<commit_before>#include <stdio.h>
#include <string.h>

#include <string>
#include <jvmti.h>

#include "globals.h"
#include "profiler.h"

static ConfigurationOptions* CONFIGURATION = new ConfigurationOptions();
static Profiler* prof;

// This has to be here, or the VM turns off class loading events.
// And AsyncGetCallTrace needs class loading events to be turned on!
void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
        jclass klass) {
    IMPLICITLY_USE(jvmti_env);
    IMPLICITLY_USE(jni_env);
    IMPLICITLY_USE(thread);
    IMPLICITLY_USE(klass);
}

// Calls GetClassMethods on a given class to force the creation of
// jmethodIDs of it.
void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) {
    jint method_count;
    JvmtiScopedPtr<jmethodID> methods(jvmti);
    jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef());
    if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) {
        // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may
        // be loaded but not prepared at this point.
        JvmtiScopedPtr<char> ksig(jvmti);
        JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL)));
        logError("Failed to create method IDs for methods in class %s with error %d ",
                 ksig.Get(), e);
    }
}

void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jniEnv, jthread thread) {
    IMPLICITLY_USE(thread);
    // Forces the creation of jmethodIDs of the classes that had already
    // been loaded (eg java.lang.Object, java.lang.ClassLoader) and
    // OnClassPrepare() misses.
    jint class_count;
    JvmtiScopedPtr<jclass> classes(jvmti);
    JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef())));
    jclass *classList = classes.Get();
    for (int i = 0; i < class_count; ++i) {
        jclass klass = classList[i];
        CreateJMethodIDsForClass(jvmti, klass);
    }
    if (CONFIGURATION->start)
        prof->start(jniEnv);
}

void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env,
        jthread thread, jclass klass) {
    IMPLICITLY_USE(jni_env);
    IMPLICITLY_USE(thread);
    // We need to do this to "prime the pump", as it were -- make sure
    // that all of the methodIDs have been initialized internally, for
    // AsyncGetCallTrace.  I imagine it slows down class loading a mite,
    // but honestly, how fast does class loading have to be?
    CreateJMethodIDsForClass(jvmti_env, klass);
}

void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) {
    IMPLICITLY_USE(jvmti_env);
    IMPLICITLY_USE(jni_env);

    prof->stop();
}

static bool PrepareJvmti(jvmtiEnv *jvmti) {
    // Set the list of permissions to do the various internal VM things
    // we want to do.
    jvmtiCapabilities caps;

    memset(&caps, 0, sizeof(caps));
    caps.can_generate_all_class_hook_events = 1;

    caps.can_get_source_file_name = 1;
    caps.can_get_line_numbers = 1;
    caps.can_get_bytecodes = 1;
    caps.can_get_constant_pool = 1;

    jvmtiCapabilities all_caps;
    int error;

    if (JVMTI_ERROR_NONE ==
            (error = jvmti->GetPotentialCapabilities(&all_caps))) {
        // This makes sure that if we need a capability, it is one of the
        // potential capabilities.  The technique isn't wonderful, but it
        // is compact and as likely to be compatible between versions as
        // anything else.
        char *has = reinterpret_cast<char *>(&all_caps);
        const char *should_have = reinterpret_cast<const char *>(&caps);
        for (int i = 0; i < sizeof(all_caps); i++) {
            if ((should_have[i] != 0) && (has[i] == 0)) {
                return false;
            }
        }

        // This adds the capabilities.
        if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) {
            logError("Failed to add capabilities with error %d\n", error);
            return false;
        }
    }
    return true;
}

static bool RegisterJvmti(jvmtiEnv *jvmti) {
    // Create the list of callbacks to be called on given events.
    jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks();
    memset(callbacks, 0, sizeof(jvmtiEventCallbacks));

    callbacks->VMInit = &OnVMInit;
    callbacks->VMDeath = &OnVMDeath;

    callbacks->ClassLoad = &OnClassLoad;
    callbacks->ClassPrepare = &OnClassPrepare;

    JVMTI_ERROR_1(
            (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))),
            false);

    jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE,
            JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT};

    size_t num_events = sizeof(events) / sizeof(jvmtiEvent);

    // Enable the callbacks to be triggered when the events occur.
    // Events are enumerated in jvmstatagent.h
    for (int i = 0; i < num_events; i++) {
        JVMTI_ERROR_1(
                (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)),
                false);
    }

    return true;
}

static void parseArguments(char *options, ConfigurationOptions &configuration) {
    configuration.initializeDefaults();
    char* next = options;
    for (char *key = options; next != NULL; key = next + 1) {
        char *value = strchr(key, '=');
        next = strchr(key, ',');
        if (value == NULL) {
            logError("No value for key %s\n", key);
            continue;
        } else {
            value++;
            if (strstr(key, "intervalMin") == key) {
                configuration.samplingIntervalMin = atoi(value);
            } else if (strstr(key, "intervalMax") == key) {
                configuration.samplingIntervalMax = atoi(value);
            } else if (strstr(key, "interval") == key) {
                configuration.samplingIntervalMin = configuration.samplingIntervalMax = atoi(value);
            } else if (strstr(key, "logPath") == key) {
                size_t  size = (next == 0) ? strlen(key) : (size_t) (next - value);
                configuration.logFilePath = (char*) malloc(size * sizeof(char));
                strncpy(configuration.logFilePath, value, size);
            } else if (strstr(key, "start") == key) {
                configuration.start = atoi(value);
            } else {
                logError("Unknown configuration option: %s\n", key);
            }
        }
    }
}

AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
    IMPLICITLY_USE(reserved);
    int err;
    jvmtiEnv *jvmti;
    parseArguments(options, *CONFIGURATION);

    if ((err = (jvm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) !=
            JNI_OK) {
        logError("JVMTI initialisation Error %d\n", err);
        return 1;
    }

    /*
      JNIEnv *jniEnv;
      if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jniEnv),
      JNI_VERSION_1_6))) != JNI_OK) {
        logError("JNI Error %d\n", err);
        return 1;
      }
      */

    if (!PrepareJvmti(jvmti)) {
        logError("Failed to initialize JVMTI.  Continuing...\n");
        return 0;
    }

    if (!RegisterJvmti(jvmti)) {
        logError("Failed to enable JVMTI events.  Continuing...\n");
        // We fail hard here because we may have failed in the middle of
        // registering callbacks, which will leave the system in an
        // inconsistent state.
        return 1;
    }

    Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace"));

    prof = new Profiler(jvm, jvmti, CONFIGURATION);

    return 0;
}

AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) {
    IMPLICITLY_USE(vm);
}

void bootstrapHandle(int signum, siginfo_t *info, void *context) {
    prof->handle(signum, info, context);
}

void logError(const char *__restrict format, ...) {
    va_list arg;

    va_start(arg, format);
    fprintf(stderr, format, arg);
    va_end(arg);
}

Profiler *getProfiler() {
    return prof;
}
<commit_msg>Use vprintf for logError<commit_after>#include <stdio.h>
#include <string.h>

#include <string>
#include <jvmti.h>

#include "globals.h"
#include "profiler.h"

static ConfigurationOptions* CONFIGURATION = new ConfigurationOptions();
static Profiler* prof;

// This has to be here, or the VM turns off class loading events.
// And AsyncGetCallTrace needs class loading events to be turned on!
void JNICALL OnClassLoad(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread,
        jclass klass) {
    IMPLICITLY_USE(jvmti_env);
    IMPLICITLY_USE(jni_env);
    IMPLICITLY_USE(thread);
    IMPLICITLY_USE(klass);
}

// Calls GetClassMethods on a given class to force the creation of
// jmethodIDs of it.
void CreateJMethodIDsForClass(jvmtiEnv *jvmti, jclass klass) {
    jint method_count;
    JvmtiScopedPtr<jmethodID> methods(jvmti);
    jvmtiError e = jvmti->GetClassMethods(klass, &method_count, methods.GetRef());
    if (e != JVMTI_ERROR_NONE && e != JVMTI_ERROR_CLASS_NOT_PREPARED) {
        // JVMTI_ERROR_CLASS_NOT_PREPARED is okay because some classes may
        // be loaded but not prepared at this point.
        JvmtiScopedPtr<char> ksig(jvmti);
        JVMTI_ERROR((jvmti->GetClassSignature(klass, ksig.GetRef(), NULL)));
        logError("Failed to create method IDs for methods in class %s with error %d ",
                 ksig.Get(), e);
    }
}

void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *jniEnv, jthread thread) {
    IMPLICITLY_USE(thread);
    // Forces the creation of jmethodIDs of the classes that had already
    // been loaded (eg java.lang.Object, java.lang.ClassLoader) and
    // OnClassPrepare() misses.
    jint class_count;
    JvmtiScopedPtr<jclass> classes(jvmti);
    JVMTI_ERROR((jvmti->GetLoadedClasses(&class_count, classes.GetRef())));
    jclass *classList = classes.Get();
    for (int i = 0; i < class_count; ++i) {
        jclass klass = classList[i];
        CreateJMethodIDsForClass(jvmti, klass);
    }
    if (CONFIGURATION->start)
        prof->start(jniEnv);
}

void JNICALL OnClassPrepare(jvmtiEnv *jvmti_env, JNIEnv *jni_env,
        jthread thread, jclass klass) {
    IMPLICITLY_USE(jni_env);
    IMPLICITLY_USE(thread);
    // We need to do this to "prime the pump", as it were -- make sure
    // that all of the methodIDs have been initialized internally, for
    // AsyncGetCallTrace.  I imagine it slows down class loading a mite,
    // but honestly, how fast does class loading have to be?
    CreateJMethodIDsForClass(jvmti_env, klass);
}

void JNICALL OnVMDeath(jvmtiEnv *jvmti_env, JNIEnv *jni_env) {
    IMPLICITLY_USE(jvmti_env);
    IMPLICITLY_USE(jni_env);

    prof->stop();
}

static bool PrepareJvmti(jvmtiEnv *jvmti) {
    // Set the list of permissions to do the various internal VM things
    // we want to do.
    jvmtiCapabilities caps;

    memset(&caps, 0, sizeof(caps));
    caps.can_generate_all_class_hook_events = 1;

    caps.can_get_source_file_name = 1;
    caps.can_get_line_numbers = 1;
    caps.can_get_bytecodes = 1;
    caps.can_get_constant_pool = 1;

    jvmtiCapabilities all_caps;
    int error;

    if (JVMTI_ERROR_NONE ==
            (error = jvmti->GetPotentialCapabilities(&all_caps))) {
        // This makes sure that if we need a capability, it is one of the
        // potential capabilities.  The technique isn't wonderful, but it
        // is compact and as likely to be compatible between versions as
        // anything else.
        char *has = reinterpret_cast<char *>(&all_caps);
        const char *should_have = reinterpret_cast<const char *>(&caps);
        for (int i = 0; i < sizeof(all_caps); i++) {
            if ((should_have[i] != 0) && (has[i] == 0)) {
                return false;
            }
        }

        // This adds the capabilities.
        if ((error = jvmti->AddCapabilities(&caps)) != JVMTI_ERROR_NONE) {
            logError("Failed to add capabilities with error %d\n", error);
            return false;
        }
    }
    return true;
}

static bool RegisterJvmti(jvmtiEnv *jvmti) {
    // Create the list of callbacks to be called on given events.
    jvmtiEventCallbacks *callbacks = new jvmtiEventCallbacks();
    memset(callbacks, 0, sizeof(jvmtiEventCallbacks));

    callbacks->VMInit = &OnVMInit;
    callbacks->VMDeath = &OnVMDeath;

    callbacks->ClassLoad = &OnClassLoad;
    callbacks->ClassPrepare = &OnClassPrepare;

    JVMTI_ERROR_1(
            (jvmti->SetEventCallbacks(callbacks, sizeof(jvmtiEventCallbacks))),
            false);

    jvmtiEvent events[] = {JVMTI_EVENT_CLASS_LOAD, JVMTI_EVENT_CLASS_PREPARE,
            JVMTI_EVENT_VM_DEATH, JVMTI_EVENT_VM_INIT};

    size_t num_events = sizeof(events) / sizeof(jvmtiEvent);

    // Enable the callbacks to be triggered when the events occur.
    // Events are enumerated in jvmstatagent.h
    for (int i = 0; i < num_events; i++) {
        JVMTI_ERROR_1(
                (jvmti->SetEventNotificationMode(JVMTI_ENABLE, events[i], NULL)),
                false);
    }

    return true;
}

static void parseArguments(char *options, ConfigurationOptions &configuration) {
    configuration.initializeDefaults();
    char* next = options;
    for (char *key = options; next != NULL; key = next + 1) {
        char *value = strchr(key, '=');
        next = strchr(key, ',');
        if (value == NULL) {
            logError("No value for key %s\n", key);
            continue;
        } else {
            value++;
            if (strstr(key, "intervalMin") == key) {
                configuration.samplingIntervalMin = atoi(value);
            } else if (strstr(key, "intervalMax") == key) {
                configuration.samplingIntervalMax = atoi(value);
            } else if (strstr(key, "interval") == key) {
                configuration.samplingIntervalMin = configuration.samplingIntervalMax = atoi(value);
            } else if (strstr(key, "logPath") == key) {
                size_t  size = (next == 0) ? strlen(key) : (size_t) (next - value);
                configuration.logFilePath = (char*) malloc(size * sizeof(char));
                strncpy(configuration.logFilePath, value, size);
            } else if (strstr(key, "start") == key) {
                configuration.start = atoi(value);
            } else {
                logError("Unknown configuration option: %s\n", key);
            }
        }
    }
}

AGENTEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
    IMPLICITLY_USE(reserved);
    int err;
    jvmtiEnv *jvmti;
    parseArguments(options, *CONFIGURATION);

    if ((err = (jvm->GetEnv(reinterpret_cast<void **>(&jvmti), JVMTI_VERSION))) !=
            JNI_OK) {
        logError("JVMTI initialisation Error %d\n", err);
        return 1;
    }

    /*
      JNIEnv *jniEnv;
      if ((err = (vm->GetEnv(reinterpret_cast<void **>(&jniEnv),
      JNI_VERSION_1_6))) != JNI_OK) {
        logError("JNI Error %d\n", err);
        return 1;
      }
      */

    if (!PrepareJvmti(jvmti)) {
        logError("Failed to initialize JVMTI.  Continuing...\n");
        return 0;
    }

    if (!RegisterJvmti(jvmti)) {
        logError("Failed to enable JVMTI events.  Continuing...\n");
        // We fail hard here because we may have failed in the middle of
        // registering callbacks, which will leave the system in an
        // inconsistent state.
        return 1;
    }

    Asgct::SetAsgct(Accessors::GetJvmFunction<ASGCTType>("AsyncGetCallTrace"));

    prof = new Profiler(jvm, jvmti, CONFIGURATION);

    return 0;
}

AGENTEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) {
    IMPLICITLY_USE(vm);
}

void bootstrapHandle(int signum, siginfo_t *info, void *context) {
    prof->handle(signum, info, context);
}

void logError(const char *__restrict format, ...) {
    va_list arg;

    va_start(arg, format);
    vfprintf(stderr, format, arg);
    va_end(arg);
}

Profiler *getProfiler() {
    return prof;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011 Matt Fichman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "Environment.hpp"
#include "Parser.hpp"
#include "SemanticAnalyzer.hpp"
#include "BasicBlockGenerator.hpp"
#include "RegisterAllocator.hpp"
#include "Intel64CodeGenerator.hpp"
#include "BasicBlockPrinter.hpp"
#include "DeadCodeEliminator.hpp"
#include "CopyPropagator.hpp"
#include "TreePrinter.hpp"
#include "Machine.hpp"
#include "Options.hpp"

#include <iostream>

int main(int argc, char** argv) {
    // Create a new empty environment to store the AST and symbols tables, and
    // set the options for compilation.
    Environment::Ptr env(new Environment());
    Options(env, argc, argv);

    // Run the compiler.  Output to a temporary file if the compiler will
    // continue on to another stage; otherwise, output the file directly.
    Parser::Ptr parser(new Parser(env));
    SemanticAnalyzer::Ptr checker(new SemanticAnalyzer(env));
    if (env->dump_ast()) {
        Stream::Ptr out(new Stream(env->output()));
        TreePrinter::Ptr print(new TreePrinter(env, out));
        return env->errors() ? 0 : 1;
    }
    if (env->errors()) { return 1; }

    Machine::Ptr machine = Machine::intel64();
    BasicBlockGenerator::Ptr generator(new BasicBlockGenerator(env, machine));
    if (env->optimize()) {
        CopyPropagator::Ptr copy(new CopyPropagator(env));
        DeadCodeEliminator::Ptr opt(new DeadCodeEliminator(env, machine));
    }
    RegisterAllocator::Ptr alloc(new RegisterAllocator(env, machine));
    if (env->dump_ir()) {
        Stream::Ptr out(new Stream(env->output()));
        BasicBlockPrinter::Ptr print(new BasicBlockPrinter(env, machine, out));
        return 0;
    }

    std::string asm_file = env->assemble() ? tmpnam(0) : env->output();
    Stream::Ptr out(new Stream(asm_file));
    Intel64CodeGenerator::Ptr codegen(new Intel64CodeGenerator(env, out));
    if (!env->assemble()) { return 0; }

    // Run the assembler.  Output to a non-temp file if the compiler will stop
    // at the assembly stage
    std::string obj_file = env->link() ? tmpnam(0) : env->output();
    std::stringstream ss;
#if defined(WINDOWS)
    ss << "nasm -fobj64 " << asm_file << " -o " << obj_file;
#elif defined(LINUX)
    ss << "nasm -felf64 " << asm_file << " -o " << obj_file;
#elif defined(DARWIN)
    ss << "nasm -fmacho64 " << asm_file << " -o " << obj_file;
#endif
    system(ss.str().c_str());
    ss.str("");

    if (!env->link()) { return 0; }

    // Run the linker.  Always output to the given output file name.
    std::string exe_file = env->output();
#if defined(WINDOWS)
    ss << "link.exe " << obj_file << " /OUT:" << exe_file;
#elif defined(LINUX)
    ss << "gcc -m64 " << obj_file << " -o " << exe_file;
#elif defined(DARWIN)
    ss << "gcc " << obj_file << " -o " << exe_file;
#endif
    for (int i = 0; i < env->libs(); i++) {
#ifdef WINDOWS
        ss << env->lib(i) << ".lib";
#else
        ss << " -l" << env->lib(i);
#endif
    }
    for (int i = 0; i < env->includes(); i++) {
        if (File::is_dir(env->include(i))) {
#ifdef WINDOWS
            ss << "/L:" << env->include(i);
#else
            ss << " -L" << env->include(i);
#endif
        }
    }

    system(ss.str().c_str());

    return 0;
}
<commit_msg>Another fix for the front end<commit_after>/*
 * Copyright (c) 2011 Matt Fichman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "Environment.hpp"
#include "Parser.hpp"
#include "SemanticAnalyzer.hpp"
#include "BasicBlockGenerator.hpp"
#include "RegisterAllocator.hpp"
#include "Intel64CodeGenerator.hpp"
#include "BasicBlockPrinter.hpp"
#include "DeadCodeEliminator.hpp"
#include "CopyPropagator.hpp"
#include "TreePrinter.hpp"
#include "Machine.hpp"
#include "Options.hpp"

#include <iostream>

int main(int argc, char** argv) {
    // Create a new empty environment to store the AST and symbols tables, and
    // set the options for compilation.
    Environment::Ptr env(new Environment());
    Options(env, argc, argv);

    // Run the compiler.  Output to a temporary file if the compiler will
    // continue on to another stage; otherwise, output the file directly.
    Parser::Ptr parser(new Parser(env));
    SemanticAnalyzer::Ptr checker(new SemanticAnalyzer(env));
    if (env->dump_ast()) {
        Stream::Ptr out(new Stream(env->output()));
        TreePrinter::Ptr print(new TreePrinter(env, out));
        return env->errors() ? 0 : 1;
    }
    if (env->errors()) { return 1; }

    Machine::Ptr machine = Machine::intel64();
    BasicBlockGenerator::Ptr generator(new BasicBlockGenerator(env, machine));
    if (env->optimize()) {
        CopyPropagator::Ptr copy(new CopyPropagator(env));
        DeadCodeEliminator::Ptr opt(new DeadCodeEliminator(env, machine));
    }
    RegisterAllocator::Ptr alloc(new RegisterAllocator(env, machine));
    if (env->dump_ir()) {
        Stream::Ptr out(new Stream(env->output()));
        BasicBlockPrinter::Ptr print(new BasicBlockPrinter(env, machine, out));
        return 0;
    }

    std::string asm_file = env->assemble() ? tmpnam(0) : env->output();
    Stream::Ptr out(new Stream(asm_file));
    Intel64CodeGenerator::Ptr codegen(new Intel64CodeGenerator(env, out));
    if (!env->assemble()) { return 0; }

    // Run the assembler.  Output to a non-temp file if the compiler will stop
    // at the assembly stage
    std::string obj_file = env->link() ? tmpnam(0) : env->output();

    std::stringstream ss;
#if defined(WINDOWS)
    ss << "nasm -fobj64 " << asm_file << " -o " << obj_file;
#elif defined(LINUX)
    ss << "nasm -felf64 " << asm_file << " -o " << obj_file;
#elif defined(DARWIN)
    ss << "nasm -fmacho64 " << asm_file << " -o " << obj_file;
#endif
    system(ss.str().c_str());
    ss.str("");

    if (!env->link()) { return 0; }

    // Run the linker.  Always output to the given output file name.
    std::string exe_file = env->output() == "-" ? "out" : env->output();
#if defined(WINDOWS)
    ss << "link.exe " << obj_file << " /OUT:" << exe_file << ".exe";
#elif defined(LINUX)
    ss << "gcc -m64 " << obj_file << " -o " << exe_file;
#elif defined(DARWIN)
    ss << "gcc " << obj_file << " -o " << exe_file;
#endif
    for (int i = 0; i < env->libs(); i++) {
#ifdef WINDOWS
        ss << env->lib(i) << ".lib";
#else
        ss << " -l" << env->lib(i);
#endif
    }
    for (int i = 0; i < env->includes(); i++) {
        if (File::is_dir(env->include(i))) {
#ifdef WINDOWS
            ss << "/L:" << env->include(i);
#else
            ss << " -L" << env->include(i);
#endif
        }
    }

    system(ss.str().c_str());

    return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////

#include "HttpResponse.h"

#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>

#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackDumper.h"
#include "Basics/tri-strings.h"
#include "Meta/conversion.h"
#include "Rest/GeneralRequest.h"

using namespace arangodb;
using namespace arangodb::basics;

bool HttpResponse::HIDE_PRODUCT_HEADER = false;

HttpResponse::HttpResponse(ResponseCode code)
    : GeneralResponse(code),
      _isHeadResponse(false),
      _body(TRI_UNKNOWN_MEM_ZONE, false),
      _bodySize(0) {
  _generateBody = false;
  _contentType = ContentType::TEXT;
  _connectionType = rest::CONNECTION_KEEP_ALIVE;
  if (_body.c_str() == nullptr) {
    // no buffer could be reserved. out of memory!
    THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
  }
}

void HttpResponse::reset(ResponseCode code) {
  _responseCode = code;
  _headers.clear();
  _connectionType = rest::CONNECTION_KEEP_ALIVE;
  _contentType = ContentType::TEXT;
  _isHeadResponse = false;
  _body.clear();
  _bodySize = 0;
}

void HttpResponse::setCookie(std::string const& name, std::string const& value,
                             int lifeTimeSeconds, std::string const& path,
                             std::string const& domain, bool secure,
                             bool httpOnly) {
  std::unique_ptr<StringBuffer> buffer =
      std::make_unique<StringBuffer>(TRI_UNKNOWN_MEM_ZONE);

  std::string tmp = StringUtils::trim(name);
  buffer->appendText(tmp);
  buffer->appendChar('=');

  tmp = StringUtils::urlEncode(value);
  buffer->appendText(tmp);

  if (lifeTimeSeconds != 0) {
    time_t rawtime;

    time(&rawtime);
    if (lifeTimeSeconds > 0) {
      rawtime += lifeTimeSeconds;
    } else {
      rawtime = 1;
    }

    if (rawtime > 0) {
      struct tm* timeinfo;
      char buffer2[80];

      timeinfo = gmtime(&rawtime);
      strftime(buffer2, 80, "%a, %d-%b-%Y %H:%M:%S %Z", timeinfo);
      buffer->appendText(TRI_CHAR_LENGTH_PAIR("; expires="));
      buffer->appendText(buffer2);
    }
  }

  if (!path.empty()) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; path="));
    buffer->appendText(path);
  }

  if (!domain.empty()) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; domain="));
    buffer->appendText(domain);
  }

  if (secure) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; secure"));
  }

  if (httpOnly) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; HttpOnly"));
  }

  _cookies.emplace_back(buffer->c_str());
}

void HttpResponse::headResponse(size_t size) {
  _body.clear();
  _isHeadResponse = true;
  _bodySize = size;
}

size_t HttpResponse::bodySize() const {
  if (_isHeadResponse) {
    return _bodySize;
  }
  return _body.length();
}

void HttpResponse::writeHeader(StringBuffer* output) {
  output->appendText(TRI_CHAR_LENGTH_PAIR("HTTP/1.1 "));
  output->appendText(responseString(_responseCode));
  output->appendText("\r\n", 2);

  bool seenServerHeader = false;
  bool seenConnectionHeader = false;
  bool seenTransferEncodingHeader = false;
  std::string transferEncoding;

  for (auto const& it : _headers) {
    std::string const& key = it.first;
    size_t const keyLength = key.size();

    // ignore content-length
    if (keyLength == 14 && key[0] == 'c' &&
        memcmp(key.c_str(), "content-length", keyLength) == 0) {
      continue;
    }

    // save transfer encoding
    if (keyLength == 17 && key[0] == 't' &&
        memcmp(key.c_str(), "transfer-encoding", keyLength) == 0) {
      seenTransferEncodingHeader = true;
      transferEncoding = it.second;
      continue;
    }

    if (keyLength == 6 && key[0] == 's' &&
        memcmp(key.c_str(), "server", keyLength) == 0) {
      // this ensures we don't print two "Server" headers
      seenServerHeader = true;
      // go on and use the user-defined "Server" header value
    } else if (keyLength == 10 && key[0] == 'c' &&
               memcmp(key.c_str(), "connection", keyLength) == 0) {
      // this ensures we don't print two "Connection" headers
      seenConnectionHeader = true;
      // go on and use the user-defined "Connection" header value
    }

    // reserve enough space for header name + ": " + value + "\r\n"
    if (output->reserve(keyLength + 2 + it.second.size() + 2) !=
        TRI_ERROR_NO_ERROR) {
      THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
    }

    char const* p = key.c_str();
    char const* end = p + keyLength;
    int capState = 1;

    while (p < end) {
      if (capState == 1) {
        // upper case
        output->appendCharUnsafe(::toupper(*p));
        capState = 0;
      } else if (capState == 0) {
        // normal case
        output->appendCharUnsafe(::tolower(*p));
        if (*p == '-') {
          capState = 1;
        } else if (*p == ':') {
          capState = 2;
        }
      } else {
        // output as is
        output->appendCharUnsafe(*p);
      }
      ++p;
    }

    output->appendTextUnsafe(": ", 2);
    output->appendTextUnsafe(it.second);
    output->appendTextUnsafe("\r\n", 2);
  }

  // add "Server" response header
  if (!seenServerHeader && !HIDE_PRODUCT_HEADER) {
    output->appendText("Server: ArangoDB\r\n");
  }

  // add "Connection" response header
  if (!seenConnectionHeader) {
    switch (_connectionType) {
      case rest::ConnectionType::CONNECTION_KEEP_ALIVE:
        output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Keep-Alive\r\n"));
        break;
      case rest::ConnectionType::CONNECTION_CLOSE:
        output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Close\r\n"));
        break;
      case rest::ConnectionType::CONNECTION_NONE:
        output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: \r\n"));
        break;
    }
  }

  // add "Content-Type" header
  switch (_contentType) {
    case ContentType::UNSET:
    case ContentType::JSON:
      output->appendText(TRI_CHAR_LENGTH_PAIR(
          "Content-Type: application/json; charset=utf-8\r\n"));
      break;
    case ContentType::VPACK:
      output->appendText(
          TRI_CHAR_LENGTH_PAIR("Content-Type: application/x-velocypack\r\n"));
      break;
    case ContentType::TEXT:
      output->appendText(
          TRI_CHAR_LENGTH_PAIR("Content-Type: text/plain; charset=utf-8\r\n"));
      break;
    case ContentType::HTML:
      output->appendText(
          TRI_CHAR_LENGTH_PAIR("Content-Type: text/html; charset=utf-8\r\n"));
      break;
    case ContentType::DUMP:
      output->appendText(TRI_CHAR_LENGTH_PAIR(
          "Content-Type: application/x-arango-dump; charset=utf-8\r\n"));
      break;
    case ContentType::CUSTOM: {
      // intentionally don't print anything here
      // the header should have been in _headers already, and should have been
      // handled above
    }
  }

  for (auto const& it : _cookies) {
    output->appendText(TRI_CHAR_LENGTH_PAIR("Set-Cookie: "));
    output->appendText(it);
    output->appendText("\r\n", 2);
  }

  if (seenTransferEncodingHeader && transferEncoding == "chunked") {
    output->appendText(
        TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: chunked\r\n\r\n"));
  } else {
    if (seenTransferEncodingHeader) {
      output->appendText(TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: "));
      output->appendText(transferEncoding);
      output->appendText("\r\n", 2);
    }

    output->appendText(TRI_CHAR_LENGTH_PAIR("Content-Length: "));

    if (_isHeadResponse) {
      // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
      //
      // 14.13 Content-Length
      //
      // The Content-Length entity-header field indicates the size of the
      // entity-body,
      // in decimal number of OCTETs, sent to the recipient or, in the case of
      // the HEAD method,
      // the size of the entity-body that would have been sent had the request
      // been a GET.
      output->appendInteger(_bodySize);
    } else {
      output->appendInteger(_body.length());
    }

    output->appendText("\r\n\r\n", 4);
  }
  // end of header, body to follow
}

void HttpResponse::addPayloadPostHook(
    VPackSlice const& slice,
    VPackOptions const* options = &VPackOptions::Options::Defaults,
    bool resolveExternals = true, bool bodySkipped = false) {
  VPackSlice const* slicePtr;
  if (!bodySkipped) {
    // we have Probably resolved externals
    TRI_ASSERT(!_vpackPayloads.empty());
    VPackSlice tmpSlice = VPackSlice(_vpackPayloads.front().data());
    slicePtr = &tmpSlice;
  } else {
    slicePtr = &slice;
  }

  switch (_contentType) {
    case rest::ContentType::VPACK: {
      size_t length = static_cast<size_t>(slicePtr->byteSize());
      if (_generateBody) {
        _body.appendText(slicePtr->startAs<const char>(), length);
      } else {
        headResponse(length);
      }
      break;
    }
    default: {
      setContentType(rest::ContentType::JSON);
      if (_generateBody) {
        arangodb::basics::VelocyPackDumper dumper(&_body, options);
        dumper.dumpValue(*slicePtr);
      } else {
        // TODO can we optimize this?
        // Just dump some where else to find real length
        StringBuffer tmp(TRI_UNKNOWN_MEM_ZONE, false);

        // convert object to string
        VPackStringBufferAdapter buffer(tmp.stringBuffer());

        // usual dumping -  but not to the response body
        VPackDumper dumper(&buffer, options);
        dumper.dump(*slicePtr);

        headResponse(tmp.length());
      }
    }
  }
}
<commit_msg>fix invalid pointer<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////

#include "HttpResponse.h"

#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>

#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackDumper.h"
#include "Basics/tri-strings.h"
#include "Meta/conversion.h"
#include "Rest/GeneralRequest.h"

using namespace arangodb;
using namespace arangodb::basics;

bool HttpResponse::HIDE_PRODUCT_HEADER = false;

HttpResponse::HttpResponse(ResponseCode code)
    : GeneralResponse(code),
      _isHeadResponse(false),
      _body(TRI_UNKNOWN_MEM_ZONE, false),
      _bodySize(0) {
  _generateBody = false;
  _contentType = ContentType::TEXT;
  _connectionType = rest::CONNECTION_KEEP_ALIVE;
  if (_body.c_str() == nullptr) {
    // no buffer could be reserved. out of memory!
    THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
  }
}

void HttpResponse::reset(ResponseCode code) {
  _responseCode = code;
  _headers.clear();
  _connectionType = rest::CONNECTION_KEEP_ALIVE;
  _contentType = ContentType::TEXT;
  _isHeadResponse = false;
  _body.clear();
  _bodySize = 0;
}

void HttpResponse::setCookie(std::string const& name, std::string const& value,
                             int lifeTimeSeconds, std::string const& path,
                             std::string const& domain, bool secure,
                             bool httpOnly) {
  std::unique_ptr<StringBuffer> buffer =
      std::make_unique<StringBuffer>(TRI_UNKNOWN_MEM_ZONE);

  std::string tmp = StringUtils::trim(name);
  buffer->appendText(tmp);
  buffer->appendChar('=');

  tmp = StringUtils::urlEncode(value);
  buffer->appendText(tmp);

  if (lifeTimeSeconds != 0) {
    time_t rawtime;

    time(&rawtime);
    if (lifeTimeSeconds > 0) {
      rawtime += lifeTimeSeconds;
    } else {
      rawtime = 1;
    }

    if (rawtime > 0) {
      struct tm* timeinfo;
      char buffer2[80];

      timeinfo = gmtime(&rawtime);
      strftime(buffer2, 80, "%a, %d-%b-%Y %H:%M:%S %Z", timeinfo);
      buffer->appendText(TRI_CHAR_LENGTH_PAIR("; expires="));
      buffer->appendText(buffer2);
    }
  }

  if (!path.empty()) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; path="));
    buffer->appendText(path);
  }

  if (!domain.empty()) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; domain="));
    buffer->appendText(domain);
  }

  if (secure) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; secure"));
  }

  if (httpOnly) {
    buffer->appendText(TRI_CHAR_LENGTH_PAIR("; HttpOnly"));
  }

  _cookies.emplace_back(buffer->c_str());
}

void HttpResponse::headResponse(size_t size) {
  _body.clear();
  _isHeadResponse = true;
  _bodySize = size;
}

size_t HttpResponse::bodySize() const {
  if (_isHeadResponse) {
    return _bodySize;
  }
  return _body.length();
}

void HttpResponse::writeHeader(StringBuffer* output) {
  output->appendText(TRI_CHAR_LENGTH_PAIR("HTTP/1.1 "));
  output->appendText(responseString(_responseCode));
  output->appendText("\r\n", 2);

  bool seenServerHeader = false;
  bool seenConnectionHeader = false;
  bool seenTransferEncodingHeader = false;
  std::string transferEncoding;

  for (auto const& it : _headers) {
    std::string const& key = it.first;
    size_t const keyLength = key.size();

    // ignore content-length
    if (keyLength == 14 && key[0] == 'c' &&
        memcmp(key.c_str(), "content-length", keyLength) == 0) {
      continue;
    }

    // save transfer encoding
    if (keyLength == 17 && key[0] == 't' &&
        memcmp(key.c_str(), "transfer-encoding", keyLength) == 0) {
      seenTransferEncodingHeader = true;
      transferEncoding = it.second;
      continue;
    }

    if (keyLength == 6 && key[0] == 's' &&
        memcmp(key.c_str(), "server", keyLength) == 0) {
      // this ensures we don't print two "Server" headers
      seenServerHeader = true;
      // go on and use the user-defined "Server" header value
    } else if (keyLength == 10 && key[0] == 'c' &&
               memcmp(key.c_str(), "connection", keyLength) == 0) {
      // this ensures we don't print two "Connection" headers
      seenConnectionHeader = true;
      // go on and use the user-defined "Connection" header value
    }

    // reserve enough space for header name + ": " + value + "\r\n"
    if (output->reserve(keyLength + 2 + it.second.size() + 2) !=
        TRI_ERROR_NO_ERROR) {
      THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
    }

    char const* p = key.c_str();
    char const* end = p + keyLength;
    int capState = 1;

    while (p < end) {
      if (capState == 1) {
        // upper case
        output->appendCharUnsafe(::toupper(*p));
        capState = 0;
      } else if (capState == 0) {
        // normal case
        output->appendCharUnsafe(::tolower(*p));
        if (*p == '-') {
          capState = 1;
        } else if (*p == ':') {
          capState = 2;
        }
      } else {
        // output as is
        output->appendCharUnsafe(*p);
      }
      ++p;
    }

    output->appendTextUnsafe(": ", 2);
    output->appendTextUnsafe(it.second);
    output->appendTextUnsafe("\r\n", 2);
  }

  // add "Server" response header
  if (!seenServerHeader && !HIDE_PRODUCT_HEADER) {
    output->appendText("Server: ArangoDB\r\n");
  }

  // add "Connection" response header
  if (!seenConnectionHeader) {
    switch (_connectionType) {
      case rest::ConnectionType::CONNECTION_KEEP_ALIVE:
        output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Keep-Alive\r\n"));
        break;
      case rest::ConnectionType::CONNECTION_CLOSE:
        output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: Close\r\n"));
        break;
      case rest::ConnectionType::CONNECTION_NONE:
        output->appendText(TRI_CHAR_LENGTH_PAIR("Connection: \r\n"));
        break;
    }
  }

  // add "Content-Type" header
  switch (_contentType) {
    case ContentType::UNSET:
    case ContentType::JSON:
      output->appendText(TRI_CHAR_LENGTH_PAIR(
          "Content-Type: application/json; charset=utf-8\r\n"));
      break;
    case ContentType::VPACK:
      output->appendText(
          TRI_CHAR_LENGTH_PAIR("Content-Type: application/x-velocypack\r\n"));
      break;
    case ContentType::TEXT:
      output->appendText(
          TRI_CHAR_LENGTH_PAIR("Content-Type: text/plain; charset=utf-8\r\n"));
      break;
    case ContentType::HTML:
      output->appendText(
          TRI_CHAR_LENGTH_PAIR("Content-Type: text/html; charset=utf-8\r\n"));
      break;
    case ContentType::DUMP:
      output->appendText(TRI_CHAR_LENGTH_PAIR(
          "Content-Type: application/x-arango-dump; charset=utf-8\r\n"));
      break;
    case ContentType::CUSTOM: {
      // intentionally don't print anything here
      // the header should have been in _headers already, and should have been
      // handled above
    }
  }

  for (auto const& it : _cookies) {
    output->appendText(TRI_CHAR_LENGTH_PAIR("Set-Cookie: "));
    output->appendText(it);
    output->appendText("\r\n", 2);
  }

  if (seenTransferEncodingHeader && transferEncoding == "chunked") {
    output->appendText(
        TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: chunked\r\n\r\n"));
  } else {
    if (seenTransferEncodingHeader) {
      output->appendText(TRI_CHAR_LENGTH_PAIR("Transfer-Encoding: "));
      output->appendText(transferEncoding);
      output->appendText("\r\n", 2);
    }

    output->appendText(TRI_CHAR_LENGTH_PAIR("Content-Length: "));

    if (_isHeadResponse) {
      // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
      //
      // 14.13 Content-Length
      //
      // The Content-Length entity-header field indicates the size of the
      // entity-body,
      // in decimal number of OCTETs, sent to the recipient or, in the case of
      // the HEAD method,
      // the size of the entity-body that would have been sent had the request
      // been a GET.
      output->appendInteger(_bodySize);
    } else {
      output->appendInteger(_body.length());
    }

    output->appendText("\r\n\r\n", 4);
  }
  // end of header, body to follow
}

void HttpResponse::addPayloadPostHook(
    VPackSlice const& slice,
    VPackOptions const* options = &VPackOptions::Options::Defaults,
    bool resolveExternals = true, bool bodySkipped = false) {

  VPackSlice const* slicePtr;
  VPackSlice tmpSlice;

  if (!bodySkipped) {
    // we have Probably resolved externals
    TRI_ASSERT(!_vpackPayloads.empty());
    tmpSlice = VPackSlice(_vpackPayloads.front().data());
    slicePtr = &tmpSlice;
  } else {
    slicePtr = &slice;
  }

  switch (_contentType) {
    case rest::ContentType::VPACK: {
      size_t length = static_cast<size_t>(slicePtr->byteSize());
      if (_generateBody) {
        _body.appendText(slicePtr->startAs<const char>(), length);
      } else {
        headResponse(length);
      }
      break;
    }
    default: {
      setContentType(rest::ContentType::JSON);
      if (_generateBody) {
        arangodb::basics::VelocyPackDumper dumper(&_body, options);
        dumper.dumpValue(*slicePtr);
      } else {
        // TODO can we optimize this?
        // Just dump some where else to find real length
        StringBuffer tmp(TRI_UNKNOWN_MEM_ZONE, false);

        // convert object to string
        VPackStringBufferAdapter buffer(tmp.stringBuffer());

        // usual dumping -  but not to the response body
        VPackDumper dumper(&buffer, options);
        dumper.dump(*slicePtr);

        headResponse(tmp.length());
      }
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __MEM_ADDR_MAPPER_HH__
#define __MEM_ADDR_MAPPER_HH__

#include "mem/port.hh"
#include "params/AddrMapper.hh"
#include "params/RangeAddrMapper.hh"
#include "sim/sim_object.hh"

/**
 * An address mapper changes the packet addresses in going from the
 * response port side of the mapper to the request port side. When the
 * response port is queried for the address ranges, it also performs the
 * necessary range updates. Note that snoop requests that travel from
 * the request port (i.e. the memory side) to the response port are
 * currently not modified.
 */

class AddrMapper : public SimObject
{

  public:

    AddrMapper(const AddrMapperParams &params);

    virtual ~AddrMapper() { }

    Port &getPort(const std::string &if_name,
                  PortID idx=InvalidPortID) override;

    void init() override;

  protected:

    /**
     * This function does the actual remapping of one address to another.
     * It is pure virtual in this case to to allow any implementation
     * required.
     * @param addr the address to remap
     * @return the new address (can be unchanged)
     */
    virtual Addr remapAddr(Addr addr) const = 0;

    class AddrMapperSenderState : public Packet::SenderState
    {

      public:

        /**
         * Construct a new sender state to remember the original address.
         *
         * @param _origAddr Address before remapping
         */
        AddrMapperSenderState(Addr _origAddr) : origAddr(_origAddr)
        { }

        /** Destructor */
        ~AddrMapperSenderState() { }

        /** The original address the packet was destined for */
        Addr origAddr;

    };

    class MapperRequestPort : public RequestPort
    {

      public:

        MapperRequestPort(const std::string& _name, AddrMapper& _mapper)
            : RequestPort(_name, &_mapper), mapper(_mapper)
        { }

      protected:

        void recvFunctionalSnoop(PacketPtr pkt)
        {
            mapper.recvFunctionalSnoop(pkt);
        }

        Tick recvAtomicSnoop(PacketPtr pkt)
        {
            return mapper.recvAtomicSnoop(pkt);
        }

        bool recvTimingResp(PacketPtr pkt)
        {
            return mapper.recvTimingResp(pkt);
        }

        void recvTimingSnoopReq(PacketPtr pkt)
        {
            mapper.recvTimingSnoopReq(pkt);
        }

        void recvRangeChange()
        {
            mapper.recvRangeChange();
        }

        bool isSnooping() const
        {
            return mapper.isSnooping();
        }

        void recvReqRetry()
        {
            mapper.recvReqRetry();
        }

      private:

        AddrMapper& mapper;

    };

    /** Instance of request port, facing the memory side */
    MapperRequestPort memSidePort;

    class MapperResponsePort : public ResponsePort
    {

      public:

        MapperResponsePort(const std::string& _name, AddrMapper& _mapper)
            : ResponsePort(_name, &_mapper), mapper(_mapper)
        { }

      protected:

        void recvFunctional(PacketPtr pkt)
        {
            mapper.recvFunctional(pkt);
        }

        Tick recvAtomic(PacketPtr pkt)
        {
            return mapper.recvAtomic(pkt);
        }

        bool recvTimingReq(PacketPtr pkt)
        {
            return mapper.recvTimingReq(pkt);
        }

        bool recvTimingSnoopResp(PacketPtr pkt)
        {
            return mapper.recvTimingSnoopResp(pkt);
        }

        AddrRangeList getAddrRanges() const
        {
            return mapper.getAddrRanges();
        }

        void recvRespRetry()
        {
            mapper.recvRespRetry();
        }

      private:

        AddrMapper& mapper;

    };

    /** Instance of response port, i.e. on the CPU side */
    MapperResponsePort cpuSidePort;

    void recvFunctional(PacketPtr pkt);

    void recvFunctionalSnoop(PacketPtr pkt);

    Tick recvAtomic(PacketPtr pkt);

    Tick recvAtomicSnoop(PacketPtr pkt);

    bool recvTimingReq(PacketPtr pkt);

    bool recvTimingResp(PacketPtr pkt);

    void recvTimingSnoopReq(PacketPtr pkt);

    bool recvTimingSnoopResp(PacketPtr pkt);

    virtual AddrRangeList getAddrRanges() const = 0;

    bool isSnooping() const;

    void recvReqRetry();

    void recvRespRetry();

    void recvRangeChange();
};

/**
 * Range address mapper that maps a set of original ranges to a set of
 * remapped ranges, where a specific range is of the same size
 * (original and remapped), only with an offset. It's useful for cases
 * where memory is mapped to two different locations
 */
class RangeAddrMapper : public AddrMapper
{

  public:

    RangeAddrMapper(const RangeAddrMapperParams &p);

    ~RangeAddrMapper() { }

    AddrRangeList getAddrRanges() const;

  protected:

    /**
     * This contains a list of ranges the should be remapped. It must
     * be the exact same length as remappedRanges which describes what
     * manipulation should be done to each range.
     */
    std::vector<AddrRange> originalRanges;

    /**
     * This contains a list of ranges that addresses should be
     * remapped to. See the description for originalRanges above
     */
    std::vector<AddrRange> remappedRanges;

    Addr remapAddr(Addr addr) const;

};

#endif //__MEM_ADDR_MAPPER_HH__
<commit_msg>mem: Fix style in addr_mapper.hh.<commit_after>/*
 * Copyright (c) 2012 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __MEM_ADDR_MAPPER_HH__
#define __MEM_ADDR_MAPPER_HH__

#include "mem/port.hh"
#include "params/AddrMapper.hh"
#include "params/RangeAddrMapper.hh"
#include "sim/sim_object.hh"

/**
 * An address mapper changes the packet addresses in going from the
 * response port side of the mapper to the request port side. When the
 * response port is queried for the address ranges, it also performs the
 * necessary range updates. Note that snoop requests that travel from
 * the request port (i.e. the memory side) to the response port are
 * currently not modified.
 */

class AddrMapper : public SimObject
{
  public:
    AddrMapper(const AddrMapperParams &params);

    virtual ~AddrMapper() = default;

    Port &getPort(const std::string &if_name,
                  PortID idx=InvalidPortID) override;

    void init() override;

  protected:
    /**
     * This function does the actual remapping of one address to another.
     * It is pure virtual in this case to to allow any implementation
     * required.
     * @param addr the address to remap
     * @return the new address (can be unchanged)
     */
    virtual Addr remapAddr(Addr addr) const = 0;

    class AddrMapperSenderState : public Packet::SenderState
    {

      public:

        /**
         * Construct a new sender state to remember the original address.
         *
         * @param _origAddr Address before remapping
         */
        AddrMapperSenderState(Addr _origAddr) : origAddr(_origAddr)
        {}

        /** Destructor */
        ~AddrMapperSenderState() {}

        /** The original address the packet was destined for */
        Addr origAddr;
    };

    class MapperRequestPort : public RequestPort
    {
      public:
        MapperRequestPort(const std::string& _name, AddrMapper& _mapper)
            : RequestPort(_name, &_mapper), mapper(_mapper)
        { }

      protected:
        void
        recvFunctionalSnoop(PacketPtr pkt) override
        {
            mapper.recvFunctionalSnoop(pkt);
        }

        Tick
        recvAtomicSnoop(PacketPtr pkt) override
        {
            return mapper.recvAtomicSnoop(pkt);
        }

        bool
        recvTimingResp(PacketPtr pkt) override
        {
            return mapper.recvTimingResp(pkt);
        }

        void
        recvTimingSnoopReq(PacketPtr pkt) override
        {
            mapper.recvTimingSnoopReq(pkt);
        }

        void
        recvRangeChange() override
        {
            mapper.recvRangeChange();
        }

        bool
        isSnooping() const override
        {
            return mapper.isSnooping();
        }

        void
        recvReqRetry() override
        {
            mapper.recvReqRetry();
        }

      private:
        AddrMapper& mapper;
    };

    /** Instance of request port, facing the memory side */
    MapperRequestPort memSidePort;

    class MapperResponsePort : public ResponsePort
    {
      public:
        MapperResponsePort(const std::string& _name, AddrMapper& _mapper)
            : ResponsePort(_name, &_mapper), mapper(_mapper)
        {}

      protected:
        void
        recvFunctional(PacketPtr pkt) override
        {
            mapper.recvFunctional(pkt);
        }

        Tick
        recvAtomic(PacketPtr pkt) override
        {
            return mapper.recvAtomic(pkt);
        }

        bool
        recvTimingReq(PacketPtr pkt) override
        {
            return mapper.recvTimingReq(pkt);
        }

        bool
        recvTimingSnoopResp(PacketPtr pkt) override
        {
            return mapper.recvTimingSnoopResp(pkt);
        }

        AddrRangeList
        getAddrRanges() const override
        {
            return mapper.getAddrRanges();
        }

        void
        recvRespRetry() override
        {
            mapper.recvRespRetry();
        }

      private:
        AddrMapper& mapper;
    };

    /** Instance of response port, i.e. on the CPU side */
    MapperResponsePort cpuSidePort;

    void recvFunctional(PacketPtr pkt);

    void recvFunctionalSnoop(PacketPtr pkt);

    Tick recvAtomic(PacketPtr pkt);

    Tick recvAtomicSnoop(PacketPtr pkt);

    bool recvTimingReq(PacketPtr pkt);

    bool recvTimingResp(PacketPtr pkt);

    void recvTimingSnoopReq(PacketPtr pkt);

    bool recvTimingSnoopResp(PacketPtr pkt);

    virtual AddrRangeList getAddrRanges() const = 0;

    bool isSnooping() const;

    void recvReqRetry();

    void recvRespRetry();

    void recvRangeChange();
};

/**
 * Range address mapper that maps a set of original ranges to a set of
 * remapped ranges, where a specific range is of the same size
 * (original and remapped), only with an offset. It's useful for cases
 * where memory is mapped to two different locations
 */
class RangeAddrMapper : public AddrMapper
{
  public:
    RangeAddrMapper(const RangeAddrMapperParams &p);

    ~RangeAddrMapper() = default;

    AddrRangeList getAddrRanges() const override;

  protected:
    /**
     * This contains a list of ranges the should be remapped. It must
     * be the exact same length as remappedRanges which describes what
     * manipulation should be done to each range.
     */
    std::vector<AddrRange> originalRanges;

    /**
     * This contains a list of ranges that addresses should be
     * remapped to. See the description for originalRanges above
     */
    std::vector<AddrRange> remappedRanges;

    Addr remapAddr(Addr addr) const override;
};

#endif //__MEM_ADDR_MAPPER_HH__
<|endoftext|>


<commit_before>AliAnalysisTaskSubJetFraction* AddTaskAliAnalysisTaskSubJetFraction(const char * njetsData, //data jets
								    const char * njetsTrue, //Pyhthia Particle Level
								    const char * njetsDet,
								    const char * njetsHybridUs,
								    const char * njetsHybridS,
								    const Double_t R,
								    const char * nrhoBase,
								    const char * ntracksData,
                                                                    const char * ntracksTrue,
                                                                    const char * ntracksDet,
								    const char * ntracksHybridUs,
								    const char * ntracksHybridS,
								    const char * nclusters,
								    const char *type,
								    const char *CentEst,
								    Double_t fSharedFractionPtMin,
								    Int_t SubJetAlgorithm,
								    Float_t SubJetRadius,
								    Float_t SubJetMinPt,
								    Int_t       pSel,
								    TString     trigClass      = "",
								    TString     kEmcalTriggers = "",
								    TString     tag            = "",
								    AliAnalysisTaskSubJetFraction::JetShapeType jetShapeType,
								    AliAnalysisTaskSubJetFraction::JetShapeSub jetShapeSub,
								    AliAnalysisTaskSubJetFraction::JetSelectionType jetSelection,
								    Float_t minpTHTrigger =0.,  Float_t maxpTHTrigger =0., AliAnalysisTaskSubJetFraction::DerivSubtrOrder derivSubtrOrder = 0  ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskAliAnalysisTaskSubJetFraction","No analysis manager found.");
      return 0;
    }
  Bool_t ismc=kFALSE;
  ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
    {
      ::Error("AliAnalysisTaskSubJetFraction", "This task requires an input event handler");
      return NULL;
    }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsData,trigClass.Data(),tag.Data());
  if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue || jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet || jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsTrue,trigClass.Data(),tag.Data());
  if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsHybridS,trigClass.Data(),tag.Data());
  //Configure jet tagger task
  AliAnalysisTaskSubJetFraction *task = new AliAnalysisTaskSubJetFraction(wagonName.Data());

  task->SetNCentBins(4);
  task->SetJetShapeType(jetShapeType);
  task->SetJetShapeSub(jetShapeSub);
  task->SetJetSelection(jetSelection);
  task->SetSubJetAlgorithm(SubJetAlgorithm);
  task->SetSubJetRadius(SubJetRadius);
  task->SetSubJetMinPt(SubJetMinPt);
  task->SetJetRadius(R);
  task->SetSharedFractionPtMin(fSharedFractionPtMin);
  task->SetDerivativeSubtractionOrder(derivSubtrOrder);
  if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) task->SetPtTriggerSelections(minpTHTrigger, maxpTHTrigger);

  // TString thename(njetsBase);
  //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE);
  //task->SetVzRange(-10.,10.);

  AliParticleContainer *trackContData=0x0;
  AliParticleContainer *trackContDet=0x0;

  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub){
    trackContData = task->AddParticleContainer(ntracksData);
    trackContDet = task->AddParticleContainer(ntracksDet);
  }
  else{
    trackContData = task->AddTrackContainer(ntracksData);
    trackContDet = task->AddTrackContainer(ntracksDet);
  }

  AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);
  AliParticleContainer *trackContHybridUs = task->AddParticleContainer(ntracksHybridUs);
  AliParticleContainer *trackContHybridS = task->AddParticleContainer(ntracksHybridS);
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

  AliJetContainer *JetContData=0x0;
  AliJetContainer *JetContTrue=0x0;
  AliJetContainer *JetContDet=0x0;
  AliJetContainer *JetContHybridUs=0x0;
  AliJetContainer *JetContHybridS=0x0;

  TString strType(type);

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue) {
    JetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->ConnectClusterContainer(clusterCont);
      JetContTrue->SetPercAreaCut(0.6);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPythiaInfoName("PythiaInfo");
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) {
    JetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->ConnectClusterContainer(clusterCont);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPercAreaCut(0.6);
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet){

    JetContDet = task->AddJetContainer(njetsDet,strType,R);  //detector level MC
    if(JetContDet) {
      JetContDet->SetRhoName(nrhoBase);
      JetContDet->ConnectParticleContainer(trackContDet);
      JetContDet->ConnectClusterContainer(clusterCont);
      JetContDet->SetPercAreaCut(0.6);
      JetContDet->SetJetRadius(R);
      JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContDet->SetPythiaInfoName("PythiaInfo");
    }

    JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Particle Level MC
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->SetPercAreaCut(0.6);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPythiaInfoName("PythiaInfo");
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim){
    JetContData = task->AddJetContainer(njetsData,strType,R); //Data
    if(JetContData) {
      JetContData->SetRhoName(nrhoBase);
      JetContData->ConnectParticleContainer(trackContData);
      JetContData->ConnectClusterContainer(clusterCont);
      JetContData->SetPercAreaCut(0.6);
      JetContData->SetJetRadius(R);
      JetContData->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContData->SetAreaEmcCut(-2);
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart){
    JetContHybridS = task->AddJetContainer(njetsHybridS,strType,R);  //Subtracted Hybrid (Pb+Pyhthia Det Level)
    if(JetContHybridS) {
      JetContHybridS->SetRhoName(nrhoBase);
      JetContHybridS->ConnectParticleContainer(trackContHybridS);
      JetContHybridS->ConnectClusterContainer(clusterCont);
      JetContHybridS->SetPercAreaCut(0.6);
      JetContHybridS->SetJetRadius(R);
      JetContHybridS->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContHybridS->SetPythiaInfoName("PythiaInfo");
      if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContHybridS->SetAreaEmcCut(-2); //??????????
    }
    if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub){ //??????????????????????????
      JetContHybridUs=task->AddJetContainer(njetsHybridUs,strType,R);     //Unsubtracted Hybrid
      if(JetContHybridUs) {
        JetContHybridUs->SetRhoName(nrhoBase);
        JetContHybridUs->ConnectParticleContainer(trackContHybridUs);
        JetContHybridUs->SetPercAreaCut(0.6);
	JetContHybridUs->SetJetRadius(R);
	JetContHybridUs->SetJetAcceptanceType(AliJetContainer::kTPCfid);
        JetContHybridUs->SetPythiaInfoName("PythiaInfo");
      }
    }
    JetContDet = task->AddJetContainer(njetsDet,strType,R); //Pythia Detector Level
    if(JetContDet) {
      JetContDet->SetRhoName(nrhoBase);
      JetContDet->ConnectParticleContainer(trackContDet);
      JetContDet->SetPercAreaCut(0.6);
      JetContDet->SetJetRadius(R);
      JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContDet->SetPythiaInfoName("PythiaInfo");
    }
    JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Pyhthia Particle Level
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->SetPercAreaCut(0.6);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPythiaInfoName("PythiaInfo");
    }
  }

  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);
  task->SetUseAliAnaUtils(kFALSE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName1(wagonName);

  if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrue) contName1 += "_True";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrueDet) contName1 += "_TrueDet";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kData) contName1 += "_Data";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kSim) contName1 += "_Sim";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kDetEmbPart) contName1 += "_DetEmbPart";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kGenOnTheFly) contName1 += "_GenOnTheFly";

  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kNoSub) contName1 += "_NoSub";
  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub) contName1 += "_ConstSub";
  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 0) contName1 += "_DerivSubSecondOrder";
  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 1) contName1 += "_DerivSubFirstOrder";

  if (jetSelection == AliAnalysisTaskSubJetFraction::kInclusive) contName1 += "_Incl";
  if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) {
  TString recoilTriggerString = Form("_Recoil_%.0f_%0.f", minpTHTrigger, maxpTHTrigger);
  contName1 += recoilTriggerString;
  }
  TString SubJetRadiusString = Form("_SubJetRadius_%f", SubJetRadius);
  contName1 += SubJetRadiusString;
  TString SubJetMinPtString = Form("_SubJetMinPt_%f", SubJetMinPt);
  contName1 += SubJetMinPtString;

  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);

  mgr->ConnectOutput(task,1,coutput1);

  return task;

}

<commit_msg>Taking an argumant out of AddTask<commit_after>AliAnalysisTaskSubJetFraction* AddTaskAliAnalysisTaskSubJetFraction(const char * njetsData, //data jets
								    const char * njetsTrue, //Pyhthia Particle Level
								    const char * njetsDet,
								    const char * njetsHybridUs,
								    const char * njetsHybridS,
								    const Double_t R,
								    const char * nrhoBase,
								    const char * ntracksData,
                                                                    const char * ntracksTrue,
                                                                    const char * ntracksDet,
								    const char * ntracksHybridUs,
								    const char * ntracksHybridS,
								    const char * nclusters,
								    const char *type,
								    const char *CentEst,
								    Double_t fSharedFractionPtMin,
								    Int_t SubJetAlgorithm,
								    Float_t SubJetRadius,
								    Float_t SubJetMinPt,
								    Int_t       pSel,
								    TString     trigClass      = "",
								    TString     kEmcalTriggers = "",
								    TString     tag            = "",
								    AliAnalysisTaskSubJetFraction::JetShapeType jetShapeType,
								    AliAnalysisTaskSubJetFraction::JetShapeSub jetShapeSub,
								    AliAnalysisTaskSubJetFraction::JetSelectionType jetSelection,
								    Float_t minpTHTrigger =0.,  Float_t maxpTHTrigger =0., AliAnalysisTaskSubJetFraction::DerivSubtrOrder derivSubtrOrder = 0  ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskAliAnalysisTaskSubJetFraction","No analysis manager found.");
      return 0;
    }
  Bool_t ismc=kFALSE;
  ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
    {
      ::Error("AliAnalysisTaskSubJetFraction", "This task requires an input event handler");
      return NULL;
    }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsData,trigClass.Data(),tag.Data());
  if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue || jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet || jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsTrue,trigClass.Data(),tag.Data());
  if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart) TString wagonName = Form("AliAnalysisTaskSubJetFraction_%s_TC%s%s",njetsHybridS,trigClass.Data(),tag.Data());
  //Configure jet tagger task
  AliAnalysisTaskSubJetFraction *task = new AliAnalysisTaskSubJetFraction(wagonName.Data());

  //  task->SetNCentBins(4);
  task->SetJetShapeType(jetShapeType);
  task->SetJetShapeSub(jetShapeSub);
  task->SetJetSelection(jetSelection);
  task->SetSubJetAlgorithm(SubJetAlgorithm);
  task->SetSubJetRadius(SubJetRadius);
  task->SetSubJetMinPt(SubJetMinPt);
  task->SetJetRadius(R);
  task->SetSharedFractionPtMin(fSharedFractionPtMin);
  task->SetDerivativeSubtractionOrder(derivSubtrOrder);
  if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) task->SetPtTriggerSelections(minpTHTrigger, maxpTHTrigger);

  // TString thename(njetsBase);
  //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE);
  //task->SetVzRange(-10.,10.);

  AliParticleContainer *trackContData=0x0;
  AliParticleContainer *trackContDet=0x0;

  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub){
    trackContData = task->AddParticleContainer(ntracksData);
    trackContDet = task->AddParticleContainer(ntracksDet);
  }
  else{
    trackContData = task->AddTrackContainer(ntracksData);
    trackContDet = task->AddTrackContainer(ntracksDet);
  }

  AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);
  AliParticleContainer *trackContHybridUs = task->AddParticleContainer(ntracksHybridUs);
  AliParticleContainer *trackContHybridS = task->AddParticleContainer(ntracksHybridS);
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

  AliJetContainer *JetContData=0x0;
  AliJetContainer *JetContTrue=0x0;
  AliJetContainer *JetContDet=0x0;
  AliJetContainer *JetContHybridUs=0x0;
  AliJetContainer *JetContHybridS=0x0;

  TString strType(type);

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrue) {
    JetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->ConnectClusterContainer(clusterCont);
      JetContTrue->SetPercAreaCut(0.6);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPythiaInfoName("PythiaInfo");
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kGenOnTheFly) {
    JetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->ConnectClusterContainer(clusterCont);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPercAreaCut(0.6);
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kTrueDet){

    JetContDet = task->AddJetContainer(njetsDet,strType,R);  //detector level MC
    if(JetContDet) {
      JetContDet->SetRhoName(nrhoBase);
      JetContDet->ConnectParticleContainer(trackContDet);
      JetContDet->ConnectClusterContainer(clusterCont);
      JetContDet->SetPercAreaCut(0.6);
      JetContDet->SetJetRadius(R);
      JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContDet->SetPythiaInfoName("PythiaInfo");
    }

    JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Particle Level MC
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->SetPercAreaCut(0.6);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPythiaInfoName("PythiaInfo");
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kData || jetShapeType==AliAnalysisTaskSubJetFraction::kSim){
    JetContData = task->AddJetContainer(njetsData,strType,R); //Data
    if(JetContData) {
      JetContData->SetRhoName(nrhoBase);
      JetContData->ConnectParticleContainer(trackContData);
      JetContData->ConnectClusterContainer(clusterCont);
      JetContData->SetPercAreaCut(0.6);
      JetContData->SetJetRadius(R);
      JetContData->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContData->SetAreaEmcCut(-2);
    }
  }

  if (jetShapeType==AliAnalysisTaskSubJetFraction::kDetEmbPart){
    JetContHybridS = task->AddJetContainer(njetsHybridS,strType,R);  //Subtracted Hybrid (Pb+Pyhthia Det Level)
    if(JetContHybridS) {
      JetContHybridS->SetRhoName(nrhoBase);
      JetContHybridS->ConnectParticleContainer(trackContHybridS);
      JetContHybridS->ConnectClusterContainer(clusterCont);
      JetContHybridS->SetPercAreaCut(0.6);
      JetContHybridS->SetJetRadius(R);
      JetContHybridS->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContHybridS->SetPythiaInfoName("PythiaInfo");
      if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub) JetContHybridS->SetAreaEmcCut(-2); //??????????
    }
    if(jetShapeSub==AliAnalysisTaskSubJetFraction::kConstSub){ //??????????????????????????
      JetContHybridUs=task->AddJetContainer(njetsHybridUs,strType,R);     //Unsubtracted Hybrid
      if(JetContHybridUs) {
        JetContHybridUs->SetRhoName(nrhoBase);
        JetContHybridUs->ConnectParticleContainer(trackContHybridUs);
        JetContHybridUs->SetPercAreaCut(0.6);
	JetContHybridUs->SetJetRadius(R);
	JetContHybridUs->SetJetAcceptanceType(AliJetContainer::kTPCfid);
        JetContHybridUs->SetPythiaInfoName("PythiaInfo");
      }
    }
    JetContDet = task->AddJetContainer(njetsDet,strType,R); //Pythia Detector Level
    if(JetContDet) {
      JetContDet->SetRhoName(nrhoBase);
      JetContDet->ConnectParticleContainer(trackContDet);
      JetContDet->SetPercAreaCut(0.6);
      JetContDet->SetJetRadius(R);
      JetContDet->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContDet->SetPythiaInfoName("PythiaInfo");
    }
    JetContTrue = task->AddJetContainer(njetsTrue,strType,R); //Pyhthia Particle Level
    if(JetContTrue) {
      JetContTrue->SetRhoName(nrhoBase);
      JetContTrue->ConnectParticleContainer(trackContTrue);
      JetContTrue->SetPercAreaCut(0.6);
      JetContTrue->SetJetRadius(R);
      JetContTrue->SetJetAcceptanceType(AliJetContainer::kTPCfid);
      JetContTrue->SetPythiaInfoName("PythiaInfo");
    }
  }

  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);
  task->SetUseAliAnaUtils(kFALSE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName1(wagonName);

  if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrue) contName1 += "_True";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kTrueDet) contName1 += "_TrueDet";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kData) contName1 += "_Data";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kSim) contName1 += "_Sim";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kDetEmbPart) contName1 += "_DetEmbPart";
  if (jetShapeType == AliAnalysisTaskSubJetFraction::kGenOnTheFly) contName1 += "_GenOnTheFly";

  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kNoSub) contName1 += "_NoSub";
  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kConstSub) contName1 += "_ConstSub";
  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 0) contName1 += "_DerivSubSecondOrder";
  if (jetShapeSub == AliAnalysisTaskSubJetFraction::kDerivSub && derivSubtrOrder == 1) contName1 += "_DerivSubFirstOrder";

  if (jetSelection == AliAnalysisTaskSubJetFraction::kInclusive) contName1 += "_Incl";
  if (jetSelection == AliAnalysisTaskSubJetFraction::kRecoil) {
  TString recoilTriggerString = Form("_Recoil_%.0f_%0.f", minpTHTrigger, maxpTHTrigger);
  contName1 += recoilTriggerString;
  }
  TString SubJetRadiusString = Form("_SubJetRadius_%f", SubJetRadius);
  contName1 += SubJetRadiusString;
  TString SubJetMinPtString = Form("_SubJetMinPt_%f", SubJetMinPt);
  contName1 += SubJetMinPtString;

  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);

  mgr->ConnectOutput(task,1,coutput1);

  return task;

}

<|endoftext|>


<commit_before>//                                PUMI Example
//
// Compile with: Add GenerateMFEMMesh.cpp in the CMakeLists.txt
//
// Sample runs:  ./GenerateMFEMMesh -m ../data/pumi/serial/sphere.smb
//                    -p ../data/pumi/geom/sphere.x_t -o 1
//
// Description:  The purpose of this example is to generate MFEM meshes for
//               complex geometry. The inputs are a Parasolid model, "*.xmt_txt"
//               and a SCOREC mesh "*.smb". Switch "-o" can be used to increase the
//               geometric order up to order 6 and consequently write the mesh
//               in that order.

#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../mesh/mesh_pumi.hpp"

#include "pumi_config.h"
#ifdef MFEM_USE_SIMMETRIX
#include <SimUtil.h>
#include <gmi_sim.h>
#endif
#include <apfMDS.h>
#include <gmi_null.h>
#include <PCU.h>
#include <apfConvert.h>
#include <gmi_mesh.h>
#include <crv.h>

using namespace std;
using namespace mfem;

int main(int argc, char *argv[])
{
    //initilize mpi
    int num_proc, myId;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &num_proc);
    MPI_Comm_rank(MPI_COMM_WORLD, &myId);

   // 1. Parse command-line options.
   const char *mesh_file = "../data/pumi/serial/sphere.smb";
#ifdef MFEM_USE_SIMMETRIX
   const char *model_file = "../data/pumi/geom/sphere.x_t";
#else
   const char *model_file = "../data/pumi/geom/sphere.dmg";
#endif
   int order = 1;
   bool visualization = 1;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree).");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.AddOption(&model_file, "-p", "--parasolid",
                  "Parasolid model to use.");

   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   //Read the SCOREC Mesh
   PCU_Comm_Init();
#ifdef MFEM_USE_SIMMETRIX
   Sim_readLicenseFile(0);
   gmi_sim_start();
   gmi_register_sim();
#endif
   gmi_register_mesh();

   apf::Mesh2* pumi_mesh;
   pumi_mesh = apf::loadMdsMesh(model_file, mesh_file);

   //If it is higher order change shape
   if (order > 1){
       crv::BezierCurver bc(pumi_mesh, order, 2);
       bc.run();
   }
   pumi_mesh->verify();

   // 2. Create the MFEM mesh object from the PUMI mesh. We can handle triangular
   //    and tetrahedral meshes. Other inputs are the same as MFEM default
   //    constructor.
   Mesh *mesh = new PumiMesh(pumi_mesh, 1, 0);

   //Write mesh in MFEM fromat
   ofstream fout("MFEMformat.mesh");
   //ofstream fout("MFEMformat.vtku");
   fout.precision(8);
   mesh->Print(fout);
   //mesh->PrintVTK(fout);

   delete mesh;

   pumi_mesh->destroyNative();
   apf::destroyMesh(pumi_mesh);
   PCU_Comm_Free();

#ifdef MFEM_USE_SIMMETRIX
   gmi_sim_stop();
   Sim_unregisterAllKeys();
#endif

   MPI_Finalize();
   return 0;
}
<commit_msg>Make changes required after review<commit_after><|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*! @file
    @brief  SEEDA03 (RX64M) メイン
	@copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved.
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/rspi_io.hpp"
#include "common/spi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/flash_man.hpp"
#include "common/time.h"

#include "chip/LTC2348_16.hpp"
#include "sample.hpp"

#include "chip/EUI_XX.hpp"

#include "r_net/http_server.hpp"
#include "r_net/ftp_server.hpp"

#ifdef DEBUG
#define CLIENT_DEBUG
#define NETS_DEBUG
#define WRITE_FILE_DEBUG
#endif

namespace seeda {

	static const int seeda_version_ = 310;
	static const uint32_t build_id_ = B_ID;

	typedef utils::command<256> CMD;

#ifdef SEEDA
	typedef device::PORT<device::PORT6, device::bitpos::B7> SW1;
	typedef device::PORT<device::PORT6, device::bitpos::B6> SW2;
#endif

	// Soft SDC 用　SPI 定義（SPI）
#ifdef SEEDA
	typedef device::PORT<device::PORTD, device::bitpos::B6> MISO;
	typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI;
	typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK;
	typedef device::spi_io<MISO, MOSI, SPCK> SPI;

	typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT;	///< カード検出
#else
	// SDC 用　SPI 定義（RSPI）
	typedef device::rspi_io<device::RSPI> SPI;
	typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT;	///< カード検出
#endif
	typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;

#ifdef SEEDA
	// LTC2348-16 A/D 制御ポート定義
	typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN;   // P40(141)
	typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV;   // PC6(61)
	typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY;  // PD0/IRQ0(126)
	typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD;    // P53(53)
	typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI;   // P56(50)
	typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO;  // P86(41)
	typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI;  // P87(39)
	typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0;  // P20(37)
	typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2;  // P21(36)
	typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4;  // P22(35)
	typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6;  // P23(34)
	typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO;
	typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC;
#endif

	typedef device::flash_io FLASH_IO;
	typedef utils::flash_man<FLASH_IO> FLASH_MAN;

	typedef net::http_server<SDC, 16, 8192> HTTP;
	typedef HTTP::http_format http_format;

	typedef net::ftp_server<SDC> FTPS;

	//-----------------------------------------------------------------//
	/*!
		@brief  SDC_IO クラスへの参照
		@return SDC_IO クラス
	*/
	//-----------------------------------------------------------------//
	SDC& at_sdc();

#ifdef SEEDA
	//-----------------------------------------------------------------//
	/*!
		@brief  EADC クラスへの参照
		@return EADC クラス
	*/
	//-----------------------------------------------------------------//
	EADC& at_eadc();
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー
	*/
	//-----------------------------------------------------------------//
	void eadc_server();

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー許可
		@param[in]	ena	「false」の場合不許可
	*/
	//-----------------------------------------------------------------//
	void enable_eadc_server(bool ena = true);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の作成
		@param[in]	date	日付
		@param[in]	time	時間
	*/
	//-----------------------------------------------------------------//
	size_t make_time(const char* date, const char* time);

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の設定
		@param[in]	t	GMT 時間
	*/
	//-----------------------------------------------------------------//
	void set_time(time_t t);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の表示
		@param[in]	t		時間
		@param[in]	dst		出力文字列
		@param[in]	size	文字列の大きさ
		@return 生成された文字列の長さ
	*/
	//-----------------------------------------------------------------//
	int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0);

	//-----------------------------------------------------------------//
	/*!
		@brief  設定スイッチの状態を取得
		@return 設定スイッチの状態
	*/
	//-----------------------------------------------------------------//
	uint8_t get_switch()
	{
#ifdef SEEDA
		return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1);
#else
		return 0;  // for only develope mode
#endif
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの参照
		@param[in]	ch	チャネル（０～７）
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	sample_t& at_sample(uint8_t ch);

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの取得
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	const sample_data& get_sample_data();

	//-----------------------------------------------------------------//
	/*!
		@brief  内臓 A/D 変換値の取得
		@param[in]	ch	チャネル（５、６、７）
		@return A/D 変換値
	*/
	//-----------------------------------------------------------------//
	uint16_t get_adc(uint32_t ch);
}

extern "C" {

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の取得
		@return GMT 時間
	*/
	//-----------------------------------------------------------------//
	time_t get_time();

};
<commit_msg>update version NO<commit_after>#pragma once
//=====================================================================//
/*! @file
    @brief  SEEDA03 (RX64M) メイン
	@copyright Copyright 2017 Kunihito Hiramatsu All Right Reserved.
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/rspi_io.hpp"
#include "common/spi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/flash_man.hpp"
#include "common/time.h"

#include "chip/LTC2348_16.hpp"
#include "sample.hpp"

#include "chip/EUI_XX.hpp"

#include "r_net/http_server.hpp"
#include "r_net/ftp_server.hpp"

#ifdef DEBUG
#define CLIENT_DEBUG
#define NETS_DEBUG
#define WRITE_FILE_DEBUG
#endif

namespace seeda {

	static const int seeda_version_ = 322;
	static const uint32_t build_id_ = B_ID;

	typedef utils::command<256> CMD;

#ifdef SEEDA
	typedef device::PORT<device::PORT6, device::bitpos::B7> SW1;
	typedef device::PORT<device::PORT6, device::bitpos::B6> SW2;
#endif

	// Soft SDC 用　SPI 定義（SPI）
#ifdef SEEDA
	typedef device::PORT<device::PORTD, device::bitpos::B6> MISO;
	typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI;
	typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK;
	typedef device::spi_io<MISO, MOSI, SPCK> SPI;

	typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT;	///< カード検出
#else
	// SDC 用　SPI 定義（RSPI）
	typedef device::rspi_io<device::RSPI> SPI;
	typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT;	///< カード検出
#endif
	typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;

#ifdef SEEDA
	// LTC2348-16 A/D 制御ポート定義
	typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN;   // P40(141)
	typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV;   // PC6(61)
	typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY;  // PD0/IRQ0(126)
	typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD;    // P53(53)
	typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI;   // P56(50)
	typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO;  // P86(41)
	typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI;  // P87(39)
	typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0;  // P20(37)
	typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2;  // P21(36)
	typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4;  // P22(35)
	typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6;  // P23(34)
	typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO;
	typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC;
#endif

	typedef device::flash_io FLASH_IO;
	typedef utils::flash_man<FLASH_IO> FLASH_MAN;

	typedef net::http_server<SDC, 16, 8192> HTTP;
	typedef HTTP::http_format http_format;

	typedef net::ftp_server<SDC> FTPS;

	//-----------------------------------------------------------------//
	/*!
		@brief  SDC_IO クラスへの参照
		@return SDC_IO クラス
	*/
	//-----------------------------------------------------------------//
	SDC& at_sdc();

#ifdef SEEDA
	//-----------------------------------------------------------------//
	/*!
		@brief  EADC クラスへの参照
		@return EADC クラス
	*/
	//-----------------------------------------------------------------//
	EADC& at_eadc();
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー
	*/
	//-----------------------------------------------------------------//
	void eadc_server();

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー許可
		@param[in]	ena	「false」の場合不許可
	*/
	//-----------------------------------------------------------------//
	void enable_eadc_server(bool ena = true);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の作成
		@param[in]	date	日付
		@param[in]	time	時間
	*/
	//-----------------------------------------------------------------//
	size_t make_time(const char* date, const char* time);

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の設定
		@param[in]	t	GMT 時間
	*/
	//-----------------------------------------------------------------//
	void set_time(time_t t);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の表示
		@param[in]	t		時間
		@param[in]	dst		出力文字列
		@param[in]	size	文字列の大きさ
		@return 生成された文字列の長さ
	*/
	//-----------------------------------------------------------------//
	int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0);

	//-----------------------------------------------------------------//
	/*!
		@brief  設定スイッチの状態を取得
		@return 設定スイッチの状態
	*/
	//-----------------------------------------------------------------//
	uint8_t get_switch()
	{
#ifdef SEEDA
		return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1);
#else
		return 0;  // for only develope mode
#endif
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの参照
		@param[in]	ch	チャネル（０～７）
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	sample_t& at_sample(uint8_t ch);

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの取得
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	const sample_data& get_sample_data();

	//-----------------------------------------------------------------//
	/*!
		@brief  内臓 A/D 変換値の取得
		@param[in]	ch	チャネル（５、６、７）
		@return A/D 変換値
	*/
	//-----------------------------------------------------------------//
	uint16_t get_adc(uint32_t ch);
}

extern "C" {

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の取得
		@return GMT 時間
	*/
	//-----------------------------------------------------------------//
	time_t get_time();

};
<|endoftext|>