<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include <new>
#include <cstdlib>

#if !defined(LEAN_TRACK_MEMORY)

namespace lean {
size_t     get_allocated_memory() {
    return 0;
}

long long  get_thread_allocated_memory() {
    return 0;
}

void * malloc(size_t sz)  {
    void * r = ::malloc(sz);
    if (r || sz == 0)
        return r;
    else
        throw std::bad_alloc();
}

void * realloc(void * ptr, size_t sz) {
    void * r = ::realloc(ptr, sz);
    if (r || sz == 0)
        return r;
    else
        throw std::bad_alloc();
}

void free(void * ptr) {
    ::free(ptr);
}
}

#else
#include <atomic>

#if defined(HAS_MALLOC_USABLE_SIZE)
#include <malloc.h> // NOLINT
namespace lean {
inline size_t malloc_size(void * ptr)             { return malloc_usable_size(ptr); }
inline void * malloc_core(size_t sz)              { return ::malloc(sz); }
inline void * realloc_core(void * ptr, size_t sz) { return realloc(ptr, sz); }
inline void   free_core(void * ptr)               { free(ptr); }
}
// REMARK: We commented the following piece of code because tc_malloc_size is hanging

// #elif defined(HAS_TCMALLOC)
// #include <gperftools/tcmalloc.h>
// namespace lean {
// inline size_t malloc_size(void * ptr)             { return tc_malloc_size(ptr); }
// inline void * malloc_core(size_t sz)              { return tc_malloc(sz); }
// inline void * realloc_core(void * ptr, size_t sz) { return tc_realloc(ptr, sz); }
// inline void   free_core(void * ptr)               { tc_free(ptr); }
// }
#elif defined(HAS_MALLOCSIZE)
#include <malloc/malloc.h> // NOLINT
namespace lean {
inline size_t malloc_size(void * ptr)             { return ::malloc_size(ptr); }
inline void * malloc_core(size_t sz)              { return ::malloc(sz); }
inline void * realloc_core(void * ptr, size_t sz) { return realloc(ptr, sz); }
inline void   free_core(void * ptr)               { free(ptr); }
}
#elif defined(HAS_MSIZE)
#include <malloc.h> // NOLINT
namespace lean {
inline size_t malloc_size(void * ptr)             { return _msize(ptr); }
inline void * malloc_core(size_t sz)              { return ::malloc(sz); }
inline void * realloc_core(void * ptr, size_t sz) { return realloc(ptr, sz); }
inline void   free_core(void * ptr)               { free(ptr); }
}
#else
namespace lean {
void * save_alloc_size(void * ptr, size_t sz) {
    if (ptr) {
        size_t * r = static_cast<size_t*>(ptr);
        *r = sz;
        return r + 1;
    } else {
        return ptr;
    }
}
inline size_t malloc_size(void * ptr)             { return static_cast<size_t*>(ptr)[-1]; }
inline void * malloc_core(size_t sz)              { return save_alloc_size(::malloc(sz + sizeof(sz)), sz); }
inline void * realloc_core(void * ptr, size_t sz) { return save_alloc_size(::realloc(static_cast<size_t*>(ptr) - 1, sz + sizeof(sz)), sz); }
inline void   free_core(void * ptr)               { ::free(static_cast<size_t*>(ptr) - 1); }
}
#endif

namespace lean {
class alloc_info {
    std::atomic<size_t> m_size;
public:
    alloc_info():m_size(0) {}
    ~alloc_info() {}
    void inc(size_t sz) { m_size += sz; }
    void dec(size_t sz) { m_size -= sz; }
    size_t size() const { return m_size; }
};

class thread_alloc_info {
    size_t m_size; // It can be negative
public:
    thread_alloc_info():m_size(0) {}
    void inc(size_t sz) { m_size += sz; }
    void dec(size_t sz) { m_size -= sz; }
    long long size() const { return static_cast<long long>(m_size); }
};

static alloc_info                     g_global_memory;
static thread_local thread_alloc_info g_thread_memory;

size_t     get_allocated_memory() { return g_global_memory.size(); }
long long  get_thread_allocated_memory() { return g_thread_memory.size(); }

void * malloc(size_t sz)  {
    void * r = malloc_core(sz);
    if (r || sz == 0) {
        size_t rsz = malloc_size(r);
        g_global_memory.inc(rsz);
        g_thread_memory.inc(rsz);
        return r;
    } else {
        throw std::bad_alloc();
    }
}

void * realloc(void * ptr, size_t sz) {
    size_t old_sz = malloc_size(ptr);
    g_global_memory.dec(old_sz);
    g_global_memory.inc(sz);
    g_thread_memory.dec(old_sz);
    g_thread_memory.inc(sz);
    void * r = realloc_core(ptr, sz);
    if (r || sz == 0)
        return r;
    else
        throw std::bad_alloc();
}

void free(void * ptr) {
    if (ptr) {
        size_t sz = malloc_size(ptr);
        g_global_memory.dec(sz);
        g_thread_memory.dec(sz);
    }
    free_core(ptr);
}
}

void* operator new(std::size_t sz) throw(std::bad_alloc) { return lean::malloc(sz); }
void  operator delete(void * ptr) throw() { return lean::free(ptr); }
void* operator new[](std::size_t sz) throw(std::bad_alloc) { return lean::malloc(sz); }
void  operator delete[](void * ptr) throw() { return lean::free(ptr); }
#endif
<commit_msg>fix(memory): increase memory counters by the actual size of reallocated memory<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include <new>
#include <cstdlib>

#if !defined(LEAN_TRACK_MEMORY)

namespace lean {
size_t     get_allocated_memory() {
    return 0;
}

long long  get_thread_allocated_memory() {
    return 0;
}

void * malloc(size_t sz)  {
    void * r = ::malloc(sz);
    if (r || sz == 0)
        return r;
    else
        throw std::bad_alloc();
}

void * realloc(void * ptr, size_t sz) {
    void * r = ::realloc(ptr, sz);
    if (r || sz == 0)
        return r;
    else
        throw std::bad_alloc();
}

void free(void * ptr) {
    ::free(ptr);
}
}

#else
#include <atomic>

#if defined(HAS_MALLOC_USABLE_SIZE)
#include <malloc.h> // NOLINT
namespace lean {
inline size_t malloc_size(void * ptr)             { return malloc_usable_size(ptr); }
inline void * malloc_core(size_t sz)              { return ::malloc(sz); }
inline void * realloc_core(void * ptr, size_t sz) { return realloc(ptr, sz); }
inline void   free_core(void * ptr)               { free(ptr); }
}
// REMARK: We commented the following piece of code because tc_malloc_size is hanging

// #elif defined(HAS_TCMALLOC)
// #include <gperftools/tcmalloc.h>
// namespace lean {
// inline size_t malloc_size(void * ptr)             { return tc_malloc_size(ptr); }
// inline void * malloc_core(size_t sz)              { return tc_malloc(sz); }
// inline void * realloc_core(void * ptr, size_t sz) { return tc_realloc(ptr, sz); }
// inline void   free_core(void * ptr)               { tc_free(ptr); }
// }
#elif defined(HAS_MALLOCSIZE)
#include <malloc/malloc.h> // NOLINT
namespace lean {
inline size_t malloc_size(void * ptr)             { return ::malloc_size(ptr); }
inline void * malloc_core(size_t sz)              { return ::malloc(sz); }
inline void * realloc_core(void * ptr, size_t sz) { return realloc(ptr, sz); }
inline void   free_core(void * ptr)               { free(ptr); }
}
#elif defined(HAS_MSIZE)
#include <malloc.h> // NOLINT
namespace lean {
inline size_t malloc_size(void * ptr)             { return _msize(ptr); }
inline void * malloc_core(size_t sz)              { return ::malloc(sz); }
inline void * realloc_core(void * ptr, size_t sz) { return realloc(ptr, sz); }
inline void   free_core(void * ptr)               { free(ptr); }
}
#else
namespace lean {
void * save_alloc_size(void * ptr, size_t sz) {
    if (ptr) {
        size_t * r = static_cast<size_t*>(ptr);
        *r = sz;
        return r + 1;
    } else {
        return ptr;
    }
}
inline size_t malloc_size(void * ptr)             { return static_cast<size_t*>(ptr)[-1]; }
inline void * malloc_core(size_t sz)              { return save_alloc_size(::malloc(sz + sizeof(sz)), sz); }
inline void * realloc_core(void * ptr, size_t sz) { return save_alloc_size(::realloc(static_cast<size_t*>(ptr) - 1, sz + sizeof(sz)), sz); }
inline void   free_core(void * ptr)               { ::free(static_cast<size_t*>(ptr) - 1); }
}
#endif

namespace lean {
class alloc_info {
    std::atomic<size_t> m_size;
public:
    alloc_info():m_size(0) {}
    ~alloc_info() {}
    void inc(size_t sz) { m_size += sz; }
    void dec(size_t sz) { m_size -= sz; }
    size_t size() const { return m_size; }
};

class thread_alloc_info {
    size_t m_size; // It can be negative
public:
    thread_alloc_info():m_size(0) {}
    void inc(size_t sz) { m_size += sz; }
    void dec(size_t sz) { m_size -= sz; }
    long long size() const { return static_cast<long long>(m_size); }
};

static alloc_info                     g_global_memory;
static thread_local thread_alloc_info g_thread_memory;

size_t     get_allocated_memory() { return g_global_memory.size(); }
long long  get_thread_allocated_memory() { return g_thread_memory.size(); }

void * malloc(size_t sz)  {
    void * r = malloc_core(sz);
    if (r || sz == 0) {
        size_t rsz = malloc_size(r);
        g_global_memory.inc(rsz);
        g_thread_memory.inc(rsz);
        return r;
    } else {
        throw std::bad_alloc();
    }
}

void * realloc(void * ptr, size_t sz) {
    size_t old_sz = malloc_size(ptr);
    g_global_memory.dec(old_sz);
    g_thread_memory.dec(old_sz);
    void * r = realloc_core(ptr, sz);
    size_t new_sz = malloc_size(r);
    g_global_memory.inc(new_sz);
    g_thread_memory.inc(new_sz);
    if (r || sz == 0)
        return r;
    else
        throw std::bad_alloc();
}

void free(void * ptr) {
    if (ptr) {
        size_t sz = malloc_size(ptr);
        g_global_memory.dec(sz);
        g_thread_memory.dec(sz);
    }
    free_core(ptr);
}
}

void* operator new(std::size_t sz) throw(std::bad_alloc) { return lean::malloc(sz); }
void  operator delete(void * ptr) throw() { return lean::free(ptr); }
void* operator new[](std::size_t sz) throw(std::bad_alloc) { return lean::malloc(sz); }
void  operator delete[](void * ptr) throw() { return lean::free(ptr); }
#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <libgen.h>
#include "utils/PVLog.hpp"

namespace PV {

void vpv_log_with_prefix(FILE *stream, const char *prefix, const char *file, int line, const char *fmt, va_list args) {
   static int buf_size = 1024;
   char msg[buf_size];
   vsnprintf(msg, buf_size, fmt, args);
   fprintf(stream, "%s<%s:%d>: %s\n", prefix, basename((char*)file), line, msg);
}

void vpv_log_error(const char *file, int line, const char *fmt, va_list args) {
   // Flush stdout before printing to stderr. This makes the output
   // a bit cleaner if logging to the console
   fflush(stdout);
   vpv_log_with_prefix(stderr, "ERROR", file, line, fmt, args);
}

void vpv_log_debug(const char *file, int line, const char *fmt, va_list args) {
   vpv_log_with_prefix(stdout, "DEBUG", file, line, fmt, args);
}

void pv_log_error(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vpv_log_error(file, line, fmt, args);
   va_end(args);
}

void pv_exit_failure(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vpv_log_error(file, line, fmt, args);
   va_end(args);
   exit(EXIT_FAILURE);
}

void pv_log_info(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vfprintf(stdout, fmt, args);
   va_end(args);
}

void pv_log_debug(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vpv_log_debug(file, line, fmt, args);
   va_end(args);
}

}
<commit_msg>Adds a newline to pv_log_info output for consistency with pv_log_error, pv_log_debug, and pv_exit_failure.<commit_after>#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <libgen.h>
#include "utils/PVLog.hpp"

namespace PV {

void vpv_log_with_prefix(FILE *stream, const char *prefix, const char *file, int line, const char *fmt, va_list args) {
   static int buf_size = 1024;
   char msg[buf_size];
   vsnprintf(msg, buf_size, fmt, args);
   fprintf(stream, "%s<%s:%d>: %s\n", prefix, basename((char*)file), line, msg);
}

void vpv_log_error(const char *file, int line, const char *fmt, va_list args) {
   // Flush stdout before printing to stderr. This makes the output
   // a bit cleaner if logging to the console
   fflush(stdout);
   vpv_log_with_prefix(stderr, "ERROR", file, line, fmt, args);
}

void vpv_log_debug(const char *file, int line, const char *fmt, va_list args) {
   vpv_log_with_prefix(stdout, "DEBUG", file, line, fmt, args);
}

void pv_log_error(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vpv_log_error(file, line, fmt, args);
   va_end(args);
}

void pv_exit_failure(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vpv_log_error(file, line, fmt, args);
   va_end(args);
   exit(EXIT_FAILURE);
}

void pv_log_info(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vfprintf(stdout, fmt, args);
   fprintf(stdout, "\n");
   va_end(args);
}

void pv_log_debug(const char *file, int line, const char *fmt, ...) {
   va_list args;
   va_start(args, fmt);
   vpv_log_debug(file, line, fmt, args);
   va_end(args);
}

}
<|endoftext|>


<commit_before>/*
* Runtime CPU detection
* (C) 2009-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/get_byte.h>
#include <botan/mem_ops.h>

#if defined(BOTAN_TARGET_OS_IS_DARWIN)
  #include <sys/sysctl.h>
#endif

#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)

#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)

  #include <intrin.h>
  #define CALL_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)

#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)

  #include <ia32intrin.h>
  #define CALL_CPUID(type, out) do { __cpuid(out, type); } while(0);

#elif BOTAN_GCC_VERSION >= 430

  // Only available starting in GCC 4.3
  #include <cpuid.h>
  #define CALL_CPUID(type, out) \
    do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0);

#else
  #warning "No method of calling CPUID for this compiler"
#endif

#endif

#ifndef CALL_CPUID
  // In all other cases, just zeroize the supposed cpuid output
  #define CALL_CPUID(type, out) \
    do { out[0] = out[1] = out[2] = out[3] = 0; } while(0);
#endif

namespace Botan {

u64bit CPUID::x86_processor_flags = 0;
size_t CPUID::cache_line = 32;
bool CPUID::altivec_capable = false;

namespace {

u32bit get_x86_cache_line_size()
   {
   const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
   const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };

   u32bit cpuid[4] = { 0 };
   CALL_CPUID(0, cpuid);

   if(same_mem(cpuid + 1, INTEL_CPUID, 3))
      {
      CALL_CPUID(1, cpuid);
      return 8 * get_byte(2, cpuid[1]);
      }
   else if(same_mem(cpuid + 1, AMD_CPUID, 3))
      {
      CALL_CPUID(0x80000005, cpuid);
      return get_byte(3, cpuid[2]);
      }
   else
      return 32; // default cache line guess
   }

#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)

bool altivec_check_sysctl()
   {
#if defined(BOTAN_TARGET_OS_IS_DARWIN)

   // From Apple's docs
   int sels[2] = { CTL_HW, HW_VECTORUNIT };
   int vector_type = 0;
   size_t length = sizeof(vector_type);
   int error = sysctl(sels, 2, &vector_type, &length, NULL, 0);

   if(error == 0 && vector_type > 0)
      return true;
#endif

   return false;
   }

bool altivec_check_pvr_emul()
   {
   bool altivec_capable = false;

#if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_NETBSD)

   /*
   On PowerPC, MSR 287 is PVR, the Processor Version Number
   Normally it is only accessible to ring 0, but Linux and NetBSD
   (others, too, maybe?) will trap and emulate it for us.

   PVR identifiers for various AltiVec enabled CPUs. Taken from
   PearPC and Linux sources, mostly.
   */

   const u16bit PVR_G4_7400  = 0x000C;
   const u16bit PVR_G5_970   = 0x0039;
   const u16bit PVR_G5_970FX = 0x003C;
   const u16bit PVR_G5_970MP = 0x0044;
   const u16bit PVR_G5_970GX = 0x0045;
   const u16bit PVR_POWER6   = 0x003E;
   const u16bit PVR_CELL_PPU = 0x0070;

   // Motorola produced G4s with PVR 0x800[0123C] (at least)
   const u16bit PVR_G4_74xx_24  = 0x800;

   u32bit pvr = 0;

   asm volatile("mfspr %0, 287" : "=r" (pvr));

   // Top 16 bit suffice to identify model
   pvr >>= 16;

   altivec_capable |= (pvr == PVR_G4_7400);
   altivec_capable |= ((pvr >> 4) == PVR_G4_74xx_24);
   altivec_capable |= (pvr == PVR_G5_970);
   altivec_capable |= (pvr == PVR_G5_970FX);
   altivec_capable |= (pvr == PVR_G5_970MP);
   altivec_capable |= (pvr == PVR_G5_970GX);
   altivec_capable |= (pvr == PVR_POWER6);
   altivec_capable |= (pvr == PVR_CELL_PPU);
#endif

   return altivec_capable;
   }

#endif

}

void CPUID::initialize()
   {
   u32bit cpuid[4] = { 0 };
   CALL_CPUID(1, cpuid);

   x86_processor_flags = ((u64bit)cpuid[2] << 32) | cpuid[3];

#if defined(BOTAN_TARGET_ARCH_IS_AMD64)
   /*
   * If we don't have access to CPUID, we can still safely assume that
   * any x86-64 processor has SSE2.
   */
   if(x86_processor_flags == 0)
     x86_processor_flags |= (1 << CPUID_SSE2_BIT);
#endif

   cache_line = get_x86_cache_line_size();

   altivec_capable = false;

#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
      if(altivec_check_sysctl() || altivec_check_pvr_emul())
         altivec_capable = true;
#endif
   }

}
<commit_msg>Clang 2.8 also has cpuid.h<commit_after>/*
* Runtime CPU detection
* (C) 2009-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/get_byte.h>
#include <botan/mem_ops.h>

#if defined(BOTAN_TARGET_OS_IS_DARWIN)
  #include <sys/sysctl.h>
#endif

#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)

#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)

  #include <intrin.h>
  #define CALL_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)

#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)

  #include <ia32intrin.h>
  #define CALL_CPUID(type, out) do { __cpuid(out, type); } while(0);

#elif (BOTAN_GCC_VERSION >= 430) || defined(BOTAN_BUILD_COMPILER_IS_CLANG)

  // Only available starting in GCC 4.3
  #include <cpuid.h>
  #define CALL_CPUID(type, out) \
    do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0);

#else
  #warning "No method of calling CPUID for this compiler"
#endif

#endif

#ifndef CALL_CPUID
  // In all other cases, just zeroize the supposed cpuid output
  #define CALL_CPUID(type, out) \
    do { out[0] = out[1] = out[2] = out[3] = 0; } while(0);
#endif

namespace Botan {

u64bit CPUID::x86_processor_flags = 0;
size_t CPUID::cache_line = 32;
bool CPUID::altivec_capable = false;

namespace {

u32bit get_x86_cache_line_size()
   {
   const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
   const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };

   u32bit cpuid[4] = { 0 };
   CALL_CPUID(0, cpuid);

   if(same_mem(cpuid + 1, INTEL_CPUID, 3))
      {
      CALL_CPUID(1, cpuid);
      return 8 * get_byte(2, cpuid[1]);
      }
   else if(same_mem(cpuid + 1, AMD_CPUID, 3))
      {
      CALL_CPUID(0x80000005, cpuid);
      return get_byte(3, cpuid[2]);
      }
   else
      return 32; // default cache line guess
   }

#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)

bool altivec_check_sysctl()
   {
#if defined(BOTAN_TARGET_OS_IS_DARWIN)

   // From Apple's docs
   int sels[2] = { CTL_HW, HW_VECTORUNIT };
   int vector_type = 0;
   size_t length = sizeof(vector_type);
   int error = sysctl(sels, 2, &vector_type, &length, NULL, 0);

   if(error == 0 && vector_type > 0)
      return true;
#endif

   return false;
   }

bool altivec_check_pvr_emul()
   {
   bool altivec_capable = false;

#if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_NETBSD)

   /*
   On PowerPC, MSR 287 is PVR, the Processor Version Number
   Normally it is only accessible to ring 0, but Linux and NetBSD
   (others, too, maybe?) will trap and emulate it for us.

   PVR identifiers for various AltiVec enabled CPUs. Taken from
   PearPC and Linux sources, mostly.
   */

   const u16bit PVR_G4_7400  = 0x000C;
   const u16bit PVR_G5_970   = 0x0039;
   const u16bit PVR_G5_970FX = 0x003C;
   const u16bit PVR_G5_970MP = 0x0044;
   const u16bit PVR_G5_970GX = 0x0045;
   const u16bit PVR_POWER6   = 0x003E;
   const u16bit PVR_CELL_PPU = 0x0070;

   // Motorola produced G4s with PVR 0x800[0123C] (at least)
   const u16bit PVR_G4_74xx_24  = 0x800;

   u32bit pvr = 0;

   asm volatile("mfspr %0, 287" : "=r" (pvr));

   // Top 16 bit suffice to identify model
   pvr >>= 16;

   altivec_capable |= (pvr == PVR_G4_7400);
   altivec_capable |= ((pvr >> 4) == PVR_G4_74xx_24);
   altivec_capable |= (pvr == PVR_G5_970);
   altivec_capable |= (pvr == PVR_G5_970FX);
   altivec_capable |= (pvr == PVR_G5_970MP);
   altivec_capable |= (pvr == PVR_G5_970GX);
   altivec_capable |= (pvr == PVR_POWER6);
   altivec_capable |= (pvr == PVR_CELL_PPU);
#endif

   return altivec_capable;
   }

#endif

}

void CPUID::initialize()
   {
   u32bit cpuid[4] = { 0 };
   CALL_CPUID(1, cpuid);

   x86_processor_flags = ((u64bit)cpuid[2] << 32) | cpuid[3];

#if defined(BOTAN_TARGET_ARCH_IS_AMD64)
   /*
   * If we don't have access to CPUID, we can still safely assume that
   * any x86-64 processor has SSE2.
   */
   if(x86_processor_flags == 0)
     x86_processor_flags |= (1 << CPUID_SSE2_BIT);
#endif

   cache_line = get_x86_cache_line_size();

   altivec_capable = false;

#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
      if(altivec_check_sysctl() || altivec_check_pvr_emul())
         altivec_capable = true;
#endif
   }

}
<|endoftext|>


<commit_before>#pragma once

//====================================================|
//            Compiler definitions                    |
//                                                    |

#define M_COMPILER_UNKNOWN                            0
#define M_COMPILER_GCC                                1
#define M_COMPILER_MSVC                               2
#define M_COMPILER_CLANG                              3

#if defined(__GNUC__) || defined(__GNUG__)
#	define M_COMPILER M_COMPILER_GCC
#elif defined(_MSC_VER)
#	define M_COMPILER M_COMPILER_MSVC
#elif defined(__clang__)
#	define M_COMPILER M_COMPILER_CLANG
#else
#	define M_COMPILER M_COMPILER_UNKNOWN
#endif

//====================================================|
//            CPU architecture definitions            |
//                                                    |
#define M_CPU_UNKNOWN                                 0
#define M_CPU_X86                                     1
#define M_CPU_X86_64                                  2
#define M_CPU_ARM                                     3

#if M_COMPILER == M_COMPILER_GCC
#	if defined(__i386__) // __i386__ is defined for any x86 processor
#		define M_CPU M_CPU_X86

#		if defined(__i686__)
#			define M_CPU_VERSION 6
#		elif defined(__i586__)
#			define M_CPU_VERSION 5
#		elif defined(__i486__)
#			define M_CPU_VERSION 4
#		else
#			define M_CPU_VERSION 3
#		endif

#	elif defined(__x86_64__)
#		define M_CPU M_CPU_X86_64

#		define M_CPU_VERSION 0

#	elif defined(__arm__)
#		define M_CPU M_CPU_ARM

#		if defined(__thumb2__) // this macro is defined when targeting only thumb-2
#			define M_CPU_ARM_THUMB 2
#		elif defined(__thumb__) // this macro is defined when targeting any, thumb-1 or thumb-2
#			define M_CPU_ARM_THUMB 1
#		endif

#		if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__)
#			define M_CPU_VERSION 7
#		elif defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6__)
#			define M_CPU_VERSION 6
#		elif defined(__ARM_ARCH_5TEJ__) || defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5T__) || defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5__)
#			define M_CPU_VERSION 5
#		elif defined(__ARM_ARCH_4T__) || defined(__ARM_ARCH_4__)
#			define M_CPU_VERSION 4
#		else
#			define M_CPU_VERSION 0
#		endif

#	else
#		define M_CPU M_CPU_UNKNOWN
#		define M_CPU_VERSION 0
#	endif

#elif M_COMPILER == M_COMPILER_MSVC
#	if defined(_M_IX86)
#		define M_CPU M_CPU_X86

#		if _M_IX86 == 600
#			define M_CPU_VERSION 6
#		elif _M_IX86 == 500
#			define M_CPU_VERSION 5
#		elif _M_IX86 == 400
#			define M_CPU_VERSION 4
#		else
#			define M_CPU_VERSION 3
#		endif

#	elif defined(_M_AMD64) || defined(_M_X64)
#		define M_CPU M_CPU_X86_64
#		define M_CPU_VERSION 0

#	else
#		define M_CPU M_CPU_UNKNOWN
#		define M_CPU_VERSION 0
#	endif
#else
#	define M_CPU M_CPU_UNKNOWN
#	define M_CPU_VERSION 0
#endif

//======================================|
//            CPU bit depth             |
#define M_CPU_BIT_DEPTH_UNKNOWN 0
#define M_CPU_BIT_DEPTH_8 1
#define M_CPU_BIT_DEPTH_16 2
#define M_CPU_BIT_DEPTH_32 3
#define M_CPU_BIT_DEPTH_64 4
#define M_CPU_BIT_DEPTH_128 5

#if M_CPU == M_CPU_X86 || M_CPU == M_CPU_ARM
#	define M_CPU_BIT_DEPTH M_CPU_BIT_DEPTH_32
#elif M_CPU == M_CPU_X86_64
#	define M_CPU_BIT_DEPTH M_CPU_BIT_DEPTH_64
#else
#	define M_CPU_BIT_DEPTH M_CPU_BIT_DEPTH_UNKNOWN
#endif

//======================================|
//            OS definitions            |
//                                      |

// OS family
#define M_OS_UNKNOWN                    0
#define M_OS_LINUX                      1
#define M_OS_WINDOWS                    2
#define M_OS_MACOSX                     3
#define M_OS_UNIX                       4
#define M_OS_SYMBIAN                    5

// Concrete OS name
#define M_OS_NAME_UNKNOWN               0
#define M_OS_NAME_MACOSX                1
#define M_OS_NAME_IOS                   2
#define M_OS_NAME_ANDROID               3
#define M_OS_NAME_SOLARIS               4

#if defined(__linux__)
#	define M_OS M_OS_LINUX
#	if defined(__ANDROID__)
#		define M_OS_NAME M_OS_NAME_ANDROID
#	else
#		define M_OS_NAME M_OS_NAME_UNKNOWN
#	endif

// _WIN32 macro is defined for both win32 and win64. _WIN32 is the correct one, WIN32 not always defined.
#elif defined(_WIN32) || defined(WIN32)
#	define M_OS M_OS_WINDOWS
#	define M_OS_NAME M_OS_NAME_UNKNOWN
#elif defined(__APPLE__)
#	define M_OS M_OS_MACOSX
#	include <TargetConditionals.h>
#	if TARGET_OS_IPHONE == 1 || TARGET_IPHONE_SIMULATOR == 1 // iOS
#		define M_OS_NAME M_OS_NAME_IOS
#	else
#		define M_OS_NAME M_OS_NAME_MACOSX
#	endif

#elif defined(__unix) || defined(__unix__) // check for UNIX should go after check for Linux, because on Linux the __unix macro is also defined
#	define M_OS M_OS_UNIX
#	if defined(sun) || defined(__sun)
#		define M_OS_NAME M_OS_NAME_SOLARIS
#	else
#		define M_OS_NAME M_OS_NAME_UNKNOWN
#	endif
#elif defined(__SYMBIAN32__)
#	define M_OS M_OS_SYMBIAN
#	define M_OS_NAME M_OS_NAME_UNKNOWN
#else
#	define M_OS M_OS_UNKNOWN
#	define M_OS_NAME M_OS_NAME_UNKNOWN
#endif

#if M_OS == M_OS_WINDOWS
#	if M_COMPILER == M_COMPILER_MSVC
#		ifdef _USRDLL
#			define DLLEXPORT __declspec(dllexport)
#		else
#			define DLLEXPORT __declspec(dllimport)
#		endif
#		pragma warning(disable : 4251) // member variable needs to have dll-interface to be used by clients of class
#		pragma warning(disable : 4275) // non dll-interface class used as base for dll-interface class
#		pragma warning(disable : 4250) // method inherited via dominance
#	else
#		define DLLEXPORT
#	endif
#else
#	define DLLEXPORT
#endif
<commit_msg>some config macros refactoring<commit_after>#pragma once

//====================================================|
//            Compiler definitions                    |
//                                                    |

#define M_COMPILER_UNKNOWN                            0
#define M_COMPILER_GCC                                1
#define M_COMPILER_MSVC                               2
#define M_COMPILER_CLANG                              3

#if defined(__GNUC__) || defined(__GNUG__)
#	define M_COMPILER M_COMPILER_GCC
#elif defined(_MSC_VER)
#	define M_COMPILER M_COMPILER_MSVC
#elif defined(__clang__)
#	define M_COMPILER M_COMPILER_CLANG
#else
#	define M_COMPILER M_COMPILER_UNKNOWN
#endif

//====================================================|
//            CPU architecture definitions            |
//                                                    |
#define M_CPU_UNKNOWN                                 0
#define M_CPU_X86                                     1
#define M_CPU_X86_64                                  2
#define M_CPU_ARM                                     3

#if M_COMPILER == M_COMPILER_GCC
#	if defined(__i386__) // __i386__ is defined for any x86 processor
#		define M_CPU M_CPU_X86

#		if defined(__i686__)
#			define M_CPU_VERSION 6
#		elif defined(__i586__)
#			define M_CPU_VERSION 5
#		elif defined(__i486__)
#			define M_CPU_VERSION 4
#		else
#			define M_CPU_VERSION 3
#		endif

#	elif defined(__x86_64__)
#		define M_CPU M_CPU_X86_64

#		define M_CPU_VERSION 0

#	elif defined(__arm__)
#		define M_CPU M_CPU_ARM

#		if defined(__thumb2__) // this macro is defined when targeting only thumb-2
#			define M_CPU_ARM_THUMB_VERSION 2
#		elif defined(__thumb__) // this macro is defined when targeting any, thumb-1 or thumb-2
#			define M_CPU_ARM_THUMB_VERSION 1
#		endif

#		if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__)
#			define M_CPU_VERSION 7
#		elif defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6__)
#			define M_CPU_VERSION 6
#		elif defined(__ARM_ARCH_5TEJ__) || defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5T__) || defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5__)
#			define M_CPU_VERSION 5
#		elif defined(__ARM_ARCH_4T__) || defined(__ARM_ARCH_4__)
#			define M_CPU_VERSION 4
#		else
#			define M_CPU_VERSION 0
#		endif

#	else
#		define M_CPU M_CPU_UNKNOWN
#		define M_CPU_VERSION 0
#	endif

#elif M_COMPILER == M_COMPILER_MSVC
#	if defined(_M_IX86)
#		define M_CPU M_CPU_X86

#		if _M_IX86 == 600
#			define M_CPU_VERSION 6
#		elif _M_IX86 == 500
#			define M_CPU_VERSION 5
#		elif _M_IX86 == 400
#			define M_CPU_VERSION 4
#		else
#			define M_CPU_VERSION 3
#		endif

#	elif defined(_M_AMD64) || defined(_M_X64)
#		define M_CPU M_CPU_X86_64
#		define M_CPU_VERSION 0

#	else
#		define M_CPU M_CPU_UNKNOWN
#		define M_CPU_VERSION 0
#	endif
#else
#	define M_CPU M_CPU_UNKNOWN
#	define M_CPU_VERSION 0
#endif

//======================================|
//            OS definitions            |
//                                      |

// OS family
#define M_OS_UNKNOWN                    0
#define M_OS_LINUX                      1
#define M_OS_WINDOWS                    2
#define M_OS_MACOSX                     3
#define M_OS_UNIX                       4

// OS name
#define M_OS_NAME_UNKNOWN               0
#define M_OS_NAME_MACOSX                1
#define M_OS_NAME_IOS                   2
#define M_OS_NAME_ANDROID               3
#define M_OS_NAME_SOLARIS               4

#if defined(__linux__)
#	define M_OS M_OS_LINUX
#	if defined(__ANDROID__)
#		define M_OS_NAME M_OS_NAME_ANDROID
#	else
#		define M_OS_NAME M_OS_NAME_UNKNOWN
#	endif

// _WIN32 macro is defined for both win32 and win64. _WIN32 is the correct one, WIN32 not always defined.
#elif defined(_WIN32) || defined(WIN32)
#	define M_OS M_OS_WINDOWS
#	define M_OS_NAME M_OS_NAME_UNKNOWN
#elif defined(__APPLE__)
#	define M_OS M_OS_MACOSX
#	include <TargetConditionals.h>
#	if TARGET_OS_IPHONE == 1 || TARGET_IPHONE_SIMULATOR == 1 // iOS
#		define M_OS_NAME M_OS_NAME_IOS
#	else
#		define M_OS_NAME M_OS_NAME_MACOSX
#	endif

#elif defined(__unix) || defined(__unix__) // check for UNIX should go after check for Linux, because on Linux the __unix macro is also defined
#	define M_OS M_OS_UNIX
#	if defined(sun) || defined(__sun)
#		define M_OS_NAME M_OS_NAME_SOLARIS
#	else
#		define M_OS_NAME M_OS_NAME_UNKNOWN
#	endif
#else
#	define M_OS M_OS_UNKNOWN
#	define M_OS_NAME M_OS_NAME_UNKNOWN
#endif

#if M_OS == M_OS_WINDOWS
#	if M_COMPILER == M_COMPILER_MSVC
#		ifdef _USRDLL
#			define DLLEXPORT __declspec(dllexport)
#		else
#			define DLLEXPORT __declspec(dllimport)
#		endif
#		pragma warning(disable : 4251) // member variable needs to have dll-interface to be used by clients of class
#		pragma warning(disable : 4275) // non dll-interface class used as base for dll-interface class
#		pragma warning(disable : 4250) // method inherited via dominance
#	else
#		define DLLEXPORT
#	endif
#else
#	define DLLEXPORT
#endif
<|endoftext|>


<commit_before>#ifndef _SDD_ORDER_STRATEGIES_VARIABLES_PER_LEVEL_HH_
#define _SDD_ORDER_STRATEGIES_VARIABLES_PER_LEVEL_HH_

#include <tuple>

#include "sdd/order/order_builder.hh"

namespace sdd {

/*------------------------------------------------------------------------------------------------*/

/// @brief
template <typename C>
struct variables_per_level
{
  const unsigned int nb_variables;

  variables_per_level(unsigned int nb)
  noexcept
    : nb_variables(nb)
  {}

  order_builder<C>
  operator()(const order_builder<C>& ob)
  const
  {
    if (ob.empty() or nb_variables == 1)
    {
      return ob;
    }
    order_builder<C> current = ob;
    while (current.height() > nb_variables)
    {
      const auto tmp = impl(current, current.height() % nb_variables);
      current = std::get<0>(tmp) << std::get<1>(tmp);
    }
    return current.height() == 1 ? current.nested() : current;
  }

  std::tuple<order_builder<C>/*current*/, order_builder<C>/*next*/, unsigned int/*counter*/>
  impl(const order_builder<C>& ob, unsigned int remainder)
  const
  {
    if (ob.next().empty())
    {
      return std::make_tuple( order_builder<C>(ob.identifier(), ob.nested())
                            , order_builder<C>()
                            , nb_variables + remainder - 2);
    }
    else
    {
      const auto tmp = impl(ob.next(), remainder);
      if (std::get<2>(tmp) == 0) // current hierarchy is full
      {
        return std::make_tuple( order_builder<C>()
                              , order_builder<C>( order_identifier<C>()
                                                , order_builder<C>(ob.identifier(), ob.nested())
                                                    << std::get<0>(tmp))
                                  << std::get<1>(tmp)
                              , nb_variables - 1);
      }
      else
      {
        return std::make_tuple( order_builder<C>(ob.identifier(), ob.nested()) << std::get<0>(tmp)
                              , std::get<1>(tmp)
                              , std::get<2>(tmp) - 1);
      }
    }
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace sdd

#endif // _SDD_ORDER_STRATEGIES_VARIABLES_PER_LEVEL_HH_
<commit_msg>Order strategy to create an order with a maximum number of identifiers per hierarchy.<commit_after>#ifndef _SDD_ORDER_IDENTIFIERS_VARIABLES_PER_HIERARCHY_HH_
#define _SDD_ORDER_IDENTIFIERS_VARIABLES_PER_HIERARCHY_HH_

#include <list>

#include "sdd/order/order_builder.hh"

namespace sdd {

/*------------------------------------------------------------------------------------------------*/

/// @brief Creates an order with a maximum number of identifiers per hierarchy.
template <typename C>
class identifiers_per_hierarchy
{
private:

  const unsigned int nb_variables;

public:

  identifiers_per_hierarchy(unsigned int nb)
  noexcept
    : nb_variables(nb)
  {}

  order_builder<C>
  operator()(order_builder<C> ob)
  const
  {
    if (ob.empty() or nb_variables == 1)
    {
      return ob;
    }

    while (ob.height() > nb_variables)
    {
      const auto packets = packetize(ob);
      order_builder<C> tmp;
      for (auto rcit = packets.rbegin(); rcit != packets.rend(); ++rcit)
      {
        tmp.push(order_identifier<C>(), *rcit);
      }
      ob = tmp;
    }

    return ob;
  }

private:

  std::list<order_builder<C>>
  packetize(const order_builder<C>& ob)
  const
  {
    std::list<order_builder<C>> packets;
    packetize_impl(ob, packets);
    return packets;
  }

  unsigned int
  packetize_impl(const order_builder<C>& ob, std::list<order_builder<C>>& packets)
  const
  {
    if (ob.empty())
    {
      packets.emplace_front();
      return 0;
    }
    else
    {
      const auto nb = packetize_impl(ob.next(), packets);
      if (nb == nb_variables)
      {
        packets.emplace_front(ob.identifier(), ob.nested());
        return 1;
      }
      else
      {
        packets.front().push(ob.identifier(), ob.nested());
        return nb + 1;
      }
    }
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace sdd

#endif // _SDD_ORDER_IDENTIFIERS_VARIABLES_PER_HIERARCHY_HH_
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef LIBUOBJECT_REMOTE_UCONTEXT_IMPL_HH
# define LIBUOBJECT_REMOTE_UCONTEXT_IMPL_HH

# include <libport/package-info.hh>

# include <serialize/binary-o-serializer.hh>
# include <urbi/uobject.hh>
# include <urbi/usyncclient.hh>

namespace urbi
{
  namespace impl
  {
    class URBI_SDK_API RemoteUContextImpl
      : public impl::UContextImpl
    {
    public:
      /// Setup to work on given client
      RemoteUContextImpl(USyncClient* client);
      virtual ~RemoteUContextImpl();
      virtual void newUObjectClass(baseURBIStarter* s);
      virtual void newUObjectHubClass(baseURBIStarterHub* s);
      virtual void uobject_unarmorAndSend(const char* str);
      virtual void send(const char* str);
      virtual void send(const void* buf, size_t size);
      void send(const std::string& s)
      {
        send(s.c_str(), s.size());
      }
      virtual void call(const std::string& object,
                        const std::string& method,
                        UAutoValue v1 = UAutoValue(),
                        UAutoValue v2 = UAutoValue(),
                        UAutoValue v3 = UAutoValue(),
                        UAutoValue v4 = UAutoValue(),
                        UAutoValue v5 = UAutoValue(),
                        UAutoValue v6 = UAutoValue());
      virtual void declare_event(const UEvent* owner);
      virtual void emit(const std::string& object,
                        UAutoValue& v1,
                        UAutoValue& v2,
                        UAutoValue& v3,
                        UAutoValue& v4,
                        UAutoValue& v5,
                        UAutoValue& v6,
                        UAutoValue& v7
                        );
      virtual UObjectMode getRunningMode() const;
      virtual std::pair<int, int> kernelVersion() const;
      virtual void yield() const;
      virtual void yield_until(libport::utime_t deadline) const;
      virtual void yield_until_things_changed() const;
      virtual void side_effect_free_set(bool s);
      virtual bool side_effect_free_get() const;
      virtual UVarImpl* getVarImpl();
      virtual UObjectImpl* getObjectImpl();
      virtual UGenericCallbackImpl* getGenericCallbackImpl();
      virtual TimerHandle setTimer(UTimerCallback* cb);
      virtual void registerHub(UObjectHub*);
      virtual void removeHub(UObjectHub*) ;
      virtual void setHubUpdate(UObjectHub*, ufloat);
      virtual void instanciated(UObject* obj);
      virtual void lock();
      virtual void unlock();
      virtual boost::asio::io_service& getIoService();

    public:
      /// Dispatch a message on our connection
      UCallbackAction dispatcher(const UMessage& msg);
      USyncClient* getClient();
      /** Make a new RTP link with the engine, using hash key \b key.
       * @return the local UObject name
       */
      void makeRTPLink(const std::string& key);

      /// Handle an assignment request.
      void assignMessage(const std::string& name, const UValue& v, time_t ts);

      /// Handle a function call.
      /// \param name  function name (should be array[1])
      /// \param var   where to store the result (should be array[2])
      /// \param args  an array which *will* shitfed by 3 to find the
      ///              function call arguments.
      void evalFunctionMessage(const std::string& name,
                               const std::string& var,
                               UList& args);

      /// Handle a RTP enable/disable message.
      /// \param varname the variable name on which it applies
      /// \param state enable rtp if nonzero
      void setRTPMessage(const std::string& varname,
                         int state);

      /// Enable/disable binary serialization mode.
      void setSerializationMode(bool);

      /// Return the result of the evaluation of the given expression
      UMessage* syncGet(const std::string& exp, libport::utime_t timeout=0);

      USyncClient* backend_;

      /// True if we received a clientError message.
      bool closed_;
#define TABLE(Type, Name)                       \
    private:                                    \
      Type Name ## _;                           \
    public:                                     \
      Type& Name()                              \
      {                                         \
        return Name ## _;                       \
      }
      TABLE(UTable, accessmap);
      TABLE(UTable, eventmap);
      TABLE(UTable, eventendmap);
      TABLE(UTable, functionmap);
      TABLE(UTable, monitormap);
      TABLE(UVarTable, varmap);
      TABLE(UTimerTable, timermap);
#undef TABLE
      UValue localCall(const std::string& object,
                const std::string& method,
                UAutoValue v1 = UAutoValue(),
                UAutoValue v2 = UAutoValue(),
                UAutoValue v3 = UAutoValue(),
                UAutoValue v4 = UAutoValue(),
                UAutoValue v5 = UAutoValue(),
                UAutoValue v6 = UAutoValue(),
                UAutoValue v7 = UAutoValue(),
                UAutoValue v8 = UAutoValue());
      UTable& tableByName(const std::string& n);
      UCallbackAction clientError(const UMessage&);
      UCallbackAction onRTPListenMessage(const UMessage&);
      // Create it on demand.
      UObject* getDummyUObject();
      void onTimer(UTimerCallback* cb);
      UObject* dummyUObject;
      typedef boost::unordered_map<std::string,
        std::pair<libport::AsyncCallHandler, UTimerCallback*> > TimerMap;
      TimerMap timerMap;
      libport::Lockable mapLock;
      // Pool of RTP connections (key= UVar name)
      typedef boost::unordered_map<std::string, UObject*> RTPLinks;
      RTPLinks rtpLinks;
      // Use RTP connections in this context if available
      bool enableRTP;
      unsigned int dispatchDepth;
      // Stream to use for urbiscript output
      LockableOstream* outputStream;
      // True when something was sent. Reset by dispatcher().
      bool dataSent;
      // Send serialized binary messages if set.
      bool serializationMode;
      libport::serialize::BinaryOSerializer* oarchive;
      libport::PackageInfo::Version version;
      #define URBI_REMOTE_RTP_INIT_CHANNEL "__remote_rtp_init"
    };

    class URBI_SDK_API RemoteUObjectImpl: public UObjectImpl
    {
    public:
      virtual ~RemoteUObjectImpl();
      virtual void initialize(UObject* owner);
      virtual void clean();
      virtual void setUpdate(ufloat period);
      virtual bool removeTimer(TimerHandle h);
      void onUpdate();

    private:
      UObject* owner_;
      ufloat period;
      libport::AsyncCallHandler updateHandler;
    };
    class RemoteUGenericCallbackImpl;
    class URBI_SDK_API RemoteUVarImpl: public UVarImpl
    {
    public:
      virtual void initialize(UVar* owner);
      virtual void clean();
      virtual void setOwned();
      virtual void sync();
      virtual void request();
      virtual void keepSynchronized();
      virtual void set(const UValue& v);
      virtual const UValue& get() const;
      virtual ufloat& in();
      virtual ufloat& out();
      virtual UDataType type() const;
      virtual UValue getProp(UProperty prop);
      virtual void setProp(UProperty prop, const UValue& v);
      virtual bool setBypass(bool enable);
      virtual time_t timestamp() const;
      virtual void unnotify();
      void update(const UValue& v);
      void update(const UValue& v, time_t timestamp);
      virtual void useRTP(bool enable);
      virtual void setInputPort(bool enable);
    private:
      // transmit the value to the remote kernel
      void transmit(const UValue& v, libport::utime_t timestamp);
      // Transmit in serialized mode.
      void transmitSerialized(const UValue& v, libport::utime_t time);
      USyncClient* client_;
      UValue value_;
      UVar* owner_;
      time_t timestamp_;
      friend class RemoteUGenericCallbackImpl;
      std::vector<RemoteUGenericCallbackImpl*> callbacks_;
    };

    class URBI_SDK_API RemoteUGenericCallbackImpl: public UGenericCallbackImpl
    {
    public:
      virtual void initialize(UGenericCallback* owner, bool owned);
      virtual void initialize(UGenericCallback* owner);
      virtual void registerCallback();
      virtual void clear();

    private:
      UGenericCallback* owner_;
      friend class RemoteUVarImpl;
    };
  }
}
#endif // !LIBUOBJECT_REMOTE_UCONTEXT_IMPL_HH
<commit_msg>Clarify comments.<commit_after>/*
 * Copyright (C) 2009-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef LIBUOBJECT_REMOTE_UCONTEXT_IMPL_HH
# define LIBUOBJECT_REMOTE_UCONTEXT_IMPL_HH

# include <libport/package-info.hh>

# include <serialize/binary-o-serializer.hh>
# include <urbi/uobject.hh>
# include <urbi/usyncclient.hh>

namespace urbi
{
  namespace impl
  {
    class URBI_SDK_API RemoteUContextImpl
      : public impl::UContextImpl
    {
    public:
      /// Setup to work on given client
      RemoteUContextImpl(USyncClient* client);
      virtual ~RemoteUContextImpl();
      virtual void newUObjectClass(baseURBIStarter* s);
      virtual void newUObjectHubClass(baseURBIStarterHub* s);
      virtual void uobject_unarmorAndSend(const char* str);
      virtual void send(const char* str);
      virtual void send(const void* buf, size_t size);
      void send(const std::string& s)
      {
        send(s.c_str(), s.size());
      }
      virtual void call(const std::string& object,
                        const std::string& method,
                        UAutoValue v1 = UAutoValue(),
                        UAutoValue v2 = UAutoValue(),
                        UAutoValue v3 = UAutoValue(),
                        UAutoValue v4 = UAutoValue(),
                        UAutoValue v5 = UAutoValue(),
                        UAutoValue v6 = UAutoValue());
      virtual void declare_event(const UEvent* owner);
      virtual void emit(const std::string& object,
                        UAutoValue& v1,
                        UAutoValue& v2,
                        UAutoValue& v3,
                        UAutoValue& v4,
                        UAutoValue& v5,
                        UAutoValue& v6,
                        UAutoValue& v7
                        );
      virtual UObjectMode getRunningMode() const;
      virtual std::pair<int, int> kernelVersion() const;
      virtual void yield() const;
      virtual void yield_until(libport::utime_t deadline) const;
      virtual void yield_until_things_changed() const;
      virtual void side_effect_free_set(bool s);
      virtual bool side_effect_free_get() const;
      virtual UVarImpl* getVarImpl();
      virtual UObjectImpl* getObjectImpl();
      virtual UGenericCallbackImpl* getGenericCallbackImpl();
      virtual TimerHandle setTimer(UTimerCallback* cb);
      virtual void registerHub(UObjectHub*);
      virtual void removeHub(UObjectHub*) ;
      virtual void setHubUpdate(UObjectHub*, ufloat);
      virtual void instanciated(UObject* obj);
      virtual void lock();
      virtual void unlock();
      virtual boost::asio::io_service& getIoService();

    public:
      /// Dispatch a message on our connection
      UCallbackAction dispatcher(const UMessage& msg);
      USyncClient* getClient();
      /** Make a new RTP link with the engine, using hash key \b key.
       * The link is established asynchronously and is ready when
       * RTPLinks[key] != 0.
       * Check if initialization is not already in progress by calling
       * RTPLinks.has(key) first.
       */
      void makeRTPLink(const std::string& key);

      /// Handle an assignment request.
      void assignMessage(const std::string& name, const UValue& v, time_t ts);

      /// Handle a function call.
      /// \param name  function name (should be array[1])
      /// \param var   where to store the result (should be array[2])
      /// \param args  an array which *will* shitfed by 3 to find the
      ///              function call arguments.
      void evalFunctionMessage(const std::string& name,
                               const std::string& var,
                               UList& args);

      /// Handle a RTP enable/disable message.
      /// \param varname the variable name on which it applies
      /// \param state enable rtp if nonzero
      void setRTPMessage(const std::string& varname,
                         int state);

      /// Enable/disable binary serialization mode.
      void setSerializationMode(bool);

      /// Return the result of the evaluation of the given expression
      UMessage* syncGet(const std::string& exp, libport::utime_t timeout=0);

      USyncClient* backend_;

      /// True if we received a clientError message.
      bool closed_;
#define TABLE(Type, Name)                       \
    private:                                    \
      Type Name ## _;                           \
    public:                                     \
      Type& Name()                              \
      {                                         \
        return Name ## _;                       \
      }
      TABLE(UTable, accessmap);
      TABLE(UTable, eventmap);
      TABLE(UTable, eventendmap);
      TABLE(UTable, functionmap);
      TABLE(UTable, monitormap);
      TABLE(UVarTable, varmap);
      TABLE(UTimerTable, timermap);
#undef TABLE
      UValue localCall(const std::string& object,
                const std::string& method,
                UAutoValue v1 = UAutoValue(),
                UAutoValue v2 = UAutoValue(),
                UAutoValue v3 = UAutoValue(),
                UAutoValue v4 = UAutoValue(),
                UAutoValue v5 = UAutoValue(),
                UAutoValue v6 = UAutoValue(),
                UAutoValue v7 = UAutoValue(),
                UAutoValue v8 = UAutoValue());
      UTable& tableByName(const std::string& n);
      UCallbackAction clientError(const UMessage&);
      UCallbackAction onRTPListenMessage(const UMessage&);
      // Create it on demand.
      UObject* getDummyUObject();
      void onTimer(UTimerCallback* cb);
      UObject* dummyUObject;
      typedef boost::unordered_map<std::string,
        std::pair<libport::AsyncCallHandler, UTimerCallback*> > TimerMap;
      TimerMap timerMap;
      libport::Lockable mapLock;
      // Pool of RTP connections (key= UVar name)
      typedef boost::unordered_map<std::string, UObject*> RTPLinks;
      RTPLinks rtpLinks;
      // Use RTP connections in this context if available
      bool enableRTP;
      unsigned int dispatchDepth;
      // Stream to use for urbiscript output
      LockableOstream* outputStream;
      // True when something was sent. Reset by dispatcher().
      bool dataSent;
      // Send serialized binary messages if set.
      bool serializationMode;
      libport::serialize::BinaryOSerializer* oarchive;
      libport::PackageInfo::Version version;
      #define URBI_REMOTE_RTP_INIT_CHANNEL "__remote_rtp_init"
    };

    class URBI_SDK_API RemoteUObjectImpl: public UObjectImpl
    {
    public:
      virtual ~RemoteUObjectImpl();
      virtual void initialize(UObject* owner);
      virtual void clean();
      virtual void setUpdate(ufloat period);
      virtual bool removeTimer(TimerHandle h);
      void onUpdate();

    private:
      UObject* owner_;
      ufloat period;
      libport::AsyncCallHandler updateHandler;
    };
    class RemoteUGenericCallbackImpl;
    class URBI_SDK_API RemoteUVarImpl: public UVarImpl
    {
    public:
      virtual void initialize(UVar* owner);
      virtual void clean();
      virtual void setOwned();
      virtual void sync();
      virtual void request();
      virtual void keepSynchronized();
      virtual void set(const UValue& v);
      virtual const UValue& get() const;
      virtual ufloat& in();
      virtual ufloat& out();
      virtual UDataType type() const;
      virtual UValue getProp(UProperty prop);
      virtual void setProp(UProperty prop, const UValue& v);
      virtual bool setBypass(bool enable);
      virtual time_t timestamp() const;
      virtual void unnotify();
      void update(const UValue& v);
      void update(const UValue& v, time_t timestamp);
      virtual void useRTP(bool enable);
      virtual void setInputPort(bool enable);
    private:
      // transmit the value to the remote kernel
      void transmit(const UValue& v, libport::utime_t timestamp);
      // Transmit in serialized mode.
      void transmitSerialized(const UValue& v, libport::utime_t time);
      USyncClient* client_;
      UValue value_;
      UVar* owner_;
      time_t timestamp_;
      friend class RemoteUGenericCallbackImpl;
      std::vector<RemoteUGenericCallbackImpl*> callbacks_;
    };

    class URBI_SDK_API RemoteUGenericCallbackImpl: public UGenericCallbackImpl
    {
    public:
      virtual void initialize(UGenericCallback* owner, bool owned);
      virtual void initialize(UGenericCallback* owner);
      virtual void registerCallback();
      virtual void clear();

    private:
      UGenericCallback* owner_;
      friend class RemoteUVarImpl;
    };
  }
}
#endif // !LIBUOBJECT_REMOTE_UCONTEXT_IMPL_HH
<|endoftext|>


<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord/util/binarymessagereader.h>
#include <fnord/exception.h>
#include <fnord/inspect.h>

namespace fnord {
namespace util {

BinaryMessageReader::BinaryMessageReader(
    void const* buf,
    size_t buf_len) :
    ptr_(buf),
    size_(buf_len),
    pos_(0) {}

uint8_t const* BinaryMessageReader::readUInt8() {
  return static_cast<uint8_t const*>(read(sizeof(uint8_t)));
}

uint16_t const* BinaryMessageReader::readUInt16() {
  return static_cast<uint16_t const*>(read(sizeof(uint16_t)));
}

uint32_t const* BinaryMessageReader::readUInt32() {
  return static_cast<uint32_t const*>(read(sizeof(uint32_t)));
}

uint64_t const* BinaryMessageReader::readUInt64() {
  return static_cast<uint64_t const*>(read(sizeof(uint64_t)));
}

void const* BinaryMessageReader::read(size_t size) {
  return static_cast<void const*>(readString(size));
}

uint64_t BinaryMessageReader::readVarUInt() {
  uint64_t value = 0;

  for (int i = 0; ; ++i) {
    auto b = *((const unsigned char*) read(1));

    value |= (b & 0x7fULL) << (7 * i);

    if (!(b & 0x80U)) {
      break;
    }
  }

  return value;
}

template <>
uint16_t const* BinaryMessageReader::readValue<uint16_t>() {
  return readUInt16();
}

template <>
uint32_t const* BinaryMessageReader::readValue<uint32_t>() {
  return readUInt32();
}

template <>
String const* BinaryMessageReader::readValue<String>() {
  auto len = *readUInt32();
  cur_str_ = String(reinterpret_cast<const char*>(read(len)), len);
  return &cur_str_;
}

char const* BinaryMessageReader::readString(size_t size) {
#ifndef FNORD_NODBEUG
  if ((pos_ + size) > size_) {
    RAISE(kBufferOverflowError, "requested read exceeds message bounds");
  }
#endif

  auto ptr = static_cast<char const*>(ptr_) + pos_;
  pos_ += size;
  return ptr;
}

std::string BinaryMessageReader::readLenencString() {
  auto len = readVarUInt();
  return String((char*) read(len), len);
}

void BinaryMessageReader::rewind() {
  pos_ = 0;
}

void BinaryMessageReader::seekTo(size_t pos) {
#ifndef FNORD_NODBEUG
  if (pos > size_) {
    RAISE(kBufferOverflowError, "requested position exceeds message bounds");
  }
#endif

  pos_ = pos;
}

size_t BinaryMessageReader::remaining() const {
  return size_ - pos_;
}

size_t BinaryMessageReader::position() const {
  return pos_;
}

}
}

<commit_msg>BinaryMessageReader::readDouble<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <fnord/util/binarymessagereader.h>
#include <fnord/exception.h>
#include <fnord/IEEE754.h>

namespace fnord {
namespace util {

BinaryMessageReader::BinaryMessageReader(
    void const* buf,
    size_t buf_len) :
    ptr_(buf),
    size_(buf_len),
    pos_(0) {}

uint8_t const* BinaryMessageReader::readUInt8() {
  return static_cast<uint8_t const*>(read(sizeof(uint8_t)));
}

uint16_t const* BinaryMessageReader::readUInt16() {
  return static_cast<uint16_t const*>(read(sizeof(uint16_t)));
}

uint32_t const* BinaryMessageReader::readUInt32() {
  return static_cast<uint32_t const*>(read(sizeof(uint32_t)));
}

uint64_t const* BinaryMessageReader::readUInt64() {
  return static_cast<uint64_t const*>(read(sizeof(uint64_t)));
}

void const* BinaryMessageReader::read(size_t size) {
  return static_cast<void const*>(readString(size));
}

uint64_t BinaryMessageReader::readVarUInt() {
  uint64_t value = 0;

  for (int i = 0; ; ++i) {
    auto b = *((const unsigned char*) read(1));

    value |= (b & 0x7fULL) << (7 * i);

    if (!(b & 0x80U)) {
      break;
    }
  }

  return value;
}

template <>
uint16_t const* BinaryMessageReader::readValue<uint16_t>() {
  return readUInt16();
}

template <>
uint32_t const* BinaryMessageReader::readValue<uint32_t>() {
  return readUInt32();
}

template <>
String const* BinaryMessageReader::readValue<String>() {
  auto len = *readUInt32();
  cur_str_ = String(reinterpret_cast<const char*>(read(len)), len);
  return &cur_str_;
}

char const* BinaryMessageReader::readString(size_t size) {
#ifndef FNORD_NODBEUG
  if ((pos_ + size) > size_) {
    RAISE(kBufferOverflowError, "requested read exceeds message bounds");
  }
#endif

  auto ptr = static_cast<char const*>(ptr_) + pos_;
  pos_ += size;
  return ptr;
}

double BinaryMessageReader::readDouble() {
  return IEEE754::fromBytes(
      *static_cast<uint64_t const*>(read(sizeof(uint64_t))));
}

std::string BinaryMessageReader::readLenencString() {
  auto len = readVarUInt();
  return String((char*) read(len), len);
}

void BinaryMessageReader::rewind() {
  pos_ = 0;
}

void BinaryMessageReader::seekTo(size_t pos) {
#ifndef FNORD_NODBEUG
  if (pos > size_) {
    RAISE(kBufferOverflowError, "requested position exceeds message bounds");
  }
#endif

  pos_ = pos;
}

size_t BinaryMessageReader::remaining() const {
  return size_ - pos_;
}

size_t BinaryMessageReader::position() const {
  return pos_;
}

}
}

<|endoftext|>


<commit_before>#include "vast/program.h"

#include <cstdlib>
#include <iostream>
#include <boost/exception/diagnostic_information.hpp>
#include "vast/archive.h"
#include "vast/exception.h"
#include "vast/id_tracker.h"
#include "vast/index.h"
#include "vast/ingestor.h"
#include "vast/logger.h"
#include "vast/query_client.h"
#include "vast/search.h"
#include "vast/comm/broccoli.h"
#include "vast/detail/cppa_type_info.h"
#include "vast/fs/path.h"
#include "vast/fs/operations.h"
#include "vast/meta/schema_manager.h"
#include "vast/util/profiler.h"
#include "config.h"

#ifdef USE_PERFTOOLS_CPU_PROFILER
#include <google/profiler.h>
#endif
#ifdef USE_PERFTOOLS_HEAP_PROFILER
#include <google/heap-profiler.h>
#endif

namespace vast {

/// Declaration of global (extern) variables.
logger* LOGGER;

program::program()
  : terminating_(false)
  , return_(EXIT_FAILURE)
{
}

bool program::init(std::string const& filename)
{
  try
  {
    config_.load(filename);
    do_init();
    return true;
  }
  catch (boost::program_options::unknown_option const& e)
  {
    std::cerr << e.what();
  }

  return false;
}

bool program::init(int argc, char *argv[])
{
  try
  {
    config_.load(argc, argv);

    if (argc < 2 || config_.check("help") || config_.check("advanced"))
    {
      config_.print(std::cerr, config_.check("advanced"));
      return false;
    }

    do_init();
    return true;
  }
  catch (error::config const& e)
  {
    std::cerr << e.what() << std::endl;
  }
  catch (boost::program_options::unknown_option const& e)
  {
    std::cerr << e.what() << ", try -h or --help" << std::endl;
  }
  catch (boost::program_options::invalid_command_line_syntax const& e)
  {
    std::cerr << "invalid command line: " << e.what() << std::endl;
  }
  catch (boost::exception const& e)
  {
    std::cerr << boost::diagnostic_information(e);
  }

  return false;
}

void program::start()
{
  using namespace cppa;
  detail::cppa_announce_types();

  auto log_dir = config_.get<fs::path>("directory") / "log";
  assert(fs::exists(log_dir));

  try
  {
#ifdef USE_PERFTOOLS_HEAP_PROFILER
    if (config_.check("perftools-heap"))
    {
      LOG(info, core) << "starting Gperftools CPU profiler";
      HeapProfilerStart((log_dir / "heap.profile").string().data());
    }
#endif
#ifdef USE_PERFTOOLS_CPU_PROFILER
    if (config_.check("perftools-cpu"))
    {
      LOG(info, core) << "starting Gperftools heap profiler";
      ProfilerStart((log_dir / "cpu.profile").string().data());
    }
#endif

    if (config_.check("profile"))
    {
      auto const& filename = log_dir / "profiler.log";
      auto ms = config_.get<unsigned>("profile");
      profiler_ = spawn<util::profiler>(filename.string(),
                                        std::chrono::seconds(ms));
      send(profiler_, atom("run"));
    }

    schema_manager_ = spawn<meta::schema_manager>();
    if (config_.check("schema"))
    {
      send(schema_manager_, atom("load"), config_.get<std::string>("schema"));

      if (config_.check("print-schema"))
      {
        send(schema_manager_, atom("print"));
        receive(
            on(atom("schema"), arg_match) >> [](std::string const& schema)
            {
              std::cout << schema << std::endl;
            });

        return;
      }
    }

    if (config_.check("tracker-actor") || config_.check("all-server"))
      tracker_ = spawn<id_tracker>(
          (config_.get<fs::path>("directory") / "id").string());
    else
      tracker_ = remote_actor(
          config_.get<std::string>("tracker.host"),
          config_.get<unsigned>("tracker.port"));

    if (config_.check("archive-actor") || config_.check("all-server"))
      archive_ = spawn<archive>(
          (config_.get<fs::path>("directory") / "archive").string(),
          config_.get<size_t>("archive.max-segments"));
    else
      archive_ = remote_actor(
          config_.get<std::string>("archive.host"),
          config_.get<unsigned>("archive.port"));

    if (config_.check("index-actor") || config_.check("all-server"))
        index_ = spawn<index>(
            archive_,
            (config_.get<fs::path>("directory") / "index").string());
    else
      index_ = remote_actor(
          config_.get<std::string>("index.host"),
          config_.get<unsigned>("index.port"));

    if (config_.check("ingestor-actor"))
    {
      comm::broccoli::init(config_.check("broccoli-messages"),
                           config_.check("broccoli-calltrace"));

      ingestor_ = spawn<ingestor>(tracker_, archive_, index_);

      send(ingestor_, atom("initialize"),
          config_.get<size_t>("ingest.max-events-per-chunk"),
          config_.get<size_t>("ingest.max-segment-size") * 1000000);

      if (config_.check("ingest.events"))
      {
        auto host = config_.get<std::string>("ingest.host");
        auto port = config_.get<unsigned>("ingest.port");
        auto events = config_.get<std::vector<std::string>>("ingest.events");
        send(ingestor_, atom("ingest"), atom("broccoli"), host, port, events);
      }

      if (config_.check("ingest.file-names"))
      {
        auto type = config_.get<std::string>("ingest.file-type");
        auto files = config_.get<std::vector<std::string>>("ingest.file-names");
        for (auto& file : files)
        {
          if (fs::exists(file))
            send(ingestor_, atom("ingest"), type, file);
          else
            LOG(error, core) << "no such file: " << file;
        }
      }
    }

    if (config_.check("search-actor") || config_.check("all-server"))
    {
      search_ = spawn<search>(archive_, index_);

      //config_.get<std::string>("search.host")
      LOG(verbose, core) << "publishing search at *:"
          << config_.get<unsigned>("search.port");
      publish(search_, config_.get<unsigned>("search.port"));
    }
    else
    {
      LOG(verbose, core) << "connecting to search at "
          << config_.get<std::string>("search.host") << ":"
          << config_.get<unsigned>("search.port");
      search_ = remote_actor(
          config_.get<std::string>("search.host"),
          config_.get<unsigned>("search.port"));
    }

    if (config_.check("query"))
    {
      auto paginate = config_.get<unsigned>("client.paginate");
      auto& expression = config_.get<std::string>("query");
      query_client_ = spawn<query_client>(search_, paginate);
      send(query_client_, atom("query"), atom("create"), expression);
    }

    await_all_others_done();
    return_ = EXIT_SUCCESS;
  }
  catch (network_error const& e)
  {
      LOG(error, core) << "network error: " << e.what();
  }
  catch (...)
  {
    LOG(fatal, core)
      << "exception details:\n"
      << boost::current_exception_diagnostic_information();
  }
}

void program::stop()
{
  using namespace cppa;

  if (terminating_)
  {
    return_ = EXIT_FAILURE;
    return;
  }

  terminating_ = true;

  auto shutdown = make_any_tuple(atom("shutdown"));

  if (config_.check("query"))
    query_client_ << shutdown;

  if (config_.check("search-actor") || config_.check("all-server"))
    search_ << shutdown;

  if (config_.check("ingestor-actor"))
    ingestor_ << shutdown;

  if (config_.check("index-actor") || config_.check("all-server"))
    index_ << shutdown;

  if (config_.check("archive-actor") || config_.check("all-server"))
    archive_ << shutdown;

  if (config_.check("tracker-actor") || config_.check("all-server"))
    tracker_ << shutdown;

  schema_manager_ << shutdown;

  if (config_.check("profile"))
    profiler_ << shutdown;

#ifdef USE_PERFTOOLS_CPU_PROFILER

  if (config_.check("perftools-cpu"))
  {
    ProfilerState state;
    ProfilerGetCurrentState(&state);
    LOG(info, core)
      << "Gperftools CPU profiler gathered "
      <<  state.samples_gathered << " samples"
      << " in file " << state.profile_name;

    LOG(info, core) << "stopping Gperftools CPU profiler";
    ProfilerStop();
  }
#endif
#ifdef USE_PERFTOOLS_HEAP_PROFILER
  if (config_.check("perftools-heap") && IsHeapProfilerRunning())
  {
    LOG(info, core) << "stopping Gperftools heap profiler";
    HeapProfilerDump("cleanup");
    HeapProfilerStop();
  }
#endif

  return_ = EXIT_SUCCESS;
}

int program::end()
{
  switch (return_)
  {
    case EXIT_SUCCESS:
      LOG(info, core) << "vast terminated cleanly";
      break;

    case EXIT_FAILURE:
      LOG(info, core) << "vast terminated with errors";
      break;

    default:
      assert(! "invalid return code");
  }

  return return_;
}

void program::do_init()
{
  auto vast_dir = config_.get<fs::path>("directory");
  if (! fs::exists(vast_dir))
    fs::mkdir(vast_dir);

  auto log_dir = vast_dir / "log";
  if (! fs::exists(log_dir))
      fs::mkdir(log_dir);

  LOGGER = new logger(
      static_cast<logger::level>(config_.get<int>("console-verbosity")),
      static_cast<logger::level>(config_.get<int>("logfile-verbosity")),
      log_dir / "vast.log");

  LOG(verbose, core) << " _   _____   __________";
  LOG(verbose, core) << "| | / / _ | / __/_  __/";
  LOG(verbose, core) << "| |/ / __ |_\\ \\  / / ";
  LOG(verbose, core) << "|___/_/ |_/___/ /_/  " << VAST_VERSION;
  LOG(verbose, core) << "";
}

} // namespace vast
<commit_msg>Publish remote actors.<commit_after>#include "vast/program.h"

#include <cstdlib>
#include <iostream>
#include <boost/exception/diagnostic_information.hpp>
#include "vast/archive.h"
#include "vast/exception.h"
#include "vast/id_tracker.h"
#include "vast/index.h"
#include "vast/ingestor.h"
#include "vast/logger.h"
#include "vast/query_client.h"
#include "vast/search.h"
#include "vast/comm/broccoli.h"
#include "vast/detail/cppa_type_info.h"
#include "vast/fs/path.h"
#include "vast/fs/operations.h"
#include "vast/meta/schema_manager.h"
#include "vast/util/profiler.h"
#include "config.h"

#ifdef USE_PERFTOOLS_CPU_PROFILER
#include <google/profiler.h>
#endif
#ifdef USE_PERFTOOLS_HEAP_PROFILER
#include <google/heap-profiler.h>
#endif

namespace vast {

/// Declaration of global (extern) variables.
logger* LOGGER;

program::program()
  : terminating_(false)
  , return_(EXIT_FAILURE)
{
}

bool program::init(std::string const& filename)
{
  try
  {
    config_.load(filename);
    do_init();
    return true;
  }
  catch (boost::program_options::unknown_option const& e)
  {
    std::cerr << e.what();
  }

  return false;
}

bool program::init(int argc, char *argv[])
{
  try
  {
    config_.load(argc, argv);

    if (argc < 2 || config_.check("help") || config_.check("advanced"))
    {
      config_.print(std::cerr, config_.check("advanced"));
      return false;
    }

    do_init();
    return true;
  }
  catch (error::config const& e)
  {
    std::cerr << e.what() << std::endl;
  }
  catch (boost::program_options::unknown_option const& e)
  {
    std::cerr << e.what() << ", try -h or --help" << std::endl;
  }
  catch (boost::program_options::invalid_command_line_syntax const& e)
  {
    std::cerr << "invalid command line: " << e.what() << std::endl;
  }
  catch (boost::exception const& e)
  {
    std::cerr << boost::diagnostic_information(e);
  }

  return false;
}

void program::start()
{
  using namespace cppa;
  detail::cppa_announce_types();

  auto log_dir = config_.get<fs::path>("directory") / "log";
  assert(fs::exists(log_dir));

  try
  {
#ifdef USE_PERFTOOLS_HEAP_PROFILER
    if (config_.check("perftools-heap"))
    {
      LOG(info, core) << "starting Gperftools CPU profiler";
      HeapProfilerStart((log_dir / "heap.profile").string().data());
    }
#endif
#ifdef USE_PERFTOOLS_CPU_PROFILER
    if (config_.check("perftools-cpu"))
    {
      LOG(info, core) << "starting Gperftools heap profiler";
      ProfilerStart((log_dir / "cpu.profile").string().data());
    }
#endif

    if (config_.check("profile"))
    {
      auto const& filename = log_dir / "profiler.log";
      auto ms = config_.get<unsigned>("profile");
      profiler_ = spawn<util::profiler>(filename.string(),
                                        std::chrono::seconds(ms));
      send(profiler_, atom("run"));
    }

    schema_manager_ = spawn<meta::schema_manager>();
    if (config_.check("schema"))
    {
      send(schema_manager_, atom("load"), config_.get<std::string>("schema"));

      if (config_.check("print-schema"))
      {
        send(schema_manager_, atom("print"));
        receive(
            on(atom("schema"), arg_match) >> [](std::string const& schema)
            {
              std::cout << schema << std::endl;
            });

        return;
      }
    }

    if (config_.check("tracker-actor") || config_.check("all-server"))
    {
      tracker_ = spawn<id_tracker>(
          (config_.get<fs::path>("directory") / "id").string());

      LOG(verbose, core) << "publishing tracker at *:"
          << config_.get<unsigned>("tracker.port");
      publish(tracker_, config_.get<unsigned>("tracker.port"));
    }
    else
    {
      tracker_ = remote_actor(
          config_.get<std::string>("tracker.host"),
          config_.get<unsigned>("tracker.port"));
    }

    if (config_.check("archive-actor") || config_.check("all-server"))
    {
      archive_ = spawn<archive>(
          (config_.get<fs::path>("directory") / "archive").string(),
          config_.get<size_t>("archive.max-segments"));

      LOG(verbose, core) << "publishing archive at *:"
          << config_.get<unsigned>("archive.port");
      publish(archive_, config_.get<unsigned>("archive.port"));
    }
    else
    {
      archive_ = remote_actor(
          config_.get<std::string>("archive.host"),
          config_.get<unsigned>("archive.port"));
    }

    if (config_.check("index-actor") || config_.check("all-server"))
    {
        index_ = spawn<index>(
            archive_,
            (config_.get<fs::path>("directory") / "index").string());

      LOG(verbose, core) << "publishing index at *:"
          << config_.get<unsigned>("index.port");
      publish(index_, config_.get<unsigned>("index.port"));
    }
    else
    {
      index_ = remote_actor(
          config_.get<std::string>("index.host"),
          config_.get<unsigned>("index.port"));
    }

    if (config_.check("ingestor-actor"))
    {
      comm::broccoli::init(config_.check("broccoli-messages"),
                           config_.check("broccoli-calltrace"));

      ingestor_ = spawn<ingestor>(tracker_, archive_, index_);

      send(ingestor_, atom("initialize"),
          config_.get<size_t>("ingest.max-events-per-chunk"),
          config_.get<size_t>("ingest.max-segment-size") * 1000000);

      if (config_.check("ingest.events"))
      {
        auto host = config_.get<std::string>("ingest.host");
        auto port = config_.get<unsigned>("ingest.port");
        auto events = config_.get<std::vector<std::string>>("ingest.events");
        send(ingestor_, atom("ingest"), atom("broccoli"), host, port, events);
      }

      if (config_.check("ingest.file-names"))
      {
        auto type = config_.get<std::string>("ingest.file-type");
        auto files = config_.get<std::vector<std::string>>("ingest.file-names");
        for (auto& file : files)
        {
          if (fs::exists(file))
            send(ingestor_, atom("ingest"), type, file);
          else
            LOG(error, core) << "no such file: " << file;
        }
      }
    }

    if (config_.check("search-actor") || config_.check("all-server"))
    {
      search_ = spawn<search>(archive_, index_);

      LOG(verbose, core) << "publishing search at *:"
          << config_.get<unsigned>("search.port");
      publish(search_, config_.get<unsigned>("search.port"));
    }
    else
    {
      LOG(verbose, core) << "connecting to search at "
          << config_.get<std::string>("search.host") << ":"
          << config_.get<unsigned>("search.port");
      search_ = remote_actor(
          config_.get<std::string>("search.host"),
          config_.get<unsigned>("search.port"));
    }

    if (config_.check("query"))
    {
      auto paginate = config_.get<unsigned>("client.paginate");
      auto& expression = config_.get<std::string>("query");
      query_client_ = spawn<query_client>(search_, paginate);
      send(query_client_, atom("query"), atom("create"), expression);
    }

    await_all_others_done();
    return_ = EXIT_SUCCESS;
  }
  catch (network_error const& e)
  {
      LOG(error, core) << "network error: " << e.what();
  }
  catch (...)
  {
    LOG(fatal, core)
      << "exception details:\n"
      << boost::current_exception_diagnostic_information();
  }
}

void program::stop()
{
  using namespace cppa;

  if (terminating_)
  {
    return_ = EXIT_FAILURE;
    return;
  }

  terminating_ = true;

  auto shutdown = make_any_tuple(atom("shutdown"));

  if (config_.check("query"))
    query_client_ << shutdown;

  if (config_.check("search-actor") || config_.check("all-server"))
    search_ << shutdown;

  if (config_.check("ingestor-actor"))
    ingestor_ << shutdown;

  if (config_.check("index-actor") || config_.check("all-server"))
    index_ << shutdown;

  if (config_.check("archive-actor") || config_.check("all-server"))
    archive_ << shutdown;

  if (config_.check("tracker-actor") || config_.check("all-server"))
    tracker_ << shutdown;

  schema_manager_ << shutdown;

  if (config_.check("profile"))
    profiler_ << shutdown;

#ifdef USE_PERFTOOLS_CPU_PROFILER

  if (config_.check("perftools-cpu"))
  {
    ProfilerState state;
    ProfilerGetCurrentState(&state);
    LOG(info, core)
      << "Gperftools CPU profiler gathered "
      <<  state.samples_gathered << " samples"
      << " in file " << state.profile_name;

    LOG(info, core) << "stopping Gperftools CPU profiler";
    ProfilerStop();
  }
#endif
#ifdef USE_PERFTOOLS_HEAP_PROFILER
  if (config_.check("perftools-heap") && IsHeapProfilerRunning())
  {
    LOG(info, core) << "stopping Gperftools heap profiler";
    HeapProfilerDump("cleanup");
    HeapProfilerStop();
  }
#endif

  return_ = EXIT_SUCCESS;
}

int program::end()
{
  switch (return_)
  {
    case EXIT_SUCCESS:
      LOG(info, core) << "vast terminated cleanly";
      break;

    case EXIT_FAILURE:
      LOG(info, core) << "vast terminated with errors";
      break;

    default:
      assert(! "invalid return code");
  }

  return return_;
}

void program::do_init()
{
  auto vast_dir = config_.get<fs::path>("directory");
  if (! fs::exists(vast_dir))
    fs::mkdir(vast_dir);

  auto log_dir = vast_dir / "log";
  if (! fs::exists(log_dir))
      fs::mkdir(log_dir);

  LOGGER = new logger(
      static_cast<logger::level>(config_.get<int>("console-verbosity")),
      static_cast<logger::level>(config_.get<int>("logfile-verbosity")),
      log_dir / "vast.log");

  LOG(verbose, core) << " _   _____   __________";
  LOG(verbose, core) << "| | / / _ | / __/_  __/";
  LOG(verbose, core) << "| |/ / __ |_\\ \\  / / ";
  LOG(verbose, core) << "|___/_/ |_/___/ /_/  " << VAST_VERSION;
  LOG(verbose, core) << "";
}

} // namespace vast
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2002 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "global.h"
#include "MainWindow.h"
#include "BzfWindow.h"
#include "bzfgl.h"

//
// MainWindow
//

MainWindow::MainWindow(BzfWindow* _window) :
				window(_window),
				quit(False),
				quadrant(FullWindow),
				isFullscreen(False),
				isFullView(True),
				allowMouseGrab(True),
				zoomFactor(1),
				width(0),
				minWidth(MinX),
				minHeight(MinY)
{
  window->addResizeCallback(resizeCB, this);
  resize();
}

MainWindow::~MainWindow()
{
  window->removeResizeCallback(resizeCB, this);
}

void			MainWindow::setZoomFactor(int _zoomFactor)
{
  zoomFactor = _zoomFactor;
}

void			MainWindow::setQuit()
{
  quit = True;
}

void			MainWindow::setMinSize(int _minWidth, int _minHeight)
{
  minWidth = _minWidth;
  minHeight = _minHeight;
  window->setMinSize(minWidth, minHeight);
  resize();
}

void			MainWindow::setPosition(int x, int y)
{
  window->setPosition(x, y);
}

void			MainWindow::setSize(int width, int height)
{
  window->setSize(width, height);
  resize();
}

void			MainWindow::showWindow(boolean on)
{
  window->showWindow(on);
  if (on) resize();
}

void			MainWindow::warpMouse()
{
  // move mouse to center of view window (zero motion box)
  int y = height >> 1;
  if (quadrant != FullWindow) y += ((trueHeight+1) >> 1) - yOrigin;
  window->warpMouse((width >> 1) + xOrigin, y);
}

void			MainWindow::getMousePosition(int& mx, int& my) const
{
  window->getMouse(mx, my);
  mx -= (width >> 1) + xOrigin;
  my -= (height >> 1);
  if (quadrant != FullWindow) my -= ((trueHeight+1) >> 1) - yOrigin;
}

void			MainWindow::grabMouse()
{
  if (allowMouseGrab) window->grabMouse();
}

void			MainWindow::ungrabMouse()
{
  if (allowMouseGrab) window->ungrabMouse();
}

boolean			MainWindow::getFullscreen()
{
  return isFullscreen;
}

void			MainWindow::setFullscreen()
{
  isFullscreen = True;
  window->setFullscreen();
  resize();
}

void			MainWindow::setFullView(boolean _isFullView)
{
  isFullView = _isFullView;
}

void			MainWindow::setNoMouseGrab()
{
  allowMouseGrab = False;
}

void			MainWindow::setQuadrant(Quadrant _quadrant)
{
  int inWidth = trueWidth;
  if (inWidth < MinX) inWidth = MinX;
  int inHeight = trueHeight;
  if (inHeight < MinY) inHeight = MinY;

  quadrant = _quadrant;
  switch (quadrant) {
    default:
    case FullWindow:
      width = inWidth;
      height = inHeight;
      if (isFullView)
        viewHeight = height;
      else
        viewHeight = inHeight * 3 / 4;
      xOrigin = 0;
      yOrigin = 0;
      break;
    case UpperLeft:
      width = inWidth >> 1;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = (inHeight+1) >> 1;
      break;
    case UpperRight:
      width = (inWidth+1) >> 1;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = inWidth >> 1;
      yOrigin = (inHeight+1) >> 1;
      break;
    case LowerLeft:
      width = inWidth >> 1;
      height = (inHeight+1) >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = 0;
      break;
    case LowerRight:
      width = (inWidth+1) >> 1;
      height = (inHeight+1) >> 1;
      viewHeight = height;
      xOrigin = inWidth >> 1;
      yOrigin = 0;
      break;
    case UpperHalf:
      width = inWidth;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = (inHeight+1) >> 1;
      break;
    case LowerHalf:
      width = inWidth;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = 0;
      break;
    case ZoomRegion:
      width = inWidth;
      height = inHeight;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = 0;
      break;
  }

  if (quadrant == ZoomRegion) {
    width = inWidth / zoomFactor + 1;
    height = inHeight / zoomFactor + 1;
  }

  glViewport(xOrigin, yOrigin, width, height);
}

void			MainWindow::resize()
{
  window->getSize(trueWidth, trueHeight);
  window->makeCurrent();
  setQuadrant(quadrant);
}

void			MainWindow::resizeCB(void* _self)
{
  MainWindow* self = (MainWindow*)_self;
  self->resize();
}

boolean			MainWindow::joystick() const
{
  return window->joystick();
}

void			MainWindow::getJoyPosition(int& mx, int& my) const
{
  window->getJoy(mx, my);
  mx = ((width >> 1)*mx)/(900);
  my = ((height >> 1)*my)/(900);
}

unsigned long                  MainWindow::getJoyButtonSet() const
{
  return window->getJoyButtons();
}

// ex: shiftwidth=2 tabstop=8
<commit_msg>mouse center<commit_after>/* bzflag
 * Copyright (c) 1993 - 2002 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "global.h"
#include "MainWindow.h"
#include "BzfWindow.h"
#include "bzfgl.h"

//
// MainWindow
//

MainWindow::MainWindow(BzfWindow* _window) :
				window(_window),
				quit(False),
				quadrant(FullWindow),
				isFullscreen(False),
				isFullView(True),
				allowMouseGrab(True),
				zoomFactor(1),
				width(0),
				minWidth(MinX),
				minHeight(MinY)
{
  window->addResizeCallback(resizeCB, this);
  resize();
}

MainWindow::~MainWindow()
{
  window->removeResizeCallback(resizeCB, this);
}

void			MainWindow::setZoomFactor(int _zoomFactor)
{
  zoomFactor = _zoomFactor;
}

void			MainWindow::setQuit()
{
  quit = True;
}

void			MainWindow::setMinSize(int _minWidth, int _minHeight)
{
  minWidth = _minWidth;
  minHeight = _minHeight;
  window->setMinSize(minWidth, minHeight);
  resize();
}

void			MainWindow::setPosition(int x, int y)
{
  window->setPosition(x, y);
}

void			MainWindow::setSize(int width, int height)
{
  window->setSize(width, height);
  resize();
}

void			MainWindow::showWindow(boolean on)
{
  window->showWindow(on);
  if (on) resize();
}

void			MainWindow::warpMouse()
{
  // move mouse to center of view window (zero motion box)
  int y = viewHeight >> 1;
  if (quadrant != FullWindow) y += ((trueHeight+1) >> 1) - yOrigin;
  window->warpMouse((width >> 1) + xOrigin, y);
}

void			MainWindow::getMousePosition(int& mx, int& my) const
{
  window->getMouse(mx, my);
  mx -= (width >> 1) + xOrigin;
  my -= (viewHeight >> 1);
  if (quadrant != FullWindow) my -= ((trueHeight+1) >> 1) - yOrigin;
}

void			MainWindow::grabMouse()
{
  if (allowMouseGrab) window->grabMouse();
}

void			MainWindow::ungrabMouse()
{
  if (allowMouseGrab) window->ungrabMouse();
}

boolean			MainWindow::getFullscreen()
{
  return isFullscreen;
}

void			MainWindow::setFullscreen()
{
  isFullscreen = True;
  window->setFullscreen();
  resize();
}

void			MainWindow::setFullView(boolean _isFullView)
{
  isFullView = _isFullView;
}

void			MainWindow::setNoMouseGrab()
{
  allowMouseGrab = False;
}

void			MainWindow::setQuadrant(Quadrant _quadrant)
{
  int inWidth = trueWidth;
  if (inWidth < MinX) inWidth = MinX;
  int inHeight = trueHeight;
  if (inHeight < MinY) inHeight = MinY;

  quadrant = _quadrant;
  switch (quadrant) {
    default:
    case FullWindow:
      width = inWidth;
      height = inHeight;
      if (isFullView)
        viewHeight = height;
      else
        viewHeight = inHeight * 3 / 4;
      xOrigin = 0;
      yOrigin = 0;
      break;
    case UpperLeft:
      width = inWidth >> 1;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = (inHeight+1) >> 1;
      break;
    case UpperRight:
      width = (inWidth+1) >> 1;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = inWidth >> 1;
      yOrigin = (inHeight+1) >> 1;
      break;
    case LowerLeft:
      width = inWidth >> 1;
      height = (inHeight+1) >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = 0;
      break;
    case LowerRight:
      width = (inWidth+1) >> 1;
      height = (inHeight+1) >> 1;
      viewHeight = height;
      xOrigin = inWidth >> 1;
      yOrigin = 0;
      break;
    case UpperHalf:
      width = inWidth;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = (inHeight+1) >> 1;
      break;
    case LowerHalf:
      width = inWidth;
      height = inHeight >> 1;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = 0;
      break;
    case ZoomRegion:
      width = inWidth;
      height = inHeight;
      viewHeight = height;
      xOrigin = 0;
      yOrigin = 0;
      break;
  }

  if (quadrant == ZoomRegion) {
    width = inWidth / zoomFactor + 1;
    height = inHeight / zoomFactor + 1;
  }

  glViewport(xOrigin, yOrigin, width, height);
}

void			MainWindow::resize()
{
  window->getSize(trueWidth, trueHeight);
  window->makeCurrent();
  setQuadrant(quadrant);
}

void			MainWindow::resizeCB(void* _self)
{
  MainWindow* self = (MainWindow*)_self;
  self->resize();
}

boolean			MainWindow::joystick() const
{
  return window->joystick();
}

void			MainWindow::getJoyPosition(int& mx, int& my) const
{
  window->getJoy(mx, my);
  mx = ((width >> 1)*mx)/(900);
  my = ((height >> 1)*my)/(900);
}

unsigned long                  MainWindow::getJoyButtonSet() const
{
  return window->getJoyButtons();
}

// ex: shiftwidth=2 tabstop=8
<|endoftext|>