예제 #1
0
파일: log.cpp 프로젝트: alogg/dolfin
//-----------------------------------------------------------------------------
void dolfin::deprecation(std::string feature,
                         std::string version,
                         std::string message, ...)
{
  read(buffer.get(), message);
  LogManager::logger.deprecation(feature, version, buffer.get());
}
예제 #2
0
파일: log.cpp 프로젝트: alogg/dolfin
//-----------------------------------------------------------------------------
void dolfin::dolfin_error(std::string location,
                          std::string task,
                          std::string reason, ...)
{
  read(buffer.get(), reason);
  LogManager::logger.dolfin_error(location, task, buffer.get());
}
예제 #3
0
파일: log.cpp 프로젝트: alogg/dolfin
//-----------------------------------------------------------------------------
void dolfin::info(std::string msg, ...)
{
  if (!LogManager::logger.is_active())
    return; // optimization
  read(buffer.get(), msg);
  LogManager::logger.log(buffer.get());
}
예제 #4
0
/** Sets up the spline object by with the parameters and attributes
 *
 * @param x :: The array of x values defining the spline
 * @param y :: The array of y values defining the spline
 * @param n :: The size of the arrays
 */
void CubicSpline::setupInput(boost::scoped_array<double> &x,
                             boost::scoped_array<double> &y, int n) const {
  // Populate data points from the input attributes and parameters
  bool xSortFlag = false;

  for (int i = 0; i < n; ++i) {
    std::string num = boost::lexical_cast<std::string>(i);

    std::string xName = "x" + num;
    std::string yName = "y" + num;

    x[i] = getAttribute(xName).asDouble();

    // if x[i] is out of order with its neighbours
    if (i > 1 && i < n && (x[i - 1] < x[i - 2] || x[i - 1] > x[i])) {
      xSortFlag = true;
    }

    y[i] = getParameter(yName);
  }

  // sort the data points if necessary
  if (xSortFlag) {
    g_log.warning() << "Spline x parameters are not in ascending order. Values "
                       "will be sorted." << std::endl;
    std::sort(x.get(), x.get() + n);
  }

  // pass values to GSL objects
  initGSLObjects(x, y, n);
  m_recalculateSpline = false;
}
예제 #5
0
    void FileAllocator::ensureLength(int fd , long size) {
#if !defined(_WIN32)
        if (useSparseFiles(fd)) {
            LOG(1) << "using ftruncate to create a sparse file" << endl;
            int ret = ftruncate(fd, size);
            uassert(16063, "ftruncate failed: " + errnoWithDescription(), ret == 0);
            return;
        }
#endif

#if defined(__linux__)
        int ret = posix_fallocate(fd,0,size);
        if ( ret == 0 )
            return;

        log() << "FileAllocator: posix_fallocate failed: " << errnoWithDescription( ret ) << " falling back" << endl;
#endif

        off_t filelen = lseek( fd, 0, SEEK_END );
        if ( filelen < size ) {
            if (filelen != 0) {
                stringstream ss;
                ss << "failure creating new datafile; lseek failed for fd " << fd << " with errno: " << errnoWithDescription();
                uassert( 10440 ,  ss.str(), filelen == 0 );
            }
            // Check for end of disk.

            uassert( 10441 ,  str::stream() << "Unable to allocate new file of size " << size << ' ' << errnoWithDescription(),
                     size - 1 == lseek(fd, size - 1, SEEK_SET) );
            uassert( 10442 ,  str::stream() << "Unable to allocate new file of size " << size << ' ' << errnoWithDescription(),
                     1 == write(fd, "", 1) );

            // File expansion is completed here. Do not do the zeroing out on OS-es where there
            // is no risk of triggering allocation-related bugs such as
            // http://support.microsoft.com/kb/2731284.
            //
            if (!ProcessInfo::isDataFileZeroingNeeded()) {
                return;
            }

            lseek(fd, 0, SEEK_SET);

            const long z = 256 * 1024;
            const boost::scoped_array<char> buf_holder (new char[z]);
            char* buf = buf_holder.get();
            memset(buf, 0, z);
            long left = size;
            while ( left > 0 ) {
                long towrite = left;
                if ( towrite > z )
                    towrite = z;

                int written = write( fd , buf , towrite );
                uassert( 10443 , errnoWithPrefix("FileAllocator: file write failed" ), written > 0 );
                left -= written;
            }
        }
    }
예제 #6
0
파일: log.cpp 프로젝트: alogg/dolfin
//-----------------------------------------------------------------------------
void dolfin::__debug(std::string file, unsigned long line,
                     std::string function, std::string format, ...)
{
  read(buffer.get(), format);
  std::ostringstream ost;
  ost << file << ":" << line << " in " << function << "()";
  std::string msg = std::string(buffer.get()) + " [at " + ost.str() + "]";
  LogManager::logger.__debug(msg);
}
예제 #7
0
void LightProcess::Initialize(const std::string &prefix, int count,
                              const std::vector<int> &inherited_fds) {
  if (prefix.empty() || count <= 0) {
    return;
  }

  if (Available()) {
    // already initialized
    return;
  }

  g_procs.reset(new LightProcess[count]);
  g_procsCount = count;

  auto afdt_filename = folly::sformat("{}.{}", prefix, getpid());

  // remove the possible leftover
  remove(afdt_filename.c_str());

  afdt_error_t err = AFDT_ERROR_T_INIT;
  auto afdt_lid = afdt_listen(afdt_filename.c_str(), &err);
  if (afdt_lid < 0) {
    Logger::Warning("Unable to afdt_listen to %s: %d %s",
                    afdt_filename.c_str(),
                    errno, folly::errnoStr(errno).c_str());
    return;
  }

  SCOPE_EXIT {
    ::close(afdt_lid);
    remove(afdt_filename.c_str());
  };

  for (int i = 0; i < count; i++) {
    if (!g_procs[i].initShadow(afdt_lid, afdt_filename, i, inherited_fds)) {
      for (int j = 0; j < i; j++) {
        g_procs[j].closeShadow();
      }
      g_procs.reset();
      g_procsCount = 0;
      break;
    }
  }

  if (!s_handlerInited) {
    struct sigaction sa;
    struct sigaction old_sa;
    sa.sa_sigaction = &LightProcess::SigChldHandler;
    sa.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
    if (sigaction(SIGCHLD, &sa, &old_sa) != 0) {
      Logger::Error("Couldn't install SIGCHLD handler");
      abort();
    }
    s_handlerInited = true;
  }
}
예제 #8
0
    void FileAllocator::ensureLength(int fd , long size) {
#if !defined(_WIN32)
        if (useSparseFiles(fd)) {
            LOG(1) << "using ftruncate to create a sparse file" << endl;
            int ret = ftruncate(fd, size);
            uassert(16063, "ftruncate failed: " + errnoWithDescription(), ret == 0);
            return;
        }
#endif

#if defined(__linux__)
        int ret = posix_fallocate(fd,0,size);
        if ( ret == 0 )
            return;

        log() << "FileAllocator: posix_fallocate failed: " << errnoWithDescription( ret ) << " falling back" << endl;
#endif

        off_t filelen = lseek( fd, 0, SEEK_END );
        if ( filelen < size ) {
            if (filelen != 0) {
                stringstream ss;
                ss << "failure creating new datafile; lseek failed for fd " << fd << " with errno: " << errnoWithDescription();
                uassert( 10440 ,  ss.str(), filelen == 0 );
            }
            // Check for end of disk.

            uassert( 10441 ,  str::stream() << "Unable to allocate new file of size " << size << ' ' << errnoWithDescription(),
                     size - 1 == lseek(fd, size - 1, SEEK_SET) );
            uassert( 10442 ,  str::stream() << "Unable to allocate new file of size " << size << ' ' << errnoWithDescription(),
                     1 == write(fd, "", 1) );
            lseek(fd, 0, SEEK_SET);

            const long z = 256 * 1024;
            const boost::scoped_array<char> buf_holder (new char[z]);
            char* buf = buf_holder.get();
            memset(buf, 0, z);
            long left = size;
            while ( left > 0 ) {
                long towrite = left;
                if ( towrite > z )
                    towrite = z;

                int written = write( fd , buf , towrite );
                uassert( 10443 , errnoWithPrefix("FileAllocator: file write failed" ), written > 0 );
                left -= written;
            }
        }
    }
예제 #9
0
HRESULT CKeyTransformBCrypt::_InitBCrypt(BCRYPT_ALG_HANDLE& hAes, BCRYPT_KEY_HANDLE& hKey,
	boost::scoped_array<UCHAR>& pKeyObj, const BYTE* pbKey32)
{
	if(m_lpBCryptOpenAlgorithmProvider(&hAes, BCRYPT_AES_ALGORITHM, NULL, 0) != 0)
	{
		ASSERT(FALSE);
		return E_FAIL;
	}

	DWORD dwKeyObjLen = 0;
	ULONG uResult = 0;
	if(m_lpBCryptGetProperty(hAes, BCRYPT_OBJECT_LENGTH, (PUCHAR)&dwKeyObjLen,
		sizeof(DWORD), &uResult, 0) != 0) KTBC_FAIL;
	if(dwKeyObjLen == 0) KTBC_FAIL;

	pKeyObj.reset(new UCHAR[dwKeyObjLen]);

	if(m_lpBCryptSetProperty(hAes, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_ECB,
		static_cast<ULONG>((wcslen(BCRYPT_CHAIN_MODE_ECB) + 1) * sizeof(wchar_t)), 0) != 0)
		KTBC_FAIL;

	BCRYPT_KEY_DATA_BLOB_32 keyBlob;
	ZeroMemory(&keyBlob, sizeof(BCRYPT_KEY_DATA_BLOB_32));
	keyBlob.dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC;
	keyBlob.dwVersion = BCRYPT_KEY_DATA_BLOB_VERSION1;
	keyBlob.cbKeyData = 32;
	memcpy(keyBlob.pbData, pbKey32, 32);

	// if(m_lpBCryptGenerateSymmetricKey(hAes, &hKey, (PUCHAR)pKeyObj.get(),
	//	dwKeyObjLen, const_cast<PUCHAR>(pbKey32), 32, 0) != 0) KTBC_FAIL;
	if(m_lpBCryptImportKey(hAes, NULL, BCRYPT_KEY_DATA_BLOB, &hKey,
		pKeyObj.get(), dwKeyObjLen, (PUCHAR)&keyBlob,
		sizeof(BCRYPT_KEY_DATA_BLOB_32), 0) != 0) KTBC_FAIL;

#ifdef _DEBUG
	DWORD dwKeyLen = 0;
	VERIFY(m_lpBCryptGetProperty(hKey, BCRYPT_KEY_STRENGTH, (PUCHAR)&dwKeyLen,
		sizeof(DWORD), &uResult, 0) == 0);
	VERIFY(dwKeyLen == 256);

	BCRYPT_ALG_HANDLE hRef = NULL;
	VERIFY(m_lpBCryptGetProperty(hKey, BCRYPT_PROVIDER_HANDLE, (PUCHAR)&hRef,
		sizeof(BCRYPT_ALG_HANDLE), &uResult, 0) == 0);
	VERIFY(hRef == hAes);
#endif

	return S_OK;
}
예제 #10
0
void LightProcess::Close() {
  for (int i = 0; i < g_procsCount; i++) {
    g_procs[i].closeShadow();
  }
  g_procs.reset();
  g_procsCount = 0;
}
예제 #11
0
inline LogCodec::int_type LogCodec::consumeVoidsAndComments(streambuf_type *buf_ptr)
{
	int_type c = buf_ptr->sgetc();
	char * const read_buf = m_read_buf.get();
	char * read_ptr;

	while (!traits_type::eq_int_type(c, traits_type::eof())) {
		if (m_field_split.find(c) != std::string::npos || m_event_split.find(c) != std::string::npos) {
			c = buf_ptr->snextc();
		} else if (m_comment_chars.find(c) != std::string::npos) {
			// ignore comment line (sorta...)
			read_ptr = read_buf;
			do {
				// check for end of line
				if (m_event_split.find(c) != std::string::npos)
					break;
				// read in the comment in case it matters...
				if (read_ptr < m_read_end)
					*(read_ptr++) = c;
				// get the next character
				c = buf_ptr->snextc();
			} while (!traits_type::eq_int_type(c, traits_type::eof()));
			*read_ptr = '\0';
			if (m_handle_elf_headers) {
				// check if it is an ELF format change
				read_buf[FIELDS_ELF_HEADER.size()] = '\0';
				if (FIELDS_ELF_HEADER == read_buf)
					changeELFFormat(read_buf + FIELDS_ELF_HEADER.size() + 1);
			}
		} else {
			break;
		}
	}
	return c;
}
예제 #12
0
inline
systembuf::systembuf(handle_type h, std::size_t bufsize) :
    m_handle(h),
    m_bufsize(bufsize),
    m_read_buf(new char[bufsize]),
    m_write_buf(new char[bufsize])
{
#if defined(BOOST_PROCESS_WIN32_API)
    BOOST_ASSERT(m_handle != INVALID_HANDLE_VALUE);
#else
    BOOST_ASSERT(m_handle >= 0);
#endif
    BOOST_ASSERT(m_bufsize > 0);

    setp(m_write_buf.get(), m_write_buf.get() + m_bufsize);
}
예제 #13
0
	void init_old_buffer(boost::scoped_array<unsigned long long> &array, const std::size_t size) {
		if (!array) {
			array.reset(new unsigned long long[size]);
			for (std::size_t i=0;i<size;i++) {
				array[i] = 0;
			}
		}
	}
예제 #14
0
 inline Matrix::column_iterator Matrix::column_end(Size i) {
     #if defined(QL_EXTRA_SAFETY_CHECKS)
     QL_REQUIRE(i<columns_,
                "column index (" << i << ") must be less than " << columns_ <<
                ": matrix cannot be accessed out of range");
     #endif
     return column_iterator(data_.get()+i+rows_*columns_,columns_);
 }
예제 #15
0
 inline Matrix::row_iterator Matrix::row_end(Size i) {
     #if defined(QL_EXTRA_SAFETY_CHECKS)
     QL_REQUIRE(i<rows_,
                "row index (" << i << ") must be less than " << rows_ <<
                ": matrix cannot be accessed out of range");
     #endif
     return data_.get()+columns_*(i+1);
 }
예제 #16
0
파일: task_id.hpp 프로젝트: edwardt/CloudI
 TaskId(std::string const & workTitle, uint32_t id,
        boost::scoped_array<uint8_t> const & taskData,
        size_t taskDataSize) :
     m_workId(workTitle, id),
     m_taskData(new uint8_t[taskDataSize]),
     m_taskDataSize(taskDataSize)
 {
     memcpy(m_taskData.get(), taskData.get(), taskDataSize);
 }
예제 #17
0
void AudioResampleImpl::splitAudioData(AudioData & data, boost::scoped_array<char*> & split) const
{
	auto dataFormat = data.format();

	if (dataFormat.isPlanar())
	{
		/// Для планарного формата необходимо представить данные из result
		const int numChannels = dataFormat.channelCount();
		split.reset(new char*[numChannels]);
		split_ref(data.begin(), data.end(), data.numBytes() / numChannels, split.get());
	}
	else
	{
		/// Interleaved данные помещаются в один массив
		split.reset(new char*[1]);
		split[0] = data.data();
	}
}
예제 #18
0
void LightProcess::Close() {
  boost::scoped_array<LightProcess> procs;
  procs.swap(g_procs);
  int count = g_procsCount;
  g_procs.reset();
  g_procsCount = 0;

  for (int i = 0; i < count; i++) {
    procs[i].closeShadow();
  }
}
예제 #19
0
inline
systembuf::int_type
systembuf::underflow(void)
{
    BOOST_ASSERT(gptr() >= egptr());

    bool ok;
#if defined(BOOST_PROCESS_WIN32_API)
    DWORD cnt;
    BOOL res = ::ReadFile(m_handle, m_read_buf.get(), (DWORD)m_bufsize, &cnt, NULL);
    ok = (res && cnt > 0);
#else
    ssize_t cnt = ::read(m_handle, m_read_buf.get(), m_bufsize);
    ok = (cnt != -1 && cnt != 0);
#endif

    if (!ok)
        return traits_type::eof();
    else {
        setg(m_read_buf.get(), m_read_buf.get(), m_read_buf.get() + cnt);
        return traits_type::to_int_type(*gptr());
    }
}
예제 #20
0
void LightProcess::Initialize(const std::string &prefix, int count,
                              const std::vector<int> &inherited_fds) {
  if (prefix.empty() || count <= 0) {
    return;
  }

  if (Available()) {
    // already initialized
    return;
  }

  g_procs.reset(new LightProcess[count]);
  g_procsCount = count;

  for (int i = 0; i < count; i++) {
    if (!g_procs[i].initShadow(prefix, i, inherited_fds)) {
      for (int j = 0; j < i; j++) {
        g_procs[j].closeShadow();
      }
      g_procs.reset();
      g_procsCount = 0;
      break;
    }
  }

  if (!s_handlerInited) {
    struct sigaction sa;
    struct sigaction old_sa;
    sa.sa_sigaction = &LightProcess::SigChldHandler;
    sa.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
    if (sigaction(SIGCHLD, &sa, &old_sa) != 0) {
      Logger::Error("Couldn't install SIGCHLD handler");
      abort();
    }
    s_handlerInited = true;
  }
}
예제 #21
0
파일: log.cpp 프로젝트: alogg/dolfin
// Buffer allocation
void allocate_buffer(std::string msg)
{
  // va_list, start, end require a char pointer of fixed size so we
  // need to allocate the buffer here. We allocate twice the size of
  // the format string and at least DOLFIN_LINELENGTH. This should be
  // ok in most cases.
  unsigned int new_size = std::max(static_cast<unsigned int>(2*msg.size()),
                                   static_cast<unsigned int>(DOLFIN_LINELENGTH));
  //static_cast<unsigned int>(DOLFIN_LINELENGTH));
  if (new_size > buffer_size)
  {
    buffer.reset(new char[new_size]);
    buffer_size = new_size;
  }
}
예제 #22
0
void LightProcess::Initialize(const std::string &prefix, int count) {
  if (prefix.empty() || count <= 0) {
    return;
  }

  if (Available()) {
    // already initialized
    return;
  }

  g_procs.reset(new LightProcess[count]);
  g_procsCount = count;

  for (int i = 0; i < count; i++) {
    if (!g_procs[i].initShadow(prefix, i)) {
      for (int j = 0; j < i; j++) {
        g_procs[j].closeShadow();
      }
      g_procs.reset();
      g_procsCount = 0;
      break;
    }
  }
}
예제 #23
0
//---------------------------- PUBLIC           -----------------------------//
wxServerConnectionThread::wxServerConnectionThread(
	wxEvtHandler * const handler, wxCities3DSocket * const socket, 
	const Game &game, const wxString &version, 
	const SpectatorArray &spectators, 
	const boost::scoped_array<wxUint8> &rng, const size_t size)
: mHandler(handler)
, mSocket(socket)
, mGame(game)
, mVersion(version)
, mSpectators(spectators)
, mSize(size)
{
	wxASSERT(NULL != mHandler);
	wxASSERT(NULL != mSocket);
	wxASSERT(0 < mSize);

	mRNG.reset(new wxUint8[mSize]);
	memcpy(mRNG.get(), rng.get(), mSize);
}
예제 #24
0
void AnmGraphicsObjectData::loadAnmFileFromData(
    boost::scoped_array<char>& anm_data) {
  const char* data = anm_data.get();

  // Read the header
  int frames_len = read_i32(data + 0x8c);
  int framelist_len = read_i32(data + 0x90);
  int animation_set_len = read_i32(data + 0x94);
  if (animation_set_len < 0) {
    throw rlvm::Exception(
        "Impossible value for animation_set_len in ANM file.");
  }

  // Read the corresponding image file we read from, and load the image.
  string raw_file_name = data + 0x1c;
  image_ = system_.graphics().getSurfaceNamed(raw_file_name);
  image_->EnsureUploaded();

  // Read the frame list
  const char* buf = data + 0xb8;
  Size screen_size = getScreenSize(system_.gameexe());
  for (int i = 0; i < frames_len; ++i) {
    Frame f;
    f.src_x1 = read_i32(buf);
    f.src_y1 = read_i32(buf+4);
    f.src_x2 = read_i32(buf+8);
    f.src_y2 = read_i32(buf+12);
    f.dest_x = read_i32(buf+16);
    f.dest_y = read_i32(buf+20);
    f.time = read_i32(buf+0x38);
    fixAxis(f, screen_size.width(), screen_size.height());
    frames.push_back(f);

    buf += 0x60;
  }

  readIntegerList(data + 0xb8 + frames_len*0x60, 0x68, framelist_len,
                  framelist);
  readIntegerList(data + 0xb8 + frames_len*0x60 + framelist_len*0x68,
                  0x78, animation_set_len, animation_set);
}
void CassandraStressClient::Setup(std::string const& server_ip) {
  success_count_ = 0;
  latencies_.reset(new double[FLAGS_operation_count/FLAGS_thread_count]);
  try {
    boost::shared_ptr<TTransport> socket =
        boost::shared_ptr<TSocket>(new TSocket(server_ip, 9160));
    transport_ = boost::shared_ptr<TFramedTransport>(
        new TFramedTransport(socket));
    boost::shared_ptr<TProtocol> protocol =
        boost::shared_ptr<TBinaryProtocol>(new TBinaryProtocol(transport_));
    client_.reset(new CassandraClient(protocol));
    transport_->open();
    std::string query = "USE offline_keyspace";
    CqlResult result;
    client_->execute_cql3_query(result, query, Compression::NONE,
                                ConsistencyLevel::ONE);
  } catch (TTransportException& te) {
    printf("Exception: %s [%d]\n", te.what(), te.getType());
  } catch (InvalidRequestException& ire) {
    printf("Exception: %s [%s]\n", ire.what(), ire.why.c_str());
  }
}
예제 #26
0
bool volume_generator_checkerboard::generate_float_volume(unsigned dim_x,
                                                          unsigned dim_y,
                                                          unsigned dim_z,
                                                          unsigned components,
                                                          boost::scoped_array<float>& buffer)

{
    if (dim_x < 1 || dim_y < 1 || dim_z < 1 || components < 1) {
        return (false);
    }

    try {
        buffer.reset(new float[dim_x * dim_y * dim_z * components]);
    }
    catch (std::bad_alloc&) {
        return (false);
    }

    float val;
    unsigned offset_dst;

    for (unsigned z = 0; z < dim_z; z++) {
        for (unsigned y = 0; y < dim_y; y++) {
            for (unsigned x = 0; x < dim_x; x++) {
                val = float(scm::math::sign(-int((x+y+z) % 2)));
                offset_dst =   x * components
                             + y * dim_x * components
                             + z * dim_x * dim_y * components;

                for (unsigned c = 0; c < components; c++) {
                    buffer[offset_dst + c] = val;
                }
            }
        }
    }

    return (true);
}
예제 #27
0
 void lock()
 {
     boost::lock(locks.get(),locks.get()+count);
 }
예제 #28
0
 inline Matrix::const_iterator Matrix::end() const {
     return data_.get()+rows_*columns_;
 }
예제 #29
0
 /** Initilize the GSL spline with the given points
  *
  * @param x :: The x points defining the spline
  * @param y :: The y points defining the spline
  * @param n :: The size of the arrays
  */
 void CubicSpline::initGSLObjects(boost::scoped_array<double>& x, boost::scoped_array<double>& y, int n) const
 {
   int status = gsl_spline_init(m_spline.get(), x.get(), y.get(), n);
   checkGSLError(status, GSL_EINVAL);
 }
예제 #30
0
 inline Matrix::iterator Matrix::end() {
     return data_.get()+rows_*columns_;
 }