<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_UNIT_DATSOURCE_UTIL
#define MAPNIK_UNIT_DATSOURCE_UTIL

#include "catch.hpp"

#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry/geometry_types.hpp>
#include <mapnik/geometry/geometry_type.hpp>

namespace {

template <typename T>
std::string vector_to_string(T const& vec)
{
    std::stringstream s;
    for (auto const& item : vec)
    {
        s << "  " << item << "\n";
    }
    return s.str();
}

template <>
std::string vector_to_string(std::vector<mapnik::attribute_descriptor> const& vec)
{
    std::stringstream s;
    for (auto const& item : vec)
    {
        s << "  " << item.get_name() << "\n";
    }
    return s.str();
}

#define REQUIRE_FIELD_NAMES(fields, names) \
    INFO("fields:\n" + vector_to_string(fields) + "names:\n" +  vector_to_string(names)); \
    REQUIRE(fields.size() == names.size()); \
    auto itr_a = fields.begin(); \
    auto const end_a = fields.end(); \
    auto itr_b = names.begin(); \
    for (; itr_a != end_a; ++itr_a, ++itr_b) \
    { \
        CHECK(itr_a->get_name() == *itr_b); \
    } \

inline void require_field_names(std::vector<mapnik::attribute_descriptor> const &fields,
                         std::initializer_list<std::string> const &names)
{
    REQUIRE_FIELD_NAMES(fields,names);
}

#define REQUIRE_FIELD_TYPES(fields, types) \
    REQUIRE(fields.size() == types.size()); \
    auto itr_a = fields.begin(); \
    auto const end_a = fields.end(); \
    auto itr_b = types.begin(); \
    for (; itr_a != end_a; ++itr_a, ++itr_b) { \
        CHECK(itr_a->get_type() == *itr_b); \
    } \

inline void require_field_types(std::vector<mapnik::attribute_descriptor> const &fields,
                         std::initializer_list<mapnik::eAttributeType> const &types)
{
    REQUIRE_FIELD_TYPES(fields, types);
}

inline mapnik::featureset_ptr all_features(mapnik::datasource_ptr ds) {
    auto fields = ds->get_descriptor().get_descriptors();
    mapnik::query query(ds->envelope());
    for (auto const &field : fields) {
        query.add_property_name(field.get_name());
    }
    return ds->features(query);
}

inline std::size_t count_features(mapnik::featureset_ptr features) {
    std::size_t count = 0;
    while (features->next()) {
        ++count;
    }
    return count;
}

using attr = std::tuple<std::string, mapnik::value>;

#define REQUIRE_ATTRIBUTES(feature, attrs) \
    REQUIRE(bool(feature)); \
    for (auto const &kv : attrs) { \
        REQUIRE(feature->has_key(std::get<0>(kv))); \
        CHECK(feature->get(std::get<0>(kv)) == std::get<1>(kv)); \
    } \

inline void require_attributes(mapnik::feature_ptr feature,
                        std::initializer_list<attr> const &attrs) {
    REQUIRE_ATTRIBUTES(feature, attrs);
}

namespace detail {
struct feature_count {
    template <typename T>
    std::size_t operator()(T const &geom) const {
        return mapnik::util::apply_visitor(*this, geom);
    }

    std::size_t operator()(mapnik::geometry::geometry_empty const &) const {
        return 0;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::point<T> const &) const {
        return 1;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::line_string<T> const &) const {
        return 1;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::polygon<T> const &) const {
        return 1;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::multi_point<T> const &mp) const {
        return mp.size();
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::multi_line_string<T> const &mls) const {
        return mls.size();
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::multi_polygon<T> const &mp) const {
        return mp.size();
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::geometry_collection<T> const &col) const {
        std::size_t sum = 0;
        for (auto const &geom : col) {
            sum += operator()(geom);
        }
        return sum;
    }
};
} // namespace detail

template <typename T>
inline std::size_t feature_count(mapnik::geometry::geometry<T> const &g) {
    return detail::feature_count()(g);
}

inline void require_geometry(mapnik::feature_ptr feature,
                      std::size_t num_parts,
                      mapnik::geometry::geometry_types type) {
    REQUIRE(bool(feature));
    CHECK(mapnik::geometry::geometry_type(feature->get_geometry()) == type);
    CHECK(feature_count(feature->get_geometry()) == num_parts);
}

inline int create_disk_index(std::string const& filename, bool silent = true)
{
    std::string cmd;
    if (std::getenv("DYLD_LIBRARY_PATH") != nullptr)
    {
        cmd += std::string("DYLD_LIBRARY_PATH=") + std::getenv("DYLD_LIBRARY_PATH") + " ";
    }
    cmd += "mapnik-index " + filename;
    if (silent)
    {
#ifndef _WINDOWS
        cmd += " 2>/dev/null";
#else
        cmd += " 2> nul";
#endif
    }
    return std::system(cmd.c_str());
}

}

#endif // MAPNIK_UNIT_DATSOURCE_UTIL
<commit_msg>add `-x3` option to `mapnik-index` to test new json parser<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_UNIT_DATSOURCE_UTIL
#define MAPNIK_UNIT_DATSOURCE_UTIL

#include "catch.hpp"

#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/geometry/geometry_types.hpp>
#include <mapnik/geometry/geometry_type.hpp>

namespace {

template <typename T>
std::string vector_to_string(T const& vec)
{
    std::stringstream s;
    for (auto const& item : vec)
    {
        s << "  " << item << "\n";
    }
    return s.str();
}

template <>
std::string vector_to_string(std::vector<mapnik::attribute_descriptor> const& vec)
{
    std::stringstream s;
    for (auto const& item : vec)
    {
        s << "  " << item.get_name() << "\n";
    }
    return s.str();
}

#define REQUIRE_FIELD_NAMES(fields, names) \
    INFO("fields:\n" + vector_to_string(fields) + "names:\n" +  vector_to_string(names)); \
    REQUIRE(fields.size() == names.size()); \
    auto itr_a = fields.begin(); \
    auto const end_a = fields.end(); \
    auto itr_b = names.begin(); \
    for (; itr_a != end_a; ++itr_a, ++itr_b) \
    { \
        CHECK(itr_a->get_name() == *itr_b); \
    } \

inline void require_field_names(std::vector<mapnik::attribute_descriptor> const &fields,
                         std::initializer_list<std::string> const &names)
{
    REQUIRE_FIELD_NAMES(fields,names);
}

#define REQUIRE_FIELD_TYPES(fields, types) \
    REQUIRE(fields.size() == types.size()); \
    auto itr_a = fields.begin(); \
    auto const end_a = fields.end(); \
    auto itr_b = types.begin(); \
    for (; itr_a != end_a; ++itr_a, ++itr_b) { \
        CHECK(itr_a->get_type() == *itr_b); \
    } \

inline void require_field_types(std::vector<mapnik::attribute_descriptor> const &fields,
                         std::initializer_list<mapnik::eAttributeType> const &types)
{
    REQUIRE_FIELD_TYPES(fields, types);
}

inline mapnik::featureset_ptr all_features(mapnik::datasource_ptr ds) {
    auto fields = ds->get_descriptor().get_descriptors();
    mapnik::query query(ds->envelope());
    for (auto const &field : fields) {
        query.add_property_name(field.get_name());
    }
    return ds->features(query);
}

inline std::size_t count_features(mapnik::featureset_ptr features) {
    std::size_t count = 0;
    while (features->next()) {
        ++count;
    }
    return count;
}

using attr = std::tuple<std::string, mapnik::value>;

#define REQUIRE_ATTRIBUTES(feature, attrs) \
    REQUIRE(bool(feature)); \
    for (auto const &kv : attrs) { \
        REQUIRE(feature->has_key(std::get<0>(kv))); \
        CHECK(feature->get(std::get<0>(kv)) == std::get<1>(kv)); \
    } \

inline void require_attributes(mapnik::feature_ptr feature,
                        std::initializer_list<attr> const &attrs) {
    REQUIRE_ATTRIBUTES(feature, attrs);
}

namespace detail {
struct feature_count {
    template <typename T>
    std::size_t operator()(T const &geom) const {
        return mapnik::util::apply_visitor(*this, geom);
    }

    std::size_t operator()(mapnik::geometry::geometry_empty const &) const {
        return 0;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::point<T> const &) const {
        return 1;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::line_string<T> const &) const {
        return 1;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::polygon<T> const &) const {
        return 1;
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::multi_point<T> const &mp) const {
        return mp.size();
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::multi_line_string<T> const &mls) const {
        return mls.size();
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::multi_polygon<T> const &mp) const {
        return mp.size();
    }

    template <typename T>
    std::size_t operator()(mapnik::geometry::geometry_collection<T> const &col) const {
        std::size_t sum = 0;
        for (auto const &geom : col) {
            sum += operator()(geom);
        }
        return sum;
    }
};
} // namespace detail

template <typename T>
inline std::size_t feature_count(mapnik::geometry::geometry<T> const &g) {
    return detail::feature_count()(g);
}

inline void require_geometry(mapnik::feature_ptr feature,
                      std::size_t num_parts,
                      mapnik::geometry::geometry_types type) {
    REQUIRE(bool(feature));
    CHECK(mapnik::geometry::geometry_type(feature->get_geometry()) == type);
    CHECK(feature_count(feature->get_geometry()) == num_parts);
}

inline int create_disk_index(std::string const& filename, bool silent = true)
{
    std::string cmd;
    if (std::getenv("DYLD_LIBRARY_PATH") != nullptr)
    {
        cmd += std::string("DYLD_LIBRARY_PATH=") + std::getenv("DYLD_LIBRARY_PATH") + " ";
    }
    cmd += "mapnik-index -x3 " + filename;
    if (silent)
    {
#ifndef _WINDOWS
        cmd += " 2>/dev/null";
#else
        cmd += " 2> nul";
#endif
    }
    return std::system(cmd.c_str());
}

}

#endif // MAPNIK_UNIT_DATSOURCE_UTIL
<|endoftext|>


<commit_before>#include "Token/Token.h"
#include "Generator/Generator.h"

#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <getopt.h>
#include <cstdio>

using namespace dale;

static const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR";

static bool
appearsToBeLib(const char *str)
{
    int len = strlen(str);
    if (len >= 2) {
        const char *end = str + (len - 2);
        if ((!strcmp(end, ".o")) || (!strcmp(end, ".a"))) {
            return true;
        }
    }
    return false;
}

static void
joinWithPrefix(std::vector<const char*> *strings, const char *prefix,
               std::string *buffer)
{
    for (std::vector<const char*>::iterator b = strings->begin(),
                                            e = strings->end();
            b != e;
            ++b) {
        buffer->append(" ");
        buffer->append(prefix);
        buffer->append(" ");
        buffer->append(*b);
    }
}

int
main(int argc, char **argv)
{
    int opt;
    char optc;

    std::vector<const char*> input_files;
    std::vector<const char*> input_link_files;
    std::vector<const char*> compile_libs;
    std::vector<const char*> run_libs;
    std::vector<const char*> include_paths;
    std::vector<const char*> run_paths;
    std::vector<const char*> bitcode_paths;
    std::vector<const char*> static_modules;
    std::vector<const char*> cto_modules;
    std::vector<const char*> module_paths;

    std::string output_path;
    const char *output_path_arg = NULL;
    const char *module_name     = NULL;

    int produce  = ASM;
    int optlevel = 0;

    int produce_set     = 0;
    int no_linking      = 0;
    int debug           = 0;
    int no_dale_stdlib  = 0;
    int no_stdlib       = 0;
    int remove_macros   = 0;
    int no_common       = 0;
    int no_strip        = 0;
    int static_mods_all = 0;
    int found_sm        = 0;
    int found_ctom      = 0;
    int enable_cto      = 0;

    int option_index         = 0;
    int forced_remove_macros = 0;

    static struct option long_options[] = {
        { "no-dale-stdlib", no_argument,       &no_dale_stdlib,  1 },
        { "no-common",      no_argument,       &no_common,       1 },
        { "no-stdlib",      no_argument,       &no_stdlib,       1 },
        { "no-strip",       no_argument,       &no_strip,        1 },
        { "static-modules", no_argument,       &static_mods_all, 1 },
        { "static-module",  required_argument, &found_sm,        1 },
        { "cto-module",     required_argument, &found_ctom,      1 },
        { "enable-cto",     no_argument,       &enable_cto,      1 },
        { 0, 0, 0, 0 }
    };

    if (argc < 2) {
        fprintf(stderr, "dalec: no input files.\n");
        exit(1);
    }

    while ((opt = getopt_long(argc, argv, options,
                              long_options, &option_index)) != -1) {
        optc = (char) opt;

        switch (optc) {
            case 'o': {
                if (output_path_arg) {
                    fprintf(stderr, "dalec: an output path has already "
                                    "been specified.\n");
                    exit(1);
                }
                output_path_arg = optarg;
                break;
            }
            case 'O': {
                optlevel = (optarg[0] - '0');
                if ((optlevel < 0) || (optlevel > 4)) {
                    fprintf(stderr, "dalec: invalid optimisation level.\n");
                    exit(1);
                }
                break;
            }
            case 's': {
                const char *type = optarg;
                if (!strcmp(type, "as")) {
                    produce = ASM;
                } else if (!strcmp(type, "ir")) {
                    produce = IR;
                } else if (!strcmp(type, "bc")) {
                    produce = BitCode;
                } else {
                    fprintf(stderr, "dalec: unrecognised output "
                            "option.\n");
                    exit(1);
                }
                produce_set = true;
                break;
            }
            case 'd': debug = 1;                                   break;
            case 'c': no_linking = 1;                              break;
            case 'r': remove_macros = 1; forced_remove_macros = 1; break;
            case 'R': remove_macros = 0; forced_remove_macros = 1; break;
            case 'I': include_paths.push_back(optarg);             break;
            case 'a': compile_libs.push_back(optarg);              break;
            case 'L': run_paths.push_back(optarg);                 break;
            case 'l': run_libs.push_back(optarg);                  break;
            case 'b': bitcode_paths.push_back(optarg);             break;
            case 'M': module_paths.push_back(optarg);              break;
            case 'm': module_name = optarg;                        break;
        };

        if (found_sm) {
            found_sm = 0;
            static_modules.push_back(optarg);
        } else if (found_ctom) {
            found_ctom = 0;
            cto_modules.push_back(optarg);
        }
    }

    /* If the user wants an executable and has not specified either
     * way with respect to removing macros, then remove macros. */
    if (!no_linking && !produce_set && !forced_remove_macros) {
        remove_macros = 1;
    }

    /* Every argument after the options is treated as an input file.
     * Input files that end with .o or .a should go straight to the
     * linker. */
    int input_file_count = argc - optind;
    for (int i = 0; i < input_file_count; ++i) {
        const char *input_file = argv[optind + i];
        if (appearsToBeLib(input_file)) {
            input_link_files.push_back(input_file);
        } else {
            input_files.push_back(input_file);
        }
    }

    if (!input_files.size()) {
        fprintf(stderr, "dalec: no input files.\n");
        exit(1);
    }

    /* Set output_path. */
    if (!no_linking) {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            if (produce == ASM) {
                output_path.append("a.out");
            } else if (produce_set) {
                output_path.append(input_files[0]);
                output_path.append(
                      (produce == IR)      ? ".ll"
                    : (produce == ASM)     ? ".s"
                    : (produce == BitCode) ? ".bc"
                                           : ".unknown"
                );
            }
        }
    } else {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            output_path.append(input_files[0]);
            output_path.append(".o");
        }
    }

    std::string compile_lib_str;
    joinWithPrefix(&compile_libs, "-l", &compile_lib_str);

    std::string include_path_str;
    joinWithPrefix(&include_paths, "-I", &include_path_str);

    std::string run_path_str;
    joinWithPrefix(&run_paths, "-L", &run_path_str);

    std::string input_file_str;
    joinWithPrefix(&input_files, " ", &input_file_str);

    std::string input_link_file_str;
    joinWithPrefix(&input_link_files, " ", &input_link_file_str);

    FILE *tempout = tmpfile();
    if (!tempout) {
        perror("Unable to open temporary output file");
        exit(1);
    }

    Generator g;
    std::vector<std::string> so_paths;

    int rest = g.run(&input_files, &bitcode_paths, tempout,
                     produce, optlevel, remove_macros,
                     module_name, no_common, &so_paths, no_strip,
                     static_mods_all, &static_modules,
                     &cto_modules, enable_cto, debug, no_dale_stdlib,
                     &compile_libs, &include_paths,
                     &module_paths);
    if (!rest) {
        exit(1);
    }

    std::string run_lib_str;
    for (std::vector<const char*>::iterator b = run_libs.begin(),
                                            e = run_libs.end();
            b != e;
            ++b) {
        run_lib_str.append(" -l ");
        run_lib_str.append(*b);
    }

    for (std::vector<std::string>::reverse_iterator b = so_paths.rbegin(),
            e = so_paths.rend();
            b != e;
            ++b) {
        input_link_file_str.append(" ");
        input_link_file_str.append((*b).c_str());
    }

    char temp_output_path[256] = "";
    strcpy(temp_output_path, output_path.c_str());
    if (!produce_set) {
        strcat(temp_output_path, ".s");
    }

    if (!rest) {
        exit(1);
    }

    if (rest) {
        fflush(tempout);
        FILE *out = fopen(temp_output_path, "w");
        fseek(tempout, 0, SEEK_SET);
        char buf[8192];
        memset(buf, 0, 8192);
        size_t bytes;
        size_t wbytes;
        while ((bytes = fread(buf, (size_t) 1, (size_t) 8192, tempout))) {
            if (ferror(tempout)) {
                perror("Unable to read output file");
                fclose(tempout);
                fclose(out);
                break;
            }
            wbytes = fwrite(buf, (size_t) 1, bytes, out);
            if (wbytes != bytes) {
                if (ferror(tempout)) {
                    perror("Unable to copy file content");
                    break;
                }
                if (ferror(out)) {
                    perror("Unable to copy file content");
                    break;
                }
            }
            if (bytes != 8192) {
                if (feof(tempout)) {
                    break;
                } else {
                    perror("Unable to copy file content");
                    break;
                }
            }
            memset(buf, 0, 8192);
        }
        fflush(tempout);
        fflush(out);
        fclose(tempout);
        fclose(out);
    }

    if (produce_set) {
        exit(0);
    }

    char final[8192] = "";
    final[0] = '\0';
    if (no_linking) {
        sprintf(final, "cc %s -c %s "
                "%s %s -o %s",
                (no_stdlib) ? "--nostdlib" : "",
                run_path_str.c_str(),
                run_lib_str.c_str(),
                temp_output_path,
                output_path.c_str());
        int res = system(final);
        if (res) {
            perror("Unable to run cc");
            fprintf(stderr, "dalec: cc failed: %d (%s)\n", res, final);
            exit(1);
        }
    } else {
        sprintf(final, "cc %s -Wl,--gc-sections %s "
                "%s %s %s -o %s",
                (no_stdlib) ? "--nostdlib" : "",
                run_path_str.c_str(),
                temp_output_path,
                input_link_file_str.c_str(),
                run_lib_str.c_str(),
                output_path.c_str());
        int res = system(final);
        if (res) {
            perror("Unable to run cc");
            fprintf(stderr, "dalec: cc failed: %d (%s)\n", res, final);
            exit(1);
        }
    }
    int rres = remove(temp_output_path);
    if (rres) {
        fprintf(stderr, "Internal error: unable to remove "
                "temporary file (%s).\n",
                temp_output_path);
    }

    return 0;
}
<commit_msg>[master] tidying<commit_after>#include "Token/Token.h"
#include "Generator/Generator.h"

#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <getopt.h>
#include <cstdio>

using namespace dale;

static const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR";
static const int COPY_SIZE = 8192;

static bool
appearsToBeLib(const char *str)
{
    int len = strlen(str);
    if (len >= 2) {
        const char *end = str + (len - 2);
        if ((!strcmp(end, ".o")) || (!strcmp(end, ".a"))) {
            return true;
        }
    }
    return false;
}

static void
joinWithPrefix(std::vector<const char*> *strings, const char *prefix,
               std::string *buffer)
{
    for (std::vector<const char*>::iterator b = strings->begin(),
                                            e = strings->end();
            b != e;
            ++b) {
        buffer->append(" ");
        buffer->append(prefix);
        buffer->append(" ");
        buffer->append(*b);
    }
}

static bool
copyFile(const char *to_path, FILE *from)
{
    FILE *to = fopen(to_path, "w");
    char buf[COPY_SIZE];
    memset(buf, 0, COPY_SIZE);
    size_t bytes;
    size_t wbytes;
    bool success = true;

    fseek(from, SEEK_SET, 0);

    while ((bytes = fread(buf, (size_t) 1, (size_t) COPY_SIZE, from))) {
        if (ferror(from)) {
            perror("Unable to read file");
            fclose(from);
            fclose(to);
            success = false;
            break;
        }
        wbytes = fwrite(buf, (size_t) 1, bytes, to);
        if (wbytes != bytes) {
            if (ferror(from)) {
                perror("Unable to copy file content");
                success = false;
                break;
            }
            if (ferror(to)) {
                perror("Unable to copy file content");
                success = false;
                break;
            }
        }
        if (bytes != COPY_SIZE) {
            if (feof(from)) {
                break;
            } else {
                perror("Unable to copy file content");
                success = false;
                break;
            }
        }
        memset(buf, 0, COPY_SIZE);
    }

    fflush(to);
    fclose(from);
    fclose(to);

    return success;
}

int
main(int argc, char **argv)
{
    int opt;
    char optc;

    std::vector<const char*> input_files;
    std::vector<const char*> input_link_files;
    std::vector<const char*> compile_libs;
    std::vector<const char*> run_libs;
    std::vector<const char*> include_paths;
    std::vector<const char*> run_paths;
    std::vector<const char*> bitcode_paths;
    std::vector<const char*> static_modules;
    std::vector<const char*> cto_modules;
    std::vector<const char*> module_paths;

    std::string output_path;
    const char *output_path_arg = NULL;
    const char *module_name     = NULL;

    int produce  = ASM;
    int optlevel = 0;

    int produce_set     = 0;
    int no_linking      = 0;
    int debug           = 0;
    int no_dale_stdlib  = 0;
    int no_stdlib       = 0;
    int remove_macros   = 0;
    int no_common       = 0;
    int no_strip        = 0;
    int static_mods_all = 0;
    int found_sm        = 0;
    int found_ctom      = 0;
    int enable_cto      = 0;

    int option_index         = 0;
    int forced_remove_macros = 0;

    static struct option long_options[] = {
        { "no-dale-stdlib", no_argument,       &no_dale_stdlib,  1 },
        { "no-common",      no_argument,       &no_common,       1 },
        { "no-stdlib",      no_argument,       &no_stdlib,       1 },
        { "no-strip",       no_argument,       &no_strip,        1 },
        { "static-modules", no_argument,       &static_mods_all, 1 },
        { "static-module",  required_argument, &found_sm,        1 },
        { "cto-module",     required_argument, &found_ctom,      1 },
        { "enable-cto",     no_argument,       &enable_cto,      1 },
        { 0, 0, 0, 0 }
    };

    if (argc < 2) {
        fprintf(stderr, "dalec: no input files.\n");
        exit(1);
    }

    while ((opt = getopt_long(argc, argv, options,
                              long_options, &option_index)) != -1) {
        optc = (char) opt;

        switch (optc) {
            case 'o': {
                if (output_path_arg) {
                    fprintf(stderr, "dalec: an output path has already "
                                    "been specified.\n");
                    exit(1);
                }
                output_path_arg = optarg;
                break;
            }
            case 'O': {
                optlevel = (optarg[0] - '0');
                if ((optlevel < 0) || (optlevel > 4)) {
                    fprintf(stderr, "dalec: invalid optimisation level.\n");
                    exit(1);
                }
                break;
            }
            case 's': {
                const char *type = optarg;
                if (!strcmp(type, "as")) {
                    produce = ASM;
                } else if (!strcmp(type, "ir")) {
                    produce = IR;
                } else if (!strcmp(type, "bc")) {
                    produce = BitCode;
                } else {
                    fprintf(stderr, "dalec: unrecognised output "
                            "option.\n");
                    exit(1);
                }
                produce_set = true;
                break;
            }
            case 'd': debug = 1;                                   break;
            case 'c': no_linking = 1;                              break;
            case 'r': remove_macros = 1; forced_remove_macros = 1; break;
            case 'R': remove_macros = 0; forced_remove_macros = 1; break;
            case 'I': include_paths.push_back(optarg);             break;
            case 'a': compile_libs.push_back(optarg);              break;
            case 'L': run_paths.push_back(optarg);                 break;
            case 'l': run_libs.push_back(optarg);                  break;
            case 'b': bitcode_paths.push_back(optarg);             break;
            case 'M': module_paths.push_back(optarg);              break;
            case 'm': module_name = optarg;                        break;
        };

        if (found_sm) {
            found_sm = 0;
            static_modules.push_back(optarg);
        } else if (found_ctom) {
            found_ctom = 0;
            cto_modules.push_back(optarg);
        }
    }

    /* If the user wants an executable and has not specified either
     * way with respect to removing macros, then remove macros. */
    if (!no_linking && !produce_set && !forced_remove_macros) {
        remove_macros = 1;
    }

    /* Every argument after the options is treated as an input file.
     * Input files that end with .o or .a should go straight to the
     * linker. */
    int input_file_count = argc - optind;
    for (int i = 0; i < input_file_count; ++i) {
        const char *input_file = argv[optind + i];
        if (appearsToBeLib(input_file)) {
            input_link_files.push_back(input_file);
        } else {
            input_files.push_back(input_file);
        }
    }

    if (!input_files.size()) {
        fprintf(stderr, "dalec: no input files.\n");
        exit(1);
    }

    /* Set output_path. */
    if (!no_linking) {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            if (produce == ASM) {
                output_path.append("a.out");
            } else if (produce_set) {
                output_path.append(input_files[0]);
                output_path.append(
                      (produce == IR)      ? ".ll"
                    : (produce == ASM)     ? ".s"
                    : (produce == BitCode) ? ".bc"
                                           : ".unknown"
                );
            }
        }
    } else {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            output_path.append(input_files[0]);
            output_path.append(".o");
        }
    }

    std::string compile_lib_str;
    joinWithPrefix(&compile_libs, "-l", &compile_lib_str);

    std::string include_path_str;
    joinWithPrefix(&include_paths, "-I", &include_path_str);

    std::string run_path_str;
    joinWithPrefix(&run_paths, "-L", &run_path_str);

    std::string input_file_str;
    joinWithPrefix(&input_files, " ", &input_file_str);

    std::string input_link_file_str;
    joinWithPrefix(&input_link_files, " ", &input_link_file_str);

    FILE *output_file = tmpfile();
    if (!output_file) {
        fprintf(stderr, "dalec: unable to open temporary output file.\n");
        exit(1);
    }
    std::vector<std::string> so_paths;
    Generator generator;

    bool generated =
        generator.run(&input_files, &bitcode_paths, output_file,
                      produce, optlevel, remove_macros,
                      module_name, no_common, &so_paths, no_strip,
                      static_mods_all, &static_modules,
                      &cto_modules, enable_cto, debug, no_dale_stdlib,
                      &compile_libs, &include_paths,
                      &module_paths);
    if (!generated) {
        exit(1);
    }
    fflush(output_file);

    std::string run_lib_str;
    joinWithPrefix(&run_libs, " -l ", &run_lib_str);

    for (std::vector<std::string>::reverse_iterator b = so_paths.rbegin(),
                                                    e = so_paths.rend();
            b != e;
            ++b) {
        input_link_file_str.append(" ");
        input_link_file_str.append((*b).c_str());
    }

    std::string intermediate_output_path = output_path;
    if (!produce_set) {
        intermediate_output_path.append(".s");
    }
    bool result = copyFile(intermediate_output_path.c_str(), output_file);
    if (!result) {
        exit(1);
    }
    if (produce_set) {
        exit(0);
    }

    char compile_cmd[8192];
    int bytes = 0;
    if (no_linking) {
        bytes = snprintf(compile_cmd, (8192 - 1),
                         "cc %s -c %s %s %s -o %s",
                         (no_stdlib) ? "--nostdlib" : "",
                         run_path_str.c_str(),
                         run_lib_str.c_str(),
                         intermediate_output_path.c_str(),
                         output_path.c_str());
    } else {
        bytes = snprintf(compile_cmd, (8192 - 1),
                         "cc %s -Wl,--gc-sections %s %s %s %s -o %s",
                         (no_stdlib) ? "--nostdlib" : "",
                         run_path_str.c_str(),
                         intermediate_output_path.c_str(),
                         input_link_file_str.c_str(),
                         run_lib_str.c_str(),
                         output_path.c_str());
    }
    if (bytes >= 8192) {
        fprintf(stderr, "dalec: cc command is too long!\n");
        exit(1);
    }

    int status = system(compile_cmd);
    if (status != 0) {
        fprintf(stderr, "dalec: cc failed.\n", res, compile_cmd);
        if (debug) {
            fprintf(stderr, "%s\n", compile_cmd);
        }
        exit(1);
    }

    status = remove(intermediate_output_path.c_str());
    if (status != 0) {
        fprintf(stderr, "dalec: unable to remove temporary file '%s'.\n",
                        intermediate_output_path.c_str());
        exit(1);
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 *   Copyright (c) 2020 Project CHIP Authors
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#include "Commands.h"

#include "Command.h"

#include <algorithm>
#include <string>

#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif

#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/ScopedBuffer.h>

void Commands::Register(const char * clusterName, commands_list commandsList)
{
    for (auto & command : commandsList)
    {
        mClusters[clusterName].push_back(std::move(command));
    }
}

int Commands::Run(int argc, char ** argv)
{
    CHIP_ERROR err = CHIP_NO_ERROR;
    chip::Controller::CommissionerInitParams initParams;
    Command * command = nullptr;
    NodeId localId;
    NodeId remoteId;

    chip::Platform::ScopedMemoryBuffer<uint8_t> noc;
    chip::Platform::ScopedMemoryBuffer<uint8_t> icac;
    chip::Platform::ScopedMemoryBuffer<uint8_t> rcac;

    err = chip::Platform::MemoryInit();
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Memory failure: %s", chip::ErrorStr(err)));

#if CHIP_DEVICE_LAYER_TARGET_LINUX && CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
    // By default, Linux device is configured as a BLE peripheral while the controller needs a BLE central.
    SuccessOrExit(err = chip::DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(/* BLE adapter ID */ 0, /* BLE central */ true));
#endif

    err = mStorage.Init();
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Storage failure: %s", chip::ErrorStr(err)));

    chip::Logging::SetLogFilter(mStorage.GetLoggingLevel());
    localId  = mStorage.GetLocalNodeId();
    remoteId = mStorage.GetRemoteNodeId();

    ChipLogProgress(Controller, "Read local id 0x" ChipLogFormatX64 ", remote id 0x" ChipLogFormatX64, ChipLogValueX64(localId),
                    ChipLogValueX64(remoteId));

    initParams.storageDelegate = &mStorage;

    err = mOpCredsIssuer.Initialize(mStorage);
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Operational Cred Issuer: %s", chip::ErrorStr(err)));

    initParams.operationalCredentialsDelegate = &mOpCredsIssuer;

    err = mController.SetUdpListenPort(mStorage.GetListenPort());
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", chip::ErrorStr(err)));

    VerifyOrExit(rcac.Alloc(chip::Controller::kMaxCHIPDERCertLength), err = CHIP_ERROR_NO_MEMORY);
    VerifyOrExit(noc.Alloc(chip::Controller::kMaxCHIPDERCertLength), err = CHIP_ERROR_NO_MEMORY);
    VerifyOrExit(icac.Alloc(chip::Controller::kMaxCHIPDERCertLength), err = CHIP_ERROR_NO_MEMORY);

    {
        chip::MutableByteSpan nocSpan(noc.Get(), chip::Controller::kMaxCHIPDERCertLength);
        chip::MutableByteSpan icacSpan(icac.Get(), chip::Controller::kMaxCHIPDERCertLength);
        chip::MutableByteSpan rcacSpan(rcac.Get(), chip::Controller::kMaxCHIPDERCertLength);

        chip::Crypto::P256Keypair ephemeralKey;
        SuccessOrExit(err = ephemeralKey.Initialize());

        // TODO - OpCreds should only be generated for pairing command
        //        store the credentials in persistent storage, and
        //        generate when not available in the storage.
        err = mOpCredsIssuer.GenerateNOCChainAfterValidation(localId, 0, ephemeralKey.Pubkey(), rcacSpan, icacSpan, nocSpan);
        SuccessOrExit(err);

        initParams.ephemeralKeypair = &ephemeralKey;
        initParams.controllerRCAC   = rcacSpan;
        initParams.controllerICAC   = icacSpan;
        initParams.controllerNOC    = nocSpan;

        err = mController.Init(initParams);
        VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", chip::ErrorStr(err)));
    }

#if CONFIG_USE_SEPARATE_EVENTLOOP
    // ServiceEvents() calls StartEventLoopTask(), which is paired with the
    // StopEventLoopTask() below.
    err = mController.ServiceEvents();
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Run Loop: %s", chip::ErrorStr(err)));
#endif // CONFIG_USE_SEPARATE_EVENTLOOP

    err = RunCommand(localId, remoteId, argc, argv, &command);
    SuccessOrExit(err);

#if !CONFIG_USE_SEPARATE_EVENTLOOP
    chip::DeviceLayer::PlatformMgr().RunEventLoop();
#endif // !CONFIG_USE_SEPARATE_EVENTLOOP

exit:
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err));
    }

#if CONFIG_USE_SEPARATE_EVENTLOOP
    chip::DeviceLayer::PlatformMgr().StopEventLoopTask();
#endif // CONFIG_USE_SEPARATE_EVENTLOOP

    if (command)
    {
        err = command->GetCommandExitStatus();
        if (err != CHIP_NO_ERROR)
        {
            ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err));
        }
    }

    if (command)
    {
        command->Shutdown();
    }

    //
    // We can call DeviceController::Shutdown() safely without grabbing the stack lock
    // since the CHIP thread and event queue have been stopped, preventing any thread
    // races.
    //
    mController.Shutdown();

    return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}

CHIP_ERROR Commands::RunCommand(NodeId localId, NodeId remoteId, int argc, char ** argv, Command ** ranCommand)
{
    CHIP_ERROR err = CHIP_NO_ERROR;
    std::map<std::string, CommandsVector>::iterator cluster;
    Command * command = nullptr;

    if (argc <= 1)
    {
        ChipLogError(chipTool, "Missing cluster name");
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    cluster = GetCluster(argv[1]);
    if (cluster == mClusters.end())
    {
        ChipLogError(chipTool, "Unknown cluster: %s", argv[1]);
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (argc <= 2)
    {
        ChipLogError(chipTool, "Missing command name");
        ShowCluster(argv[0], argv[1], cluster->second);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (!IsGlobalCommand(argv[2]))
    {
        command = GetCommand(cluster->second, argv[2]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown command: %s", argv[2]);
            ShowCluster(argv[0], argv[1], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }
    else
    {
        if (argc <= 3)
        {
            ChipLogError(chipTool, "Missing attribute name");
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }

        command = GetGlobalCommand(cluster->second, argv[2], argv[3]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown attribute: %s", argv[3]);
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }

    if (!command->InitArguments(argc - 3, &argv[3]))
    {
        ShowCommand(argv[0], argv[1], command);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    {
        Command::ExecutionContext execContext;

        execContext.commissioner  = &mController;
        execContext.opCredsIssuer = &mOpCredsIssuer;
        execContext.storage       = &mStorage;
        execContext.localId       = localId;
        execContext.remoteId      = remoteId;

        command->SetExecutionContext(execContext);
        *ranCommand = command;

        //
        // Set this to true first BEFORE we send commands to ensure we don't end
        // up in a situation where the response comes back faster than we can
        // set the variable to true, which will cause it to block indefinitely.
        //
        command->UpdateWaitForResponse(true);
#if CONFIG_USE_SEPARATE_EVENTLOOP
        chip::DeviceLayer::PlatformMgr().ScheduleWork(RunQueuedCommand, reinterpret_cast<intptr_t>(command));
        command->WaitForResponse(command->GetWaitDurationInSeconds());
#else  // CONFIG_USE_SEPARATE_EVENTLOOP
        err = command->Run();
        SuccessOrExit(err);
        command->ScheduleWaitForResponse(command->GetWaitDurationInSeconds());
#endif // CONFIG_USE_SEPARATE_EVENTLOOP
    }

exit:
    return err;
}

void Commands::RunQueuedCommand(intptr_t commandArg)
{
    auto * command = reinterpret_cast<Command *>(commandArg);
    CHIP_ERROR err = command->Run();
    if (err != CHIP_NO_ERROR)
    {
        command->SetCommandExitStatus(err);
    }
}

std::map<std::string, Commands::CommandsVector>::iterator Commands::GetCluster(std::string clusterName)
{
    for (auto & cluster : mClusters)
    {
        std::string key(cluster.first);
        std::transform(key.begin(), key.end(), key.begin(), ::tolower);
        if (key.compare(clusterName) == 0)
        {
            return mClusters.find(cluster.first);
        }
    }

    return mClusters.end();
}

Command * Commands::GetCommand(CommandsVector & commands, std::string commandName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

Command * Commands::GetGlobalCommand(CommandsVector & commands, std::string commandName, std::string attributeName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0 && attributeName.compare(command->GetAttribute()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

bool Commands::IsGlobalCommand(std::string commandName) const
{
    return commandName.compare("read") == 0 || commandName.compare("write") == 0 || commandName.compare("report") == 0;
}

void Commands::ShowClusters(std::string executable)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s cluster_name command_name [param1 param2 ...]\n", executable.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Clusters:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & cluster : mClusters)
    {
        std::string clusterName(cluster.first);
        std::transform(clusterName.begin(), clusterName.end(), clusterName.begin(),
                       [](unsigned char c) { return std::tolower(c); });
        fprintf(stderr, "  | * %-82s|\n", clusterName.c_str());
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCluster(std::string executable, std::string clusterName, CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s command_name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Commands:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    bool readCommand   = false;
    bool writeCommand  = false;
    bool reportCommand = false;
    for (auto & command : commands)
    {
        bool shouldPrint = true;

        if (IsGlobalCommand(command->GetName()))
        {
            if (strcmp(command->GetName(), "read") == 0 && readCommand == false)
            {
                readCommand = true;
            }
            else if (strcmp(command->GetName(), "write") == 0 && writeCommand == false)
            {
                writeCommand = true;
            }
            else if (strcmp(command->GetName(), "report") == 0 && reportCommand == false)
            {
                reportCommand = true;
            }
            else
            {
                shouldPrint = false;
            }
        }

        if (shouldPrint)
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetName());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowClusterAttributes(std::string executable, std::string clusterName, std::string commandName,
                                     CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s %s attribute-name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str(),
            commandName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Attributes:                                                                         |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetAttribute());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCommand(std::string executable, std::string clusterName, Command * command)
{
    fprintf(stderr, "Usage:\n");

    std::string arguments = "";
    arguments += command->GetName();

    size_t argumentsCount = command->GetArgumentsCount();
    for (size_t i = 0; i < argumentsCount; i++)
    {
        arguments += " ";
        arguments += command->GetArgumentName(i);
    }
    fprintf(stderr, "  %s %s %s\n", executable.c_str(), clusterName.c_str(), arguments.c_str());
}
<commit_msg>Don't clobber chip-tool error (#9504)<commit_after>/*
 *   Copyright (c) 2020 Project CHIP Authors
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#include "Commands.h"

#include "Command.h"

#include <algorithm>
#include <string>

#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif

#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/ScopedBuffer.h>

void Commands::Register(const char * clusterName, commands_list commandsList)
{
    for (auto & command : commandsList)
    {
        mClusters[clusterName].push_back(std::move(command));
    }
}

int Commands::Run(int argc, char ** argv)
{
    CHIP_ERROR err = CHIP_NO_ERROR;
    chip::Controller::CommissionerInitParams initParams;
    Command * command = nullptr;
    NodeId localId;
    NodeId remoteId;

    chip::Platform::ScopedMemoryBuffer<uint8_t> noc;
    chip::Platform::ScopedMemoryBuffer<uint8_t> icac;
    chip::Platform::ScopedMemoryBuffer<uint8_t> rcac;

    err = chip::Platform::MemoryInit();
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Memory failure: %s", chip::ErrorStr(err)));

#if CHIP_DEVICE_LAYER_TARGET_LINUX && CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
    // By default, Linux device is configured as a BLE peripheral while the controller needs a BLE central.
    SuccessOrExit(err = chip::DeviceLayer::Internal::BLEMgrImpl().ConfigureBle(/* BLE adapter ID */ 0, /* BLE central */ true));
#endif

    err = mStorage.Init();
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init Storage failure: %s", chip::ErrorStr(err)));

    chip::Logging::SetLogFilter(mStorage.GetLoggingLevel());
    localId  = mStorage.GetLocalNodeId();
    remoteId = mStorage.GetRemoteNodeId();

    ChipLogProgress(Controller, "Read local id 0x" ChipLogFormatX64 ", remote id 0x" ChipLogFormatX64, ChipLogValueX64(localId),
                    ChipLogValueX64(remoteId));

    initParams.storageDelegate = &mStorage;

    err = mOpCredsIssuer.Initialize(mStorage);
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Operational Cred Issuer: %s", chip::ErrorStr(err)));

    initParams.operationalCredentialsDelegate = &mOpCredsIssuer;

    err = mController.SetUdpListenPort(mStorage.GetListenPort());
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", chip::ErrorStr(err)));

    VerifyOrExit(rcac.Alloc(chip::Controller::kMaxCHIPDERCertLength), err = CHIP_ERROR_NO_MEMORY);
    VerifyOrExit(noc.Alloc(chip::Controller::kMaxCHIPDERCertLength), err = CHIP_ERROR_NO_MEMORY);
    VerifyOrExit(icac.Alloc(chip::Controller::kMaxCHIPDERCertLength), err = CHIP_ERROR_NO_MEMORY);

    {
        chip::MutableByteSpan nocSpan(noc.Get(), chip::Controller::kMaxCHIPDERCertLength);
        chip::MutableByteSpan icacSpan(icac.Get(), chip::Controller::kMaxCHIPDERCertLength);
        chip::MutableByteSpan rcacSpan(rcac.Get(), chip::Controller::kMaxCHIPDERCertLength);

        chip::Crypto::P256Keypair ephemeralKey;
        SuccessOrExit(err = ephemeralKey.Initialize());

        // TODO - OpCreds should only be generated for pairing command
        //        store the credentials in persistent storage, and
        //        generate when not available in the storage.
        err = mOpCredsIssuer.GenerateNOCChainAfterValidation(localId, 0, ephemeralKey.Pubkey(), rcacSpan, icacSpan, nocSpan);
        SuccessOrExit(err);

        initParams.ephemeralKeypair = &ephemeralKey;
        initParams.controllerRCAC   = rcacSpan;
        initParams.controllerICAC   = icacSpan;
        initParams.controllerNOC    = nocSpan;

        err = mController.Init(initParams);
        VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Commissioner: %s", chip::ErrorStr(err)));
    }

#if CONFIG_USE_SEPARATE_EVENTLOOP
    // ServiceEvents() calls StartEventLoopTask(), which is paired with the
    // StopEventLoopTask() below.
    err = mController.ServiceEvents();
    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Controller, "Init failure! Run Loop: %s", chip::ErrorStr(err)));
#endif // CONFIG_USE_SEPARATE_EVENTLOOP

    err = RunCommand(localId, remoteId, argc, argv, &command);
    SuccessOrExit(err);

#if !CONFIG_USE_SEPARATE_EVENTLOOP
    chip::DeviceLayer::PlatformMgr().RunEventLoop();
#endif // !CONFIG_USE_SEPARATE_EVENTLOOP

exit:
#if CONFIG_USE_SEPARATE_EVENTLOOP
    chip::DeviceLayer::PlatformMgr().StopEventLoopTask();
#endif // CONFIG_USE_SEPARATE_EVENTLOOP

    if ((err == CHIP_NO_ERROR) && (command != nullptr))
    {
        err = command->GetCommandExitStatus();
    }
    if (err != CHIP_NO_ERROR)
    {
        ChipLogError(chipTool, "Run command failure: %s", chip::ErrorStr(err));
    }

    if (command)
    {
        command->Shutdown();
    }

    //
    // We can call DeviceController::Shutdown() safely without grabbing the stack lock
    // since the CHIP thread and event queue have been stopped, preventing any thread
    // races.
    //
    mController.Shutdown();

    return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}

CHIP_ERROR Commands::RunCommand(NodeId localId, NodeId remoteId, int argc, char ** argv, Command ** ranCommand)
{
    CHIP_ERROR err = CHIP_NO_ERROR;
    std::map<std::string, CommandsVector>::iterator cluster;
    Command * command = nullptr;

    if (argc <= 1)
    {
        ChipLogError(chipTool, "Missing cluster name");
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    cluster = GetCluster(argv[1]);
    if (cluster == mClusters.end())
    {
        ChipLogError(chipTool, "Unknown cluster: %s", argv[1]);
        ShowClusters(argv[0]);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (argc <= 2)
    {
        ChipLogError(chipTool, "Missing command name");
        ShowCluster(argv[0], argv[1], cluster->second);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    if (!IsGlobalCommand(argv[2]))
    {
        command = GetCommand(cluster->second, argv[2]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown command: %s", argv[2]);
            ShowCluster(argv[0], argv[1], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }
    else
    {
        if (argc <= 3)
        {
            ChipLogError(chipTool, "Missing attribute name");
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }

        command = GetGlobalCommand(cluster->second, argv[2], argv[3]);
        if (command == nullptr)
        {
            ChipLogError(chipTool, "Unknown attribute: %s", argv[3]);
            ShowClusterAttributes(argv[0], argv[1], argv[2], cluster->second);
            ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
        }
    }

    if (!command->InitArguments(argc - 3, &argv[3]))
    {
        ShowCommand(argv[0], argv[1], command);
        ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
    }

    {
        Command::ExecutionContext execContext;

        execContext.commissioner  = &mController;
        execContext.opCredsIssuer = &mOpCredsIssuer;
        execContext.storage       = &mStorage;
        execContext.localId       = localId;
        execContext.remoteId      = remoteId;

        command->SetExecutionContext(execContext);
        *ranCommand = command;

        //
        // Set this to true first BEFORE we send commands to ensure we don't end
        // up in a situation where the response comes back faster than we can
        // set the variable to true, which will cause it to block indefinitely.
        //
        command->UpdateWaitForResponse(true);
#if CONFIG_USE_SEPARATE_EVENTLOOP
        chip::DeviceLayer::PlatformMgr().ScheduleWork(RunQueuedCommand, reinterpret_cast<intptr_t>(command));
        command->WaitForResponse(command->GetWaitDurationInSeconds());
#else  // CONFIG_USE_SEPARATE_EVENTLOOP
        err = command->Run();
        SuccessOrExit(err);
        command->ScheduleWaitForResponse(command->GetWaitDurationInSeconds());
#endif // CONFIG_USE_SEPARATE_EVENTLOOP
    }

exit:
    return err;
}

void Commands::RunQueuedCommand(intptr_t commandArg)
{
    auto * command = reinterpret_cast<Command *>(commandArg);
    CHIP_ERROR err = command->Run();
    if (err != CHIP_NO_ERROR)
    {
        command->SetCommandExitStatus(err);
    }
}

std::map<std::string, Commands::CommandsVector>::iterator Commands::GetCluster(std::string clusterName)
{
    for (auto & cluster : mClusters)
    {
        std::string key(cluster.first);
        std::transform(key.begin(), key.end(), key.begin(), ::tolower);
        if (key.compare(clusterName) == 0)
        {
            return mClusters.find(cluster.first);
        }
    }

    return mClusters.end();
}

Command * Commands::GetCommand(CommandsVector & commands, std::string commandName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

Command * Commands::GetGlobalCommand(CommandsVector & commands, std::string commandName, std::string attributeName)
{
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0 && attributeName.compare(command->GetAttribute()) == 0)
        {
            return command.get();
        }
    }

    return nullptr;
}

bool Commands::IsGlobalCommand(std::string commandName) const
{
    return commandName.compare("read") == 0 || commandName.compare("write") == 0 || commandName.compare("report") == 0;
}

void Commands::ShowClusters(std::string executable)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s cluster_name command_name [param1 param2 ...]\n", executable.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Clusters:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & cluster : mClusters)
    {
        std::string clusterName(cluster.first);
        std::transform(clusterName.begin(), clusterName.end(), clusterName.begin(),
                       [](unsigned char c) { return std::tolower(c); });
        fprintf(stderr, "  | * %-82s|\n", clusterName.c_str());
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCluster(std::string executable, std::string clusterName, CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s command_name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Commands:                                                                           |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    bool readCommand   = false;
    bool writeCommand  = false;
    bool reportCommand = false;
    for (auto & command : commands)
    {
        bool shouldPrint = true;

        if (IsGlobalCommand(command->GetName()))
        {
            if (strcmp(command->GetName(), "read") == 0 && readCommand == false)
            {
                readCommand = true;
            }
            else if (strcmp(command->GetName(), "write") == 0 && writeCommand == false)
            {
                writeCommand = true;
            }
            else if (strcmp(command->GetName(), "report") == 0 && reportCommand == false)
            {
                reportCommand = true;
            }
            else
            {
                shouldPrint = false;
            }
        }

        if (shouldPrint)
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetName());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowClusterAttributes(std::string executable, std::string clusterName, std::string commandName,
                                     CommandsVector & commands)
{
    fprintf(stderr, "Usage:\n");
    fprintf(stderr, "  %s %s %s attribute-name [param1 param2 ...]\n", executable.c_str(), clusterName.c_str(),
            commandName.c_str());
    fprintf(stderr, "\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    fprintf(stderr, "  | Attributes:                                                                         |\n");
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
    for (auto & command : commands)
    {
        if (commandName.compare(command->GetName()) == 0)
        {
            fprintf(stderr, "  | * %-82s|\n", command->GetAttribute());
        }
    }
    fprintf(stderr, "  +-------------------------------------------------------------------------------------+\n");
}

void Commands::ShowCommand(std::string executable, std::string clusterName, Command * command)
{
    fprintf(stderr, "Usage:\n");

    std::string arguments = "";
    arguments += command->GetName();

    size_t argumentsCount = command->GetArgumentsCount();
    for (size_t i = 0; i < argumentsCount; i++)
    {
        arguments += " ";
        arguments += command->GetArgumentName(i);
    }
    fprintf(stderr, "  %s %s %s\n", executable.c_str(), clusterName.c_str(), arguments.c_str());
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log: AliT0Preprocessor.cxx,v $
Revision 1.8  2007/12/07 15:22:51  alla
bug fixed by Alberto

Revision 1.7  2007/12/06 16:35:24  alla
new bugs fixed by Tomek

Revision 1.5  2007/11/23 19:28:52  alla
bug fixed

Version 2.1  2007/11/21
Preprocessor storing data to OCDB (T.Malkiewicz)

Version 1.1  2006/10
Preliminary test version (T.Malkiewicz)
*/
// T0 preprocessor:
// 1) takes data from DCS and passes it to the class AliTOFDataDCS
// for processing and writes the result to the Reference DB.
// 2) takes data form DAQ (both from Laser Calibration and Physics runs),
// processes it, and stores either to OCDB or to Reference DB.

#include "AliT0Preprocessor.h"
#include "AliT0DataDCS.h"
#include "AliT0CalibWalk.h"
#include "AliT0CalibTimeEq.h"

#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliCDBEntry.h"
#include "AliLog.h"

#include <TTimeStamp.h>
#include <TFile.h>
#include <TObjString.h>
#include <TNamed.h>
#include "AliT0Dqclass.h"

#include "iostream.h"

ClassImp(AliT0Preprocessor)

//____________________________________________________
AliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) :
  AliPreprocessor("T00", shuttle),
  fData(0)
{
  //constructor
  AddRunType("PHYSICS");
  AddRunType("STANDALONE");
  AddRunType("LASER");
}
//____________________________________________________

AliT0Preprocessor::~AliT0Preprocessor()
{
  //destructor
  delete fData;
  fData = 0;
}
//____________________________________________________

void AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)
{
  // Creates AliT0DataDCS object
  AliPreprocessor::Initialize(run, startTime, endTime);
  AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));
  fData = new AliT0DataDCS(fRun, fStartTime, fEndTime, GetStartTimeDCSQuery(), GetEndTimeDCSQuery());
}
//____________________________________________________

Bool_t AliT0Preprocessor::ProcessDCS(){
	// Check whether DCS should be processed or not...
	TString runType = GetRunType();
	Log(Form("ProcessDCS - RunType: %s",runType.Data()));

	if((runType == "STANDALONE")||
	   (runType == "PHYSICS")||
	   (runType == "LASER")){
	  return kFALSE;
	  //	return kTRUE;
	}else{
	return kFALSE;
	}
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessDCSDataPoints(TMap* dcsAliasMap){
	// Fills data into AliT0DataDCS object
	Log("Processing DCS DP");
	Bool_t resultDCSMap=kFALSE;
	Bool_t resultDCSStore=kFALSE;

        if(!dcsAliasMap)
        {
          Log("No DCS input data");
          return 1;
        }
        else
        {
          resultDCSMap=fData->ProcessData(*dcsAliasMap);
          if(!resultDCSMap)
          {
            Log("Error when processing DCS data");
            return 2;// return error Code for processed DCS data not stored
          }
          else
          {
            AliCDBMetaData metaDataDCS;
            metaDataDCS.SetBeamPeriod(0);
            metaDataDCS.SetResponsible("Tomasz Malkiewicz");
            metaDataDCS.SetComment("This preprocessor fills an AliTODataDCS object.");
            AliInfo("Storing DCS Data");
            resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS);
            if (!resultDCSStore)
            {
              Log("Some problems occurred while storing DCS data results in ReferenceDB");
              return 2;// return error Code for processed DCS data not stored
            }
          }
        }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessLaser(){
	// Processing data from DAQ Standalone run
  Log("Processing Laser calibration - Walk Correction");

  //Retrieve the last T0 calibration object

  Float_t parqtcold[24][2], parledold[24][2],parqtcnew[24][2], parlednew[24][2] , goodled[24][2], goodqtc[24][2];

  AliT0CalibWalk* clb=0;
  AliCDBEntry* entryCalib = GetFromOCDB("Calib", "Slewing_Walk");
  if(!entryCalib)
    Log(Form("Cannot find any AliCDBEntry for [Calib, SlewingWalk]!"));
  else {
    clb = (AliT0CalibWalk*)entryCalib->GetObject();

    for(Int_t i=0; i<24; i++)
      {
	for(Int_t ipar=0; ipar<2; ipar++)
	  {
	    parqtcold[i][ipar] = clb->GetQTCpar(i,ipar);
	    parledold[i][ipar] = clb->GetLEDpar(i, ipar);
	    goodqtc[i][ipar] = 999;
	    goodled[i][ipar] = 999;
	    //	    cout<<" old "<<i<<" "<<ipar<<" qtc "<< parqtcold[i][ipar]<<" led "<<parledold[i][ipar]<<endl;
	  }
      }
  }
  Bool_t resultLaser=kFALSE;
  //processing DAQ
  TList* list = GetFileSources(kDAQ, "LASER");
  if (list)
    {
            TIter iter(list);
            TObjString *source;
            while ((source = dynamic_cast<TObjString *> (iter.Next())))
            {
              const char *laserFile = GetFile(kDAQ, "LASER", source->GetName());
              if (laserFile)
              {
                Log(Form("File with Id LASER found in source %s!", source->GetName()));
                AliT0CalibWalk *laser = new AliT0CalibWalk();
                laser->MakeWalkCorrGraph(laserFile);
		Int_t iStore=0;
		//check difference with what was before
		if(laser && clb){
	        iStore = 1;
		  for(Int_t i=0; i<24; i++)
		    {
		      for(Int_t ifit=0; ifit<2; ifit++)
			{
			  parqtcnew[i][ifit] = laser->GetQTCpar(i,ifit);
			  if( parqtcold[i][ifit] != 0 && parqtcnew[i][ifit] !=0)
			    {
			      goodqtc[i][ifit] =
				(parqtcnew[i][ifit] - parqtcold[i][ifit])/parqtcold[i][ifit];
			      //			      cout<<"qtc "<<i<<" "<<ifit<<" "<< goodqtc[i][ifit]<<endl;
			    }
			  parlednew[i][ifit] = laser->GetLEDpar(i,ifit);
			  if(parledold[i][ifit] != 0 )
			    {
			      goodled[i][ifit]=
				(parlednew[i][ifit] - parledold[i][ifit])/parledold[i][ifit];
			      //			      cout<<"led "<<i<<" "<<ifit<<" "<< goodled[i][ifit]<<endl;
			    }
			  if(TMath::Abs(goodqtc[i][ifit])>0.1 ||
			     TMath::Abs(goodled[i][ifit])>0.1)
			    iStore = 0;
			}
		    }
		}
		AliCDBMetaData metaData;
		metaData.SetBeamPeriod(0);
                metaData.SetResponsible("Tomek&Michal");
                metaData.SetComment("Walk correction from laser runs.");
		if( iStore>0)
		  resultLaser=Store("Calib","Slewing_Walk", laser, &metaData, 0, 1);
                delete laser;
		Log(Form("resultLaser = %d",resultLaser));
              }
              else
              {
                Log(Form("Could not find file with Id LASER in source %s!", source->GetName()));
                return 1;
              }
            }
            if (!resultLaser)
            {
              Log("No Laser Data stored");
              return 3;//return error code for failure in storing Laser Data
            }
          } else {
	  	Log("No sources found for id LASER!");
		return 1;
	  }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessPhysics(){
	//Processing data from DAQ Physics run
	Log("Processing Physics");

	Bool_t resultOnline=kFALSE;
	//processing DAQ
	TList* listPhys = GetFileSources(kDAQ, "PHYSICS");
        if (listPhys)
          {
            TIter iter(listPhys);
            TObjString *sourcePhys;
            while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next())))
            {
              const char *filePhys = GetFile(kDAQ, "PHYSICS", sourcePhys->GetName());
              if (filePhys)
              {
                AliT0CalibTimeEq *online = new AliT0CalibTimeEq();
                online->Reset();
                online->ComputeOnlineParams(filePhys);
                AliCDBMetaData metaData;
                metaData.SetBeamPeriod(0);
                metaData.SetResponsible("Tomek&Michal");
                metaData.SetComment("Time equalizing result.");
                resultOnline = Store("Calib","TimeDelay", online, &metaData, 0, 1);
		Log(Form("resultOnline = %d",resultOnline));
                delete online;
              }
		else
              {
                Log(Form("Could not find file with Id PHYSICS in source %s!", sourcePhys->GetName()));
                return 1;
              }

            }
            if (!resultOnline)
            {
              Log("No Data stored");
              return 4;//return error code for failure in storing OCDB Data
            }
          } else {
	  	Log("No sources found for id PHYSICS!");
		return 1;
	  }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessCosmic(){
	//Processing data from DAQ Physics run
	Log("Processing Laser Physics");

	Bool_t resultLaserOnline=kFALSE;
	//processing DAQ
	TList* listLaser = GetFileSources(kDAQ, "COSMIC");
        if (listLaser)
          {
            TIter iter(listLaser);
            TObjString *sourceLaser;
            while ((sourceLaser = dynamic_cast<TObjString *> (iter.Next())))
            {
              const char *fileLaser = GetFile(kDAQ, "COSMIC", sourceLaser->GetName());
              if (fileLaser)
              {
                AliT0CalibTimeEq *onlineLaser = new AliT0CalibTimeEq();
                onlineLaser->Reset();
                onlineLaser->ComputeOnlineParams(fileLaser);
                AliCDBMetaData metaData;
                metaData.SetBeamPeriod(0);
                metaData.SetResponsible("Tomek&Michal");
                metaData.SetComment("Time equalizing result.");
                resultLaserOnline = Store("Calib","LaserTimeDelay", onlineLaser, &metaData, 0, 1);
		Log(Form("resultLaserOnline = %d",resultLaserOnline));
                delete onlineLaser;
              }
		else
              {
                Log(Form("Could not find file with Id COSMIC in source %s!", sourceLaser->GetName()));
                return 0;
              }

            }
            if (!resultLaserOnline)
            {
              Log("No Laser Data stored");
              return 0;//return error code for failure in storing OCDB Data
            }
          } else {
	  	Log("No sources found for id COSMIC!");
		return 0;
	  }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )
{
  // T0 preprocessor return codes:
  // return=0 : all ok
  // return=1 : no DCS input data
  // return=2 : failed to store DCS data
  // return=3 : no Laser data (Walk correction)
  // return=4 : failed to store OCDB time equalized data
  // return=5 : no DAQ input for OCDB
  // return=6 : failed to retrieve DAQ data from OCDB
  // return=7 : failed to store T0 OCDB data
	Bool_t dcsDP = ProcessDCS();
	Log(Form("dcsDP = %d",dcsDP));
        TString runType = GetRunType();
	Log(Form("RunType: %s",runType.Data()));
	//processing
 	if(runType == "STANDALONE"){
	  if(dcsDP==1){
	    Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
	    return iresultDCS;
	  }
	}
 	if(runType == "LASER"){
	  Int_t iresultLaser = ProcessLaser();
	  if(dcsDP==1){
            Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
            return iresultDCS;
          }
	  Log(Form("iresultLaser = %d",iresultLaser));
	  return iresultLaser;
	}
	else if(runType == "PHYSICS"){
	  Int_t iresultPhysics = ProcessPhysics();
	 //	 Int_t iresultCosmic = ProcessCosmic();
	  if(dcsDP==1){
	    Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
	    return iresultDCS;
	  }
	  Log(Form("iresultPhysics = %d",iresultPhysics));
	  return iresultPhysics;
	  //		Log(Form("iresultPhysics =iresultCosmic %d",iresultCosmic));
	  //	return iresultCosmic;
	}

	return 0;
}
<commit_msg>Fix compilation on mac<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log: AliT0Preprocessor.cxx,v $
Revision 1.8  2007/12/07 15:22:51  alla
bug fixed by Alberto

Revision 1.7  2007/12/06 16:35:24  alla
new bugs fixed by Tomek

Revision 1.5  2007/11/23 19:28:52  alla
bug fixed

Version 2.1  2007/11/21
Preprocessor storing data to OCDB (T.Malkiewicz)

Version 1.1  2006/10
Preliminary test version (T.Malkiewicz)
*/
// T0 preprocessor:
// 1) takes data from DCS and passes it to the class AliTOFDataDCS
// for processing and writes the result to the Reference DB.
// 2) takes data form DAQ (both from Laser Calibration and Physics runs),
// processes it, and stores either to OCDB or to Reference DB.

#include "AliT0Preprocessor.h"
#include "AliT0DataDCS.h"
#include "AliT0CalibWalk.h"
#include "AliT0CalibTimeEq.h"

#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliCDBEntry.h"
#include "AliLog.h"

#include <TTimeStamp.h>
#include <TFile.h>
#include <TObjString.h>
#include <TNamed.h>
#include "AliT0Dqclass.h"

#include "iostream"

ClassImp(AliT0Preprocessor)

//____________________________________________________
AliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) :
  AliPreprocessor("T00", shuttle),
  fData(0)
{
  //constructor
  AddRunType("PHYSICS");
  AddRunType("STANDALONE");
  AddRunType("LASER");
}
//____________________________________________________

AliT0Preprocessor::~AliT0Preprocessor()
{
  //destructor
  delete fData;
  fData = 0;
}
//____________________________________________________

void AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)
{
  // Creates AliT0DataDCS object
  AliPreprocessor::Initialize(run, startTime, endTime);
  AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));
  fData = new AliT0DataDCS(fRun, fStartTime, fEndTime, GetStartTimeDCSQuery(), GetEndTimeDCSQuery());
}
//____________________________________________________

Bool_t AliT0Preprocessor::ProcessDCS(){
	// Check whether DCS should be processed or not...
	TString runType = GetRunType();
	Log(Form("ProcessDCS - RunType: %s",runType.Data()));

	if((runType == "STANDALONE")||
	   (runType == "PHYSICS")||
	   (runType == "LASER")){
	  return kFALSE;
	  //	return kTRUE;
	}else{
	return kFALSE;
	}
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessDCSDataPoints(TMap* dcsAliasMap){
	// Fills data into AliT0DataDCS object
	Log("Processing DCS DP");
	Bool_t resultDCSMap=kFALSE;
	Bool_t resultDCSStore=kFALSE;

        if(!dcsAliasMap)
        {
          Log("No DCS input data");
          return 1;
        }
        else
        {
          resultDCSMap=fData->ProcessData(*dcsAliasMap);
          if(!resultDCSMap)
          {
            Log("Error when processing DCS data");
            return 2;// return error Code for processed DCS data not stored
          }
          else
          {
            AliCDBMetaData metaDataDCS;
            metaDataDCS.SetBeamPeriod(0);
            metaDataDCS.SetResponsible("Tomasz Malkiewicz");
            metaDataDCS.SetComment("This preprocessor fills an AliTODataDCS object.");
            AliInfo("Storing DCS Data");
            resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS);
            if (!resultDCSStore)
            {
              Log("Some problems occurred while storing DCS data results in ReferenceDB");
              return 2;// return error Code for processed DCS data not stored
            }
          }
        }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessLaser(){
	// Processing data from DAQ Standalone run
  Log("Processing Laser calibration - Walk Correction");

  //Retrieve the last T0 calibration object

  Float_t parqtcold[24][2], parledold[24][2],parqtcnew[24][2], parlednew[24][2] , goodled[24][2], goodqtc[24][2];

  AliT0CalibWalk* clb=0;
  AliCDBEntry* entryCalib = GetFromOCDB("Calib", "Slewing_Walk");
  if(!entryCalib)
    Log(Form("Cannot find any AliCDBEntry for [Calib, SlewingWalk]!"));
  else {
    clb = (AliT0CalibWalk*)entryCalib->GetObject();

    for(Int_t i=0; i<24; i++)
      {
	for(Int_t ipar=0; ipar<2; ipar++)
	  {
	    parqtcold[i][ipar] = clb->GetQTCpar(i,ipar);
	    parledold[i][ipar] = clb->GetLEDpar(i, ipar);
	    goodqtc[i][ipar] = 999;
	    goodled[i][ipar] = 999;
	    //	    cout<<" old "<<i<<" "<<ipar<<" qtc "<< parqtcold[i][ipar]<<" led "<<parledold[i][ipar]<<endl;
	  }
      }
  }
  Bool_t resultLaser=kFALSE;
  //processing DAQ
  TList* list = GetFileSources(kDAQ, "LASER");
  if (list)
    {
            TIter iter(list);
            TObjString *source;
            while ((source = dynamic_cast<TObjString *> (iter.Next())))
            {
              const char *laserFile = GetFile(kDAQ, "LASER", source->GetName());
              if (laserFile)
              {
                Log(Form("File with Id LASER found in source %s!", source->GetName()));
                AliT0CalibWalk *laser = new AliT0CalibWalk();
                laser->MakeWalkCorrGraph(laserFile);
		Int_t iStore=0;
		//check difference with what was before
		if(laser && clb){
	        iStore = 1;
		  for(Int_t i=0; i<24; i++)
		    {
		      for(Int_t ifit=0; ifit<2; ifit++)
			{
			  parqtcnew[i][ifit] = laser->GetQTCpar(i,ifit);
			  if( parqtcold[i][ifit] != 0 && parqtcnew[i][ifit] !=0)
			    {
			      goodqtc[i][ifit] =
				(parqtcnew[i][ifit] - parqtcold[i][ifit])/parqtcold[i][ifit];
			      //			      cout<<"qtc "<<i<<" "<<ifit<<" "<< goodqtc[i][ifit]<<endl;
			    }
			  parlednew[i][ifit] = laser->GetLEDpar(i,ifit);
			  if(parledold[i][ifit] != 0 )
			    {
			      goodled[i][ifit]=
				(parlednew[i][ifit] - parledold[i][ifit])/parledold[i][ifit];
			      //			      cout<<"led "<<i<<" "<<ifit<<" "<< goodled[i][ifit]<<endl;
			    }
			  if(TMath::Abs(goodqtc[i][ifit])>0.1 ||
			     TMath::Abs(goodled[i][ifit])>0.1)
			    iStore = 0;
			}
		    }
		}
		AliCDBMetaData metaData;
		metaData.SetBeamPeriod(0);
                metaData.SetResponsible("Tomek&Michal");
                metaData.SetComment("Walk correction from laser runs.");
		if( iStore>0)
		  resultLaser=Store("Calib","Slewing_Walk", laser, &metaData, 0, 1);
                delete laser;
		Log(Form("resultLaser = %d",resultLaser));
              }
              else
              {
                Log(Form("Could not find file with Id LASER in source %s!", source->GetName()));
                return 1;
              }
            }
            if (!resultLaser)
            {
              Log("No Laser Data stored");
              return 3;//return error code for failure in storing Laser Data
            }
          } else {
	  	Log("No sources found for id LASER!");
		return 1;
	  }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessPhysics(){
	//Processing data from DAQ Physics run
	Log("Processing Physics");

	Bool_t resultOnline=kFALSE;
	//processing DAQ
	TList* listPhys = GetFileSources(kDAQ, "PHYSICS");
        if (listPhys)
          {
            TIter iter(listPhys);
            TObjString *sourcePhys;
            while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next())))
            {
              const char *filePhys = GetFile(kDAQ, "PHYSICS", sourcePhys->GetName());
              if (filePhys)
              {
                AliT0CalibTimeEq *online = new AliT0CalibTimeEq();
                online->Reset();
                online->ComputeOnlineParams(filePhys);
                AliCDBMetaData metaData;
                metaData.SetBeamPeriod(0);
                metaData.SetResponsible("Tomek&Michal");
                metaData.SetComment("Time equalizing result.");
                resultOnline = Store("Calib","TimeDelay", online, &metaData, 0, 1);
		Log(Form("resultOnline = %d",resultOnline));
                delete online;
              }
		else
              {
                Log(Form("Could not find file with Id PHYSICS in source %s!", sourcePhys->GetName()));
                return 1;
              }

            }
            if (!resultOnline)
            {
              Log("No Data stored");
              return 4;//return error code for failure in storing OCDB Data
            }
          } else {
	  	Log("No sources found for id PHYSICS!");
		return 1;
	  }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::ProcessCosmic(){
	//Processing data from DAQ Physics run
	Log("Processing Laser Physics");

	Bool_t resultLaserOnline=kFALSE;
	//processing DAQ
	TList* listLaser = GetFileSources(kDAQ, "COSMIC");
        if (listLaser)
          {
            TIter iter(listLaser);
            TObjString *sourceLaser;
            while ((sourceLaser = dynamic_cast<TObjString *> (iter.Next())))
            {
              const char *fileLaser = GetFile(kDAQ, "COSMIC", sourceLaser->GetName());
              if (fileLaser)
              {
                AliT0CalibTimeEq *onlineLaser = new AliT0CalibTimeEq();
                onlineLaser->Reset();
                onlineLaser->ComputeOnlineParams(fileLaser);
                AliCDBMetaData metaData;
                metaData.SetBeamPeriod(0);
                metaData.SetResponsible("Tomek&Michal");
                metaData.SetComment("Time equalizing result.");
                resultLaserOnline = Store("Calib","LaserTimeDelay", onlineLaser, &metaData, 0, 1);
		Log(Form("resultLaserOnline = %d",resultLaserOnline));
                delete onlineLaser;
              }
		else
              {
                Log(Form("Could not find file with Id COSMIC in source %s!", sourceLaser->GetName()));
                return 0;
              }

            }
            if (!resultLaserOnline)
            {
              Log("No Laser Data stored");
              return 0;//return error code for failure in storing OCDB Data
            }
          } else {
	  	Log("No sources found for id COSMIC!");
		return 0;
	  }
	return 0;
}
//____________________________________________________

UInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )
{
  // T0 preprocessor return codes:
  // return=0 : all ok
  // return=1 : no DCS input data
  // return=2 : failed to store DCS data
  // return=3 : no Laser data (Walk correction)
  // return=4 : failed to store OCDB time equalized data
  // return=5 : no DAQ input for OCDB
  // return=6 : failed to retrieve DAQ data from OCDB
  // return=7 : failed to store T0 OCDB data
	Bool_t dcsDP = ProcessDCS();
	Log(Form("dcsDP = %d",dcsDP));
        TString runType = GetRunType();
	Log(Form("RunType: %s",runType.Data()));
	//processing
 	if(runType == "STANDALONE"){
	  if(dcsDP==1){
	    Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
	    return iresultDCS;
	  }
	}
 	if(runType == "LASER"){
	  Int_t iresultLaser = ProcessLaser();
	  if(dcsDP==1){
            Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
            return iresultDCS;
          }
	  Log(Form("iresultLaser = %d",iresultLaser));
	  return iresultLaser;
	}
	else if(runType == "PHYSICS"){
	  Int_t iresultPhysics = ProcessPhysics();
	 //	 Int_t iresultCosmic = ProcessCosmic();
	  if(dcsDP==1){
	    Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
	    return iresultDCS;
	  }
	  Log(Form("iresultPhysics = %d",iresultPhysics));
	  return iresultPhysics;
	  //		Log(Form("iresultPhysics =iresultCosmic %d",iresultCosmic));
	  //	return iresultCosmic;
	}

	return 0;
}
<|endoftext|>


<commit_before>#ifndef __CINT__
  #include <iostream.h>
  #include "AliRun.h"
  #include "AliTPCv1.h"
  #include "AliTPCv2.h"
  #include "AliTPCParam.h"

  #include "TFile.h"
  #include "TStopwatch.h"
#endif

Int_t AliTPCFindClusters(Int_t n) {
   TFile *out=TFile::Open("AliTPCclusters.root","new");
   if (!out->IsOpen()) {cerr<<"Delete old AliTPCclusters.root !\n"; return 1;}
   TFile *in=TFile::Open("rfio:galice.root");
   if (!in->IsOpen()) {cerr<<"Can't open galice.root !\n"; return 2;}

   if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
     cerr<<"gAlice have not been found on galice.root !\n";
     return 3;
   }

   TDirectory *cwd = gDirectory;

   AliTPC *TPC = (AliTPC*)gAlice->GetDetector("TPC");
   Int_t ver = TPC->IsVersion();
   cerr<<"TPC version "<<ver<<" has been found !\n";

   AliTPCParam *dig=(AliTPCParam *)in->Get("75x40_100x60");
   if (!dig) {cerr<<"TPC parameters have not been found !\n"; return 4;}

   TStopwatch timer;

   switch (ver) {
   case 1:
      cerr<<"Making clusters...\n";
      {
       AliTPCv1 &tpc=*((AliTPCv1*)TPC);
       tpc.SetParam(dig); timer.Start(); cwd->cd();
       for(Int_t i=0;i<n;i++){
         printf("Processing event %d\n",i);
         gAlice->GetEvent(i);
         tpc.Hits2Clusters(out,i);
       }
      }
      break;
   case 2:
      cerr<<"Looking for clusters...\n";
      {
	// delete gAlice; gAlice=0;
       AliTPCv2 tpc;
       tpc.SetParam(dig); timer.Start(); cwd->cd();
       for (Int_t i=0;i<n;i++){
	 printf("Processing event %d\n",i);
         tpc.Digits2Clusters(out,i);
	 //	 AliTPCclusterer::Digits2Clusters(dig, out, i);
       }
      }
      break;
   default:
      cerr<<"Invalid TPC version !\n";
      return 5;
   }

   timer.Stop(); timer.Print();

   delete gAlice; gAlice=0;

   out->Close();
   in->Close();

   return 0;
}
<commit_msg>The default number of events is set to 1<commit_after>#ifndef __CINT__
  #include <iostream.h>
  #include "AliRun.h"
  #include "AliTPCv1.h"
  #include "AliTPCv2.h"
  #include "AliTPCParam.h"

  #include "TFile.h"
  #include "TStopwatch.h"
#endif

Int_t AliTPCFindClusters(Int_t n=1) {
   TFile *out=TFile::Open("AliTPCclusters.root","new");
   if (!out->IsOpen()) {cerr<<"Delete old AliTPCclusters.root !\n"; return 1;}
   TFile *in=TFile::Open("rfio:galice.root");
   if (!in->IsOpen()) {cerr<<"Can't open galice.root !\n"; return 2;}

   if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
     cerr<<"gAlice have not been found on galice.root !\n";
     return 3;
   }

   TDirectory *cwd = gDirectory;

   AliTPC *TPC = (AliTPC*)gAlice->GetDetector("TPC");
   Int_t ver = TPC->IsVersion();
   cerr<<"TPC version "<<ver<<" has been found !\n";

   AliTPCParam *dig=(AliTPCParam *)in->Get("75x40_100x60");
   if (!dig) {cerr<<"TPC parameters have not been found !\n"; return 4;}

   TStopwatch timer;

   switch (ver) {
   case 1:
      cerr<<"Making clusters...\n";
      {
       AliTPCv1 &tpc=*((AliTPCv1*)TPC);
       tpc.SetParam(dig); timer.Start(); cwd->cd();
       for(Int_t i=0;i<n;i++){
         printf("Processing event %d\n",i);
         gAlice->GetEvent(i);
         tpc.Hits2Clusters(out,i);
       }
      }
      break;
   case 2:
      cerr<<"Looking for clusters...\n";
      {
	// delete gAlice; gAlice=0;
       AliTPCv2 tpc;
       tpc.SetParam(dig); timer.Start(); cwd->cd();
       for (Int_t i=0;i<n;i++){
	 printf("Processing event %d\n",i);
         tpc.Digits2Clusters(out,i);
	 //	 AliTPCclusterer::Digits2Clusters(dig, out, i);
       }
      }
      break;
   default:
      cerr<<"Invalid TPC version !\n";
      return 5;
   }

   timer.Stop(); timer.Print();

   delete gAlice; gAlice=0;

   out->Close();
   in->Close();

   return 0;
}
<|endoftext|>