text:
#include <dlib/opencv.h>
#include <opencv2/highgui/highgui.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>

#include <iostream>
#include <omp.h>

using namespace dlib;
using namespace std;

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "../../../third_party/stb/stb_image.h"
#include "../../../third_party/stb/stb_image_write.h"

#include "../../core/include/simple_dlib_face_detection.hpp"

primitive_image_t primitive_image_clone(primitive_image_t& p)
{
	primitive_image_t q = p;
	q.pixcels = new unsigned char[p.x*p.y*p.channels];

	const int sz = p.x*p.y*p.channels;
#pragma omp parallel for
	for (int i = 0; i < sz; i++) q.pixcels[i] = p.pixcels[i];

	return q;
}

void delete_primitive_image(primitive_image_t& p)
{
	if (p.pixcels) delete[] p.pixcels;
}

void delete_dlibImg(void* dlibImg)
{
	matrix<bgr_pixel>* dlibimage = (matrix<bgr_pixel>*)dlibImg;
	delete dlibimage;
}

int ToBMP(const char* filename, char* newfile)
{
	unsigned char *image_data = 0;
	int x, y;
	int nbit;
	image_data = stbi_load(filename, &x, &y, &nbit, 0);
	if (image_data == NULL)
	{
		printf("image file[%s] read error.\n", filename);
		return -1;
	}
	stbi_write_bmp(newfile, x, y, nbit, (void*)image_data);
	return 0;
}

void* get_frontal_face_detector_ptr()
{
	frontal_face_detector* detector = new frontal_face_detector(get_frontal_face_detector());

	return (void*)detector;
}

void load_primitive_image(char* filename, primitive_image_t& p)
{
	p.pixcels = stbi_load(filename, &p.x, &p.y, &p.channels, 0);
	if (p.pixcels == NULL)
	{
		printf("image file[%s] read error.\n", filename);
		return;
	}
}

void save_primitive_image(char* filename, primitive_image_t p)
{
	stbi_write_bmp(filename, p.x, p.y, p.channels, (void*)p.pixcels);
}

primitive_image_t dlibImage2primitive_image(void* img_p, const int channels)
{
	matrix<bgr_pixel> img = *((matrix<bgr_pixel>*)img_p);

	primitive_image_t out_image;
	out_image.x = img.nc();
	out_image.y = img.nr();
	out_image.channels = channels;
	out_image.pixcels = new unsigned char[img.nr()*img.nc()*channels];

	const int sz = img.nr()*img.nc();
#pragma omp parallel for
	for (int i = 0; i < sz; i++)
	{
		if (channels == 1)
		{
			out_image.pixcels[channels*i + 0] = img(i).red;
		}
		else
		{
			out_image.pixcels[channels*i + 0] = img(i).red;
			out_image.pixcels[channels*i + 1] = img(i).green;
			out_image.pixcels[channels*i + 2] = img(i).blue;
		}
	}
	return out_image;
}

void* primitive_image2dlibImage(primitive_image_t& image)
{
	matrix<bgr_pixel>* img_p = new matrix<bgr_pixel>(image.y, image.x);

	const int channels = image.channels;

	const int sz = image.x*image.y;
	if (channels == 1)
	{
#pragma omp parallel for
		for (int i = 0; i < sz; i++)
		{
			bgr_pixel bgr(image.pixcels[channels*i + 0], image.pixcels[channels*i + 0], image.pixcels[channels*i + 0]);
			(*img_p)(i) = bgr;
		}
		return (void*)img_p;
	}

#pragma omp parallel for
	for (int i = 0; i < sz; i++)
	{
		bgr_pixel bgr(image.pixcels[channels*i + 2], image.pixcels[channels*i + 1], image.pixcels[channels*i + 0]);
		(*img_p)(i) = bgr;
	}
	return (void*)img_p;
}

void primitive_image2dlibImage_(primitive_image_t& image, matrix<bgr_pixel>& img_p)
{

	const int channels = image.channels;

	const int sz = image.x*image.y;
	if (channels == 1)
	{
#pragma omp parallel for
		for (int i = 0; i < sz; i++)
		{
			bgr_pixel bgr(image.pixcels[channels*i + 0], image.pixcels[channels*i + 0], image.pixcels[channels*i + 0]);
			img_p(i) = bgr;
		}
		return;
	}
#pragma omp parallel for
	for (int i = 0; i < sz; i++)
	{
		img_p(i) = bgr_pixel(image.pixcels[channels*i + 2], image.pixcels[channels*i + 1], image.pixcels[channels*i + 0]);
	}

}

int face_detector(void* win_p, primitive_image_t& image, void* detector_ptr, std::vector<rectangle_2d_t>& rectangleList)
{
	frontal_face_detector& detector = *((frontal_face_detector*)detector_ptr);

	matrix<bgr_pixel> img_p(image.y, image.x);
	primitive_image2dlibImage_(image, img_p);

	//save_bmp(img_p, "zzzz.bmp"); exit(0);
	//primitive_image_t q = dlibImage2primitive_image((void*)&img_p, 3);
	//save_primitive_image("zzzz.bmp", *q);

	// Make the image bigger by a factor of two.  This is useful since
	// the face detector looks for faces that are about 80 by 80 pixels
	// or larger.  Therefore, if you want to find faces that are smaller
	// than that then you need to upsample the image as we do here by
	// calling pyramid_up().  So this will allow it to detect faces that
	// are at least 40 by 40 pixels in size.  We could call pyramid_up()
	// again to find even smaller faces, but note that every time we
	// upsample the image we make the detector run slower since it must
	// process a larger image.
	pyramid_up(img_p);

	// Now tell the face detector to give us a list of bounding boxes
	// around all the faces it can find in the image.
	std::vector<rectangle> dets = detector(img_p);

	if (dets.size() == 0)
	{
		if (win_p)
		{
			image_window* win = ((image_window*)win_p);
			win->clear_overlay();
			win->set_image(img_p);
		}
		return 0;
	}

	const float scale[2] = { (float)image.x / (float)img_p.nc(), (float)image.y / (float)img_p.nr() };

	rectangleList.resize(dets.size());
	const int dets_sz = dets.size();
#pragma omp parallel for
	for (int i = 0; i < dets_sz; i++)
	{
		rectangle_2d_t rec;

		rec.left   = dets[i].left()*scale[0];
		rec.right  = dets[i].right()*scale[0];
		rec.top    = dets[i].top()*scale[1];
		rec.bottom = dets[i].bottom()*scale[1];

		rectangleList[i] = rec;
	}
	if (win_p)
	{
		if (win_p)
		{
			image_window* win = ((image_window*)win_p);
			win->clear_overlay();
			win->set_image(img_p);
			win->add_overlay(dets, rgb_pixel(255, 0, 0));
		}
	}

	return rectangleList.size();
}

void* new_shape_predictor(char* shape_predictor_data)
{
	dlib::shape_predictor* model = new shape_predictor;
	deserialize(shape_predictor_data) >> *model;
	return (void*)model;
}
void delete_shape_predictor(void* model)
{
	dlib::shape_predictor* model_ = (shape_predictor*)model;
	delete model_;
}

void delete_full_object_detection_shape(void* shape)
{
	delete (std::vector<full_object_detection>*)shape;
}

int face_detector_cv( void* win_p, void* cvMat_image, void* detector_ptr, std::vector<rectangle_2d_t>& rectangleList, void* shape_predictor_model)
{
	cv::Mat& image = *(cv::Mat*)cvMat_image;
	frontal_face_detector& detector = *((frontal_face_detector*)detector_ptr);

	cv_image<bgr_pixel> cimg(image);

	// Make the image bigger by a factor of two.  This is useful since
	// the face detector looks for faces that are about 80 by 80 pixels
	// or larger.  Therefore, if you want to find faces that are smaller
	// than that then you need to upsample the image as we do here by
	// calling pyramid_up().  So this will allow it to detect faces that
	// are at least 40 by 40 pixels in size.  We could call pyramid_up()
	// again to find even smaller faces, but note that every time we
	// upsample the image we make the detector run slower since it must
	// process a larger image.
	//pyramid_up<cv_image<bgr_pixel>>(cimg);

	// Now tell the face detector to give us a list of bounding boxes
	// around all the faces it can find in the image.
	std::vector<rectangle> dets = detector(cimg);

	if (dets.size() == 0)
	{
		if (win_p)
		{
			image_window* win = ((image_window*)win_p);
			// Display it all on the screen
			win->clear_overlay();
			win->set_image(cimg);
		}
		return 0;
	}

	const float scale[2] = { (float)image.cols / (float)cimg.nc(), (float)image.rows / (float)cimg.nr() };

	rectangleList.resize(dets.size());
	const int dets_sz = dets.size();
#pragma omp parallel for
	for (int i = 0; i < dets_sz; i++)
	{
		rectangle_2d_t rec;

		rec.left = dets[i].left()*scale[0];
		rec.right = dets[i].right()*scale[0];
		rec.top = dets[i].top()*scale[1];
		rec.bottom = dets[i].bottom()*scale[1];

		rectangleList[i] = rec;
	}

	std::vector<full_object_detection> shapes;
	if (shape_predictor_model)
	{
		shape_predictor pose_model = *(shape_predictor*)shape_predictor_model;
		// Find the pose of each face.
		for (unsigned long i = 0; i < dets.size(); ++i)
			shapes.push_back(pose_model(cimg, dets[i]));
	}

	if (win_p)
	{
		image_window* win = ((image_window*)win_p);
		// Display it all on the screen
		win->clear_overlay();
		win->set_image(cimg);
		if (shape_predictor_model)
		{
			win->add_overlay(render_face_detections(shapes));
		}
		win->add_overlay(dets, rgb_pixel(255, 0, 0));

	}
	return rectangleList.size();
}

void* create_image_window()
{
	//image_window win;
	return (void*)(new image_window);
}
void close_image_window(void* win_p)
{
	((image_window*)win_p)->close_window();
}

void set_image_window(void*win_p, void* dlib_img)
{
	((image_window*)win_p)->set_size(640, 480);
	((image_window*)win_p)->set_image(*((matrix<bgr_pixel>*)dlib_img));
}

void resize_image_window(void*win_p, int w, int h)
{
	((image_window*)win_p)->set_size(w, h);
}


text:
//
// Created by Ivan Kishchenko on 29.08.2021.
//

#ifdef RASPBERRY_ARCH

#include "ZeroMQSocket.h"
#include "ZeroMQLogger.h"
#include "zeromq/ZeroMQWriter.h"
#include "zeromq/ZeroMQReader.h"
#include <boost/lexical_cast.hpp>

using namespace boost;
using namespace boost::asio;

ZeroMQSocket::ZeroMQSocket(boost::asio::io_service &service, std::string_view address, int port)
        : _socket(service), _timer(service) {
    ip::tcp::resolver::query resolver_query(address.data(), lexical_cast<std::string>(port));
    boost::asio::ip::tcp::resolver resolver(service);
    auto iterator = resolver.resolve(resolver_query);
    _endpoint = *iterator;
    startConnect();
}

void ZeroMQSocket::startConnect() {
    _inc.consume(_inc.size());
    _timer.cancel();
    _status = ZeroMQStatus::ZMQ_Idle;
    _socket.close();
    _socket.async_connect(_endpoint, [this](const boost::system::error_code &err) {
        if (err) {
            zero_mq::log::warning("connect failed: {}", err.message());
            _timer.schedule(boost::posix_time::seconds{5}, [this]() {
                startConnect();
            });
        } else {
            zero_mq::log::info("connected");

            std::unique_ptr<ZeroMQBuf<>> buf(new ZeroMQBufFix<64>());
            std::ostream out(buf.get());
            ZeroMQGreeting greeting(false);
            out << greeting;
            startSend(buf);
            _status = ZeroMQStatus::ZMQ_C_Wait_Header;

            startRecv();
        }
    });
}

void ZeroMQSocket::onCommand(const ZeroMQCommand &cmd) {
    zero_mq::log::info("handle cmd: {}", cmd.getName());
    if (cmd.getName() == ZERO_MQ_CMD_READY) {
        ZeroMQEncoder enc;

        std::unique_ptr<ZeroMQBuf<>> out(new ZeroMQBufFix<64>());

        ZeroMQCommand reply(ZERO_MQ_CMD_READY);
        reply.props.emplace(ZERO_MQ_PROP_IDENTIFY, "joystick");
        reply.props.emplace(ZERO_MQ_PROP_SOCKET_TYPE, "PUB");
        enc.write(*out, reply);
        startSend(out);
        _timer.schedule(boost::posix_time::seconds{5}, [this]() {
            onIdle();
        });
        publish("joystick", "ready");
    } else if (cmd.getName() == ZERO_MQ_CMD_SUBSCRIBE) {
        zero_mq::log::info("subscribe: {}", cmd.props.at(ZERO_MQ_PROP_SUBSCRIPTION));
        _topics.emplace(cmd.props.at(ZERO_MQ_PROP_SUBSCRIPTION));
    } else if (cmd.getName() == ZERO_MQ_CMD_CANCEL) {
        zero_mq::log::info("cancel: {}", cmd.props.at(ZERO_MQ_PROP_SUBSCRIPTION));
        _topics.erase(cmd.props.at(ZERO_MQ_PROP_SUBSCRIPTION));
    }
}

void ZeroMQSocket::onMessage(const ZeroMQMessage &msg) {
    for (auto item: msg.data) {
        zero_mq::log::info("msg: {}", item);
    }
}

void ZeroMQSocket::handleData(ZeroMQCharBuf &incBuf) {
    while (incBuf.size()) {
        zero_mq::log::info("inc size: {}:{}", incBuf.size(), incBuf.in_avail());
        switch (_status) {
            case ZeroMQStatus::ZMQ_C_Wait_Header: {
                if (incBuf.size() < 10) {
                    return;
                }
                const uint8_t hdr[] = {0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f};
                if (std::memcmp(_inc.data(), hdr, 9) != 0) {
                    startConnect();
                    return;
                }
                _status = ZeroMQStatus::ZMQ_C_Wait_Greeting;
            }
            case ZeroMQStatus::ZMQ_C_Wait_Greeting: {
                if (incBuf.size() < 64) {
                    return;
                }
                ZeroMQReader inc(incBuf);
                std::array<uint8_t, 64> greeting{};
                inc.readBinary<uint8_t, 64>(greeting);
                incBuf.consume(64);

                _status = ZeroMQStatus::ZMQ_Stream;
            }
                break;
            case ZeroMQStatus::ZMQ_Stream: {
                ZeroMQDecoder dec;
                dec.onCommand([this](const ZeroMQCommand &cmd) {
                    onCommand(cmd);
                });
                dec.onMessage([this](const ZeroMQMessage &msg) {
                    onMessage(msg);
                });
                while (dec.read(incBuf)) {}
            }
                return;
            default:
                startConnect();
                break;
        }
    }
}

void ZeroMQSocket::startRecv() {
    _socket.async_receive(
            boost::asio::buffer(_incBuf.data(), _incBuf.size()),
            [this](const boost::system::error_code &err, std::size_t size) {
                if (!err) {
                    zero_mq::log::info("socker recv: {}\n{}", size, ZeroMQUtils::netDump((const uint8_t *) _incBuf.data(), size));

                    _inc.sputn(_incBuf.data(), size);

                    handleData(_inc);
                    startRecv();
                } else {
                    zero_mq::log::info("recv failed: {}", err.message());
                    startConnect();
                }
            }
    );
}

void ZeroMQSocket::startSend(std::unique_ptr<ZeroMQCharBuf> &buf) {
    zero_mq::log::info("socket send:\n{}", ZeroMQUtils::netDump((const uint8_t *) buf->data(), buf->size()));
    async_write(_socket, boost::asio::buffer(buf->data(), buf->size()), [this, buf = std::move(buf)](const boost::system::error_code &err, std::size_t size) {
        if (err) {
            zero_mq::log::info("send failed: {}", err.message());
            startConnect();
        } else {
            zero_mq::log::info("sent: {}:{}", size, buf->size());
        }
    });
}

void ZeroMQSocket::onIdle() {
    publish("joystick", "Control Message");
    publish("joystick1", "skip");
    publish("joystick", "Axis");
    _timer.schedule(boost::posix_time::seconds{5}, [this]() {
        onIdle();
    });
}

void ZeroMQSocket::publish(std::string_view topic, std::string_view data) {
    if (_topics.find(topic.data()) != _topics.end()) {
        ZeroMQEncoder enc;
        std::unique_ptr<ZeroMQBuf<>> buf(new ZeroMQBufFix<256>());

        ZeroMQMessage msg;
        msg << topic.data() << data.data();

        if (!enc.write(*buf, msg)) {
            startSend(buf);
        }
    }
}

#endif

ext: cpp


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_ParticleCollidingInCellEventHandler.hpp
//! \author Alex Robinson
//! \brief  Particle colliding in cell event handler declaration
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PARTICLE_COLLIDING_IN_CELL_EVENT_HANDLER_HPP
#define MONTE_CARLO_PARTICLE_COLLIDING_IN_CELL_EVENT_HANDLER_HPP

// Std Lib Includes
#include <memory>

// Boost Includes
#include <boost/mpl/contains.hpp>

// FRENSIE Includes
#include "MonteCarlo_ParticleCollidingInCellEventDispatcher.hpp"
#include "Utility_DesignByContract.hpp"
#include "Utility_Vector.hpp"

namespace MonteCarlo{

/*! The particle colliding in cell event handler class
 * \ingroup particle_colliding_in_cell_event
 */
class ParticleCollidingInCellEventHandler
{

public:

  //! Constructor
  ParticleCollidingInCellEventHandler();

  //! Destructor
  virtual ~ParticleCollidingInCellEventHandler()
  { /* ... */ }

  //! Return the particle colliding in cell event dispatcher
  ParticleCollidingInCellEventDispatcher&
  getParticleCollidingInCellEventDispatcher();

  //! Return the particle colliding in cell event dispatcher
  const ParticleCollidingInCellEventDispatcher&
  getParticleCollidingInCellEventDispatcher() const;

  //! Update the observers from a particle colliding in cell event
  void updateObserversFromParticleCollidingInCellEvent(
                                    const ParticleState& particle,
                                    const double inverse_total_cross_section );

protected:

  /*! \brief Register an observer with the appropriate particle colliding in
   * cell event dispatcher.
   */
  template<typename Observer>
  void registerObserverWithTag(
                              const std::shared_ptr<Observer>& observer,
                              const std::set<uint64_t>& entity_ids,
                              const std::set<ParticleType>& particle_types,
                              ParticleCollidingInCellEventObserver::EventTag );

  /*! \brief Register an observer with the appropriate particle colliding in
   * cell event dispatcher.
   */
  template<typename Observer>
  void registerObserverWithTag(
                              const std::shared_ptr<Observer>& observer,
                              const std::set<uint64_t>& entity_ids,
                              ParticleCollidingInCellEventObserver::EventTag );

private:

  // Serialize the observer
  template<typename Archive>
  void serialize( Archive& ar, const unsigned version );

  // Declare the boost serialization access object as a friend
  friend class boost::serialization::access;

  // The particle colliding in cell event dispatcher
  ParticleCollidingInCellEventDispatcher
  d_particle_colliding_in_cell_event_dispatcher;
};

// Register an observer with the appropriate particle colliding in
// cell event dispatcher.
template<typename Observer>
inline void ParticleCollidingInCellEventHandler::registerObserverWithTag(
                               const std::shared_ptr<Observer>& observer,
                               const std::set<uint64_t>& entity_ids,
                               const std::set<ParticleType>& particle_types,
                               ParticleCollidingInCellEventObserver::EventTag )
{
  // Make sure the Observer class has the correct event tag
  testStaticPrecondition((boost::mpl::contains<typename Observer::EventTags,ParticleCollidingInCellEventObserver::EventTag>::value));

  std::shared_ptr<ParticleCollidingInCellEventObserver> observer_base =
    std::dynamic_pointer_cast<ParticleCollidingInCellEventObserver>( observer );

  for( auto&& entity_id : entity_ids )
  {
    d_particle_colliding_in_cell_event_dispatcher.attachObserver(
                                                               entity_id,
                                                               particle_types,
                                                               observer_base );
  }
}

// Register an observer with the appropriate particle colliding in
// cell event dispatcher.
template<typename Observer>
inline void ParticleCollidingInCellEventHandler::registerObserverWithTag(
                               const std::shared_ptr<Observer>& observer,
                               const std::set<uint64_t>& entity_ids,
                               ParticleCollidingInCellEventObserver::EventTag )
{
  // Make sure the Observer class has the correct event tag
  testStaticPrecondition((boost::mpl::contains<typename Observer::EventTags,ParticleCollidingInCellEventObserver::EventTag>::value));

  std::shared_ptr<ParticleCollidingInCellEventObserver> observer_base =
    std::dynamic_pointer_cast<ParticleCollidingInCellEventObserver>( observer );

  for( auto&& entity_id : entity_ids )
  {
    d_particle_colliding_in_cell_event_dispatcher.attachObserver(
                                                               entity_id,
                                                               observer_base );
  }
}

// Serialize the observer
template<typename Archive>
void ParticleCollidingInCellEventHandler::serialize( Archive& ar, const unsigned version )
{
  ar & BOOST_SERIALIZATION_NVP( d_particle_colliding_in_cell_event_dispatcher );
}

} // end MonteCarlo namespace

BOOST_CLASS_VERSION( MonteCarlo::ParticleCollidingInCellEventHandler, 0 );
EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, ParticleCollidingInCellEventHandler );

#endif // end MONTE_CARLO_PARTICLE_COLLIDING_IN_CELL_EVENT_HANDLER_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_ParticleCollidingInCellEventHandler.hpp
//---------------------------------------------------------------------------//

ext: hpp


text:
#include "custom-instructions.h"
#include "runtime-dump.h"
#include "tci_analyzer.h"
#include "crete-debug.h"

#include <boost/serialization/split_member.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/unordered_set.hpp>
#include <boost/filesystem/operations.hpp>

#include <crete/custom_opcode.h>
#include <crete/debug_flags.h>

extern "C" {
#include "cpu.h"

extern CPUArchState *g_cpuState_bct;
void qemu_system_shutdown_request(void);
}

#include "tcg.h"

using namespace std;

// shared from runtime-dump.cpp
extern uint64_t g_crete_target_pid;
extern bool g_crete_is_valid_target_pid;

// TODO: xxx We may need this to capture the initial test case, when
//        there are more concolic variables than the ones listed
//        in crete.xml from guest
// static bool crete_flag_write_initial_input = false;
static const string crete_trace_ready_file_name = "trace_ready";

static boost::unordered_set<uint64_t> g_pc_exclude_filters;
static boost::unordered_set<uint64_t> g_pc_include_filters;

static uint64_t target_process_count = 0;
static set<string> concolics_names;

// CRETE_INSTR_SEND_TARGET_PID_VALUE
static inline void crete_custom_instr_sent_target_pid()
{
	g_crete_flags->set((uint64_t)g_cpuState_bct->cr[3]);

	g_crete_target_pid = g_cpuState_bct->cr[3];
	g_crete_is_valid_target_pid = true;
	++target_process_count;
}

// CRETE_INSTR_VOID_TARGET_PID_VALUE
static inline void crete_custom_instr_void_target_pid()
{
	g_crete_flags->reset();

    g_crete_is_valid_target_pid = false;
    runtime_env->handleCreteVoidTargetPid();
}

static inline void crete_custom_instr_check_target_pid()
{
    // Only process if it is from valid target pid while not processing interrupt
    if(g_crete_is_valid_target_pid &&
            ((uint64_t)g_cpuState_bct->cr[3] == g_crete_target_pid) &&
            !runtime_env->check_interrupt_process_info(0))
    {
        target_ulong addr = g_cpuState_bct->regs[R_EAX];
        uint8_t ret = 1;

        if(RuntimeEnv::access_guest_memory(g_cpuState_bct, addr, &ret, 1, 1) != 0) {
            cerr << "[CRETE ERROR] access_guest_memory() failed in crete_custom_instr_check_target_pid()\n";
            assert(0);
        }
    }
}

static string get_unique_name(const char *name)
{
    stringstream unique_name;
    unique_name << name << "_p" << target_process_count;
    string base_name = unique_name.str();

    unsigned count = 0;
    while(!concolics_names.insert(unique_name.str()).second) {
        unique_name.str(string());
        unique_name << base_name << "_" << ++count;
    }

    return unique_name.str();
}
#define MAX_CONCOLIC_NAME_SIZE 256
static char current_concolic_name[2*MAX_CONCOLIC_NAME_SIZE];

// CRETE_INSTR_SEND_CONCOLIC_NAME_VALUE
static inline void crete_custom_instr_send_concolic_name()
{
    assert(current_concolic_name[0] == '\0' &&
            "[CRETE ERROR] current_concolic_name should be reset to empty\n");

    target_ulong name_guest_addr = g_cpuState_bct->regs[R_EAX];
    target_ulong name_size = g_cpuState_bct->regs[R_ECX];

    assert(name_size > 0 && name_size < MAX_CONCOLIC_NAME_SIZE
            && "[CRETE ERROR] name size for concolic variable is bigger than MAX_CONCOLIC_NAME_SIZE\n");

    if(RuntimeEnv::access_guest_memory(g_cpuState_bct, name_guest_addr,
            (uint8_t *)current_concolic_name, name_size, 0) != 0) {

        cerr << "[CRETE ERROR] access_guest_memory() failed in crete_custom_instr_send_concolic_name()\n";
        assert(0);
    }

    current_concolic_name[name_size] = '\0';

    string unique_name = get_unique_name(current_concolic_name);
    if(strcmp(unique_name.c_str(), current_concolic_name))
    {
        uint64_t unique_name_size = unique_name.size();
        assert(unique_name_size > name_size);
        assert(unique_name_size < (2*MAX_CONCOLIC_NAME_SIZE-1));
        strncpy(current_concolic_name, unique_name.c_str(), unique_name_size);
        current_concolic_name[unique_name_size] = '\0';

        if(RuntimeEnv::access_guest_memory(g_cpuState_bct, name_guest_addr,
                (uint8_t *)current_concolic_name, unique_name_size+1, 1) != 0) {

            cerr << "[CRETE ERROR] access_guest_memory() failed in crete_custom_instr_send_concolic_name()\n";
            assert(0);
        }
    }
}

// CRETE_INSTR_PRE_MAKE_CONCOLIC_VALUE
static inline void crete_custom_instr_pre_make_concolic()
{
    assert(current_concolic_name[0] != '\0' &&
            "[CRETE ERROR] current_concolic_name is empty. "
            "It should have been set by crete_custom_instr_send_concolic_name\n");

    string concolic_name(current_concolic_name);
    memset(current_concolic_name, 0, 512);

    target_ulong guest_addr = g_cpuState_bct->regs[R_EAX];
    target_ulong size = g_cpuState_bct->regs[R_ECX];

    runtime_env->handlecreteMakeConcolic(concolic_name, guest_addr, size);
}

// CRETE_INSTR_KERNEL_OOPS_VALUE
// TODO: xxx make it better with keeping traces so far
// Report with prints and quit VM, from where vm-node should log the
// VM quit with related information and test case
static inline void crete_custom_instr_kernel_oops()
{
    fprintf(stderr, "[Potential Bugs] crete_kernel_oops()\n");
    qemu_system_shutdown_request();
}

// CRETE_INSTR_PRIME_VALUE:
// Reset flags and structs being used for testing an executable
static inline void crete_custom_instr_prime()
{
    g_pc_include_filters.clear();
    g_pc_exclude_filters.clear();

#if defined(CRETE_DBG_MEM)
    fprintf(stderr, "[CRETE_DBG_MEM] memory usage(crete_custom_instr_prime()) = %.3fMB\n",
            crete_mem_usage());
#endif
}

namespace fs = boost::filesystem;

// CRETE_INSTR_DUMP_VALUE
static inline void crete_tracing_finish()
{
	assert(rt_dump_tb_count != 0 && "[CRETE ERROR] Nothing is captured.\n");
    assert(runtime_env);

	// Waiting for vm_node
    while(fs::exists(crete_trace_ready_file_name))
        ; // Wait for it to not exist. FIXME: not efficient and can hang qume.

    // Writing trace to file
    runtime_env->writeRtEnvToFile();
    runtime_env->printInfo();

    fs::ofstream ofs(fs::path("hostfile") / crete_trace_ready_file_name);

    if(!ofs.good())
    {
        assert(0 && "can't write to crete_trace_ready_file_name");
    }
}

// CRETE_INSTR_DUMP_VALUE
// Reset flags and structs being used for tracing one concrete run of an executable
static inline void crete_tracing_reset()
{
    // Release
    crete_runtime_dump_close(); // Cleanup must happen before tb_flush (or crash occurs).
    tb_flush(g_cpuState_bct); // Flush tb cache, so references to runtime_env/tcg_llvm_ctx are destroyed.
    assert(!runtime_env && !g_crete_flags);

    // reset flags
    g_crete_is_valid_target_pid = false;
    g_crete_target_pid = 0;
    target_process_count = 0;
    concolics_names.clear();

    // Reacquire
    crete_runtime_dump_initialize();
    assert(runtime_env && g_crete_flags);
    crete_tci_next_iteration();
}

// CRETE_INSTR_EXCLUDE_FILTER_VALUE
static inline void crete_custom_instr_exclude_filter()
{
	// Note: using ecx/eax is safe for 64bit, as regs[] is defined as target_ulong, and there's no R_RCX/R_RAX
    target_ulong addr_begin = g_cpuState_bct->regs[R_EAX];
    target_ulong addr_end = g_cpuState_bct->regs[R_ECX];

    for(uint64_t i = addr_begin; i < addr_end; ++i) {
        g_pc_exclude_filters.insert(i);
    }
}

// CRETE_INSTR_INCLUDE_FILTER_VALUE
static inline void crete_custom_instr_inlude_filter()
{
	// Note: using ecx/eax is safe for 64bit, as regs[] is defined as target_ulong, and there's no R_RCX/R_RAX
    target_ulong addr_begin = g_cpuState_bct->regs[R_EAX];
    target_ulong addr_end = g_cpuState_bct->regs[R_ECX];

    for(uint64_t i = addr_begin; i < addr_end; ++i) {
        g_pc_include_filters.insert(i);
    }
}

// CRETE_INSTR_READ_PORT_VALUE
//NOTE: xxx check whether port is valid on client side
static void crete_custom_instr_read_port()
{
	target_ulong guest_addr = g_cpuState_bct->regs[R_EAX];
	target_ulong size = g_cpuState_bct->regs[R_ECX];

	unsigned short port = 0;

	const char* file_path = "hostfile/port";

	if(fs::exists(file_path))
	{
	    fs::ifstream ifs(file_path,
	            std::ios_base::in | std::ios_base::binary);

	    assert(ifs.good());

	    ifs >> port;
	}

	assert(size == sizeof(port));

	if(RuntimeEnv::access_guest_memory(g_cpuState_bct, guest_addr,
	        (uint8_t *)(&port), size, 1) != 0) {

	    cerr << "[CRETE ERROR] access_guest_memory() failed\n";
	    assert(0);
	}
}

void crete_custom_instruction_handler(uint64_t arg) {
	switch (arg) {
	case CRETE_INSTR_READ_PORT_VALUE:
	    crete_custom_instr_read_port();
	    break;

	case CRETE_INSTR_PRIME_VALUE:
	    crete_custom_instr_prime();
	    crete_tracing_reset();
	    break;

	case CRETE_INSTR_SEND_TARGET_PID_VALUE:
	    crete_custom_instr_sent_target_pid();
	    break;

	case CRETE_INSTR_VOID_TARGET_PID_VALUE:
	    crete_custom_instr_void_target_pid();
	    break;

	case CRETE_INSTR_CHECK_TARGET_PID_VALUE:
	    crete_custom_instr_check_target_pid();
	    break;

	case CRETE_INSTR_SEND_CONCOLIC_NAME_VALUE:
	    crete_custom_instr_send_concolic_name();
	    break;

	case CRETE_INSTR_PRE_MAKE_CONCOLIC_VALUE:
	    crete_custom_instr_pre_make_concolic();
	    break;

	case CRETE_INSTR_KERNEL_OOPS_VALUE:
	    crete_custom_instr_kernel_oops();
	    break;

	case CRETE_INSTR_DUMP_VALUE:
	    crete_tracing_finish();
	    crete_tracing_reset();
	    break;

	case CRETE_INSTR_EXCLUDE_FILTER_VALUE: // Exclude filter
	    crete_custom_instr_exclude_filter();
	    break;

	case CRETE_INSTR_INCLUDE_FILTER_VALUE: // Include filter
	    crete_custom_instr_inlude_filter();
	    break;

	case CRETE_INSTR_QUIT_VALUE:
	    qemu_system_shutdown_request();
	    break;
// Add new custom instruction handler here

	default:
	    assert(0 && "illegal operation: unsupported op code\n");
	}
}

int crete_is_pc_in_exclude_filter_range(uint64_t pc)
{
    boost::unordered_set<uint64_t>::const_iterator it = g_pc_exclude_filters.find(pc);
    if(it != g_pc_exclude_filters.end()){
        return 1;
    } else {
        return 0;
    }
}

int crete_is_pc_in_include_filter_range(uint64_t pc)
{
    boost::unordered_set<uint64_t>::const_iterator it = g_pc_include_filters.find(pc);
    if(it != g_pc_include_filters.end()){
        return 1;
    } else {
        return 0;
    }
}

struct PIDWriter
{
    PIDWriter()
    {
        fs::path dir = "hostfile";

        if(!fs::exists(dir))
        {
        fs::create_directories(dir);
        }

        fs::path p = dir / "pid";

        if(fs::exists(p))
        {
            fs::remove(p);
        }

        fs::ofstream ofs(p,
                 ios_base::binary | ios_base::out);

        if(!ofs.good())
        {
            assert(0 && "Could not open hostfile/pid for writing");
        }

        ofs << ::getpid();
    }
} pid_writer; // Ctor writes PID when program starts.


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include "Evolution/DiscontinuousGalerkin/Limiters/Minmod.hpp"

#include <array>
#include <boost/functional/hash.hpp>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <memory>
#include <pup.h>
#include <type_traits>
#include <unordered_map>
#include <utility>

#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tags.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Domain/Structure/Direction.hpp"
#include "Domain/Structure/DirectionMap.hpp"
#include "Domain/Structure/Element.hpp"
#include "Domain/Structure/ElementId.hpp"
#include "Domain/Structure/OrientationMap.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Evolution/DiscontinuousGalerkin/Limiters/MinmodHelpers.hpp"
#include "Evolution/DiscontinuousGalerkin/Limiters/MinmodType.hpp"
#include "NumericalAlgorithms/LinearOperators/MeanValue.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Literals.hpp"
#include "Utilities/Numeric.hpp"
#include "Utilities/TMPL.hpp"

namespace Limiters {
namespace Minmod_detail {

// Implements the minmod limiter for one Tensor<DataVector> at a time.
template <size_t VolumeDim, typename Tag, typename PackagedData>
bool limit_one_tensor(
    const gsl::not_null<DataVector*> u_lin_buffer,
    const gsl::not_null<BufferWrapper<VolumeDim>*> buffer,
    const gsl::not_null<typename Tag::type*> tensor,
    const Limiters::MinmodType minmod_type, const double tvb_constant,
    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,
    const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,
    const std::array<double, VolumeDim>& element_size,
    const std::unordered_map<
        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,
        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&
        neighbor_data) noexcept {
  // True if the mesh is linear-order in every direction
  const bool mesh_is_linear = (mesh.extents() == Index<VolumeDim>(2));
  const bool minmod_type_is_linear =
      (minmod_type != Limiters::MinmodType::LambdaPiN);
  const bool using_linear_limiter_on_non_linear_mesh =
      minmod_type_is_linear and not mesh_is_linear;

  // In each direction, average the size of all different neighbors in that
  // direction. Note that only the component of neighor_size that is normal
  // to the face is needed (and, therefore, computed). Note that this average
  // does not depend on the solution on the neighboring elements, so could be
  // precomputed outside of `limit_one_tensor`. Changing the code to
  // precompute the average may or may not be a measurable optimization.
  const auto effective_neighbor_sizes =
      compute_effective_neighbor_sizes(element, neighbor_data);

  bool some_component_was_limited = false;
  for (size_t i = 0; i < tensor->size(); ++i) {
    // In each direction, average the mean of the i'th tensor component over
    // all different neighbors in that direction. This produces one effective
    // neighbor per direction.
    const auto effective_neighbor_means =
        compute_effective_neighbor_means<Tag>(i, element, neighbor_data);

    DataVector& u = (*tensor)[i];
    double u_mean = std::numeric_limits<double>::signaling_NaN();
    std::array<double, VolumeDim> u_limited_slopes{};
    const bool reduce_slopes = minmod_limited_slopes(
        u_lin_buffer, buffer, make_not_null(&u_mean),
        make_not_null(&u_limited_slopes), minmod_type, tvb_constant, u, mesh,
        element, element_size, effective_neighbor_means,
        effective_neighbor_sizes);

    if (reduce_slopes or using_linear_limiter_on_non_linear_mesh) {
      u = u_mean;
      for (size_t d = 0; d < VolumeDim; ++d) {
        u += logical_coords.get(d) * gsl::at(u_limited_slopes, d);
      }
      some_component_was_limited = true;
    }
  }  // end for loop over tensor components

  return some_component_was_limited;
}

}  // namespace Minmod_detail

template <size_t VolumeDim, typename... Tags>
Minmod<VolumeDim, tmpl::list<Tags...>>::Minmod(
    const MinmodType minmod_type, const double tvb_constant,
    const bool disable_for_debugging) noexcept
    : minmod_type_(minmod_type),
      tvb_constant_(tvb_constant),
      disable_for_debugging_(disable_for_debugging) {
  ASSERT(tvb_constant >= 0.0, "The TVB constant must be non-negative.");
}

template <size_t VolumeDim, typename... Tags>
void Minmod<VolumeDim, tmpl::list<Tags...>>::pup(PUP::er& p) noexcept {
  p | minmod_type_;
  p | tvb_constant_;
  p | disable_for_debugging_;
}

template <size_t VolumeDim, typename... Tags>
void Minmod<VolumeDim, tmpl::list<Tags...>>::package_data(
    const gsl::not_null<PackagedData*> packaged_data,
    const typename Tags::type&... tensors, const Mesh<VolumeDim>& mesh,
    const std::array<double, VolumeDim>& element_size,
    const OrientationMap<VolumeDim>& orientation_map) const noexcept {
  if (UNLIKELY(disable_for_debugging_)) {
    // Do not initialize packaged_data
    return;
  }

  const auto wrap_compute_means = [&mesh, &packaged_data](
                                      auto tag, const auto tensor) noexcept {
    for (size_t i = 0; i < tensor.size(); ++i) {
      // Compute the mean using the local orientation of the tensor and mesh:
      // this avoids the work of reorienting the tensor while giving the same
      // result.
      get<::Tags::Mean<decltype(tag)>>(packaged_data->means)[i] =
          mean_value(tensor[i], mesh);
    }
    return '0';
  };
  expand_pack(wrap_compute_means(Tags{}, tensors)...);
  packaged_data->element_size =
      orientation_map.permute_from_neighbor(element_size);
}

template <size_t VolumeDim, typename... Tags>
bool Minmod<VolumeDim, tmpl::list<Tags...>>::operator()(
    const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,
    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,
    const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,
    const std::array<double, VolumeDim>& element_size,
    const std::unordered_map<
        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,
        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&
        neighbor_data) const noexcept {
  if (UNLIKELY(disable_for_debugging_)) {
    // Do not modify input tensors
    return false;
  }

  DataVector u_lin_buffer(mesh.number_of_grid_points());
  Minmod_detail::BufferWrapper<VolumeDim> buffer(mesh);

  bool limiter_activated = false;
  const auto wrap_limit_one_tensor = [this, &limiter_activated, &element, &mesh,
                                      &logical_coords, &element_size,
                                      &neighbor_data, &u_lin_buffer, &buffer](
                                         auto tag, const auto tensor) noexcept {
    limiter_activated =
        Minmod_detail::limit_one_tensor<VolumeDim, decltype(tag)>(
            &u_lin_buffer, &buffer, tensor, minmod_type_, tvb_constant_, mesh,
            element, logical_coords, element_size, neighbor_data) or
        limiter_activated;
    return '0';
  };
  expand_pack(wrap_limit_one_tensor(Tags{}, tensors)...);
  return limiter_activated;
}

template <size_t LocalDim, typename LocalTagList>
bool operator==(const Minmod<LocalDim, LocalTagList>& lhs,
                const Minmod<LocalDim, LocalTagList>& rhs) noexcept {
  return lhs.minmod_type_ == rhs.minmod_type_ and
         lhs.tvb_constant_ == rhs.tvb_constant_ and
         lhs.disable_for_debugging_ == rhs.disable_for_debugging_;
}

template <size_t VolumeDim, typename TagList>
bool operator!=(const Minmod<VolumeDim, TagList>& lhs,
                const Minmod<VolumeDim, TagList>& rhs) noexcept {
  return not(lhs == rhs);
}

}  // namespace Limiters

ext: tpp

max_stars_repo_name: Ambrou/spectre

max_issues_repo_name: Ambrou/spectre

max_forks_repo_name: isaaclegred/spectre


text:
#include "command.h"

#include "kits_cmd.h"
#include "genarchive.h"
#include "mergeruns.h"
#include "agglog.h"
#include "logcat.h"
#include "verifylog.h"
#include "truncatelog.h"
#include "logstats.h"
#include "propstats.h"
#include "logpagestats.h"
#include "dbinspect.h"
#include "loganalysis.h"
#include "dbscan.h"
#include "addbackup.h"
#include "xctlatency.h"
#include "tracerestore.h"

#include <boost/foreach.hpp>

/*
 * Adapted from
 * http://stackoverflow.com/questions/582331/is-there-a-way-to-instantiate-objects-from-a-string-holding-their-class-name
 */
Command::ConstructorMap Command::constructorMap;

template<typename T> Command* createCommand()
{
    return new T;
}

#define REGISTER_COMMAND(str, cmd) \
{ \
    Command::constructorMap[str] = &createCommand<cmd>; \
}

void Command::init()
{
    /*
     * COMMANDS MUST BE REGISTERED HERE AND ONLY HERE
     */
    REGISTER_COMMAND("logcat", LogCat);
    //REGISTER_COMMAND("logreplay", LogReplay);
    REGISTER_COMMAND("genarchive", GenArchive);
    REGISTER_COMMAND("mergeruns", MergeRuns);
    REGISTER_COMMAND("verifylog", VerifyLog);
    REGISTER_COMMAND("truncatelog", TruncateLog);
    REGISTER_COMMAND("dbscan", DBScan);
    REGISTER_COMMAND("addbackup", AddBackup);
    REGISTER_COMMAND("xctlatency", XctLatency);
    REGISTER_COMMAND("agglog", AggLog);
    REGISTER_COMMAND("logstats", LogStats);
    REGISTER_COMMAND("logpagestats", LogPageStats);
    REGISTER_COMMAND("dbinspect", DBInspect);
    REGISTER_COMMAND("loganalysis", LogAnalysis);
    REGISTER_COMMAND("kits", KitsCommand);
    REGISTER_COMMAND("propstats", PropStats);
    REGISTER_COMMAND("tracerestore", RestoreTrace);
}

void Command::setupCommonOptions()
{
    options.add_options()
        ("help,h", "Displays help information regarding a specific command")
        ("config,c", po::value<string>()->implicit_value("zapps.conf"),
         "Specify path to a config file");
}

void Command::showCommands()
{
    cerr << "Usage: zapps <command> [options] "
        << endl << "Commands:" << endl;
    ConstructorMap::iterator it;
    for (it = constructorMap.begin(); it != constructorMap.end(); it++) {
        // Options common to all commands
        Command* cmd = (it->second)();
        cmd->setupCommonOptions();
        cmd->setupOptions();
        cerr << it->first << endl << cmd->options << endl << endl;
    }
}

Command* Command::parse(int argc, char ** argv)
{
    if (argc >= 2) {
        string cmdStr = argv[1];
        std::transform(cmdStr.begin(), cmdStr.end(), cmdStr.begin(), ::tolower);
        if (constructorMap.find(cmdStr) != constructorMap.end()) {
            Command* cmd = constructorMap[cmdStr]();
            cmd->setupCommonOptions();
            cmd->setCommandString(cmdStr);
            cmd->setupOptions();

            po::variables_map vm;
            po::store(po::parse_command_line(argc,argv,cmd->getOptions()), vm);
            if (vm.count("config") > 0) {
                string pathToFile = vm["config"].as<string>();
                std::ifstream file;
                file.open(pathToFile.c_str());
                po::store(po::parse_config_file(file,cmd->getOptions(), true), vm);
            }
            if (vm.count("help") > 0) {
                cmd->helpOption();
                return NULL;
            }

            po::notify(vm);
            cmd->setOptionValues(vm);
            return cmd;
        }
    }

    showCommands();
    return NULL;
}

void Command::setupSMOptions(po::options_description& options)
{
    boost::program_options::options_description smoptions("Storage Manager Options");
    smoptions.add_options()
    ("db-config-design", po::value<string>()->default_value("normal"),
       "")
    ("physical-hacks-enable", po::value<int>()->default_value(0),
        "Enables physical hacks, such as padding of records")
    ("db-worker-sli", po::value<bool>()->default_value(0),
        "Speculative Lock inheritance")
    ("db-loaders", po::value<int>()->default_value(10),
        "Specifies the number of threads that are used to load the db")
    ("db-worker-queueloops", po::value<int>()->default_value(10),
                "?")
    ("db-cl-batchsz", po::value<int>()->default_value(10),
                "Specify the batchsize of a client executing transactions")
    ("db-cl-thinktime", po::value<int>()->default_value(0),
            "Specify a 'thinktime' for a client")
    ("records-to-access", po::value<uint>()->default_value(0),
        "Used in the benchmarks for the secondary indexes")
    ("activation_delay", po::value<uint>()->default_value(0),
            "")
    ("db-workers", po::value<uint>()->default_value(1),
        "Specify the number of workers executing transactions")
    ("dir-trace", po::value<string>()->default_value("RAT"),
        "")
    /** System related options **/
    ("sys-maxcpucount", po::value<uint>()->default_value(0),
        "Maximum CPU Count of a system")
    ("sys-activecpucount", po::value<uint>()->default_value(0),
        "Active CPU Count of a system")
    /**SM Options**/
    ("sm_logdir", po::value<string>()->default_value("log"),
        "Path to log directory")
    ("sm_dbfile", po::value<string>()->default_value("db"),
        "Path to the file on which to store database pages")
    ("sm_format", po::value<bool>()->default_value(false),
        "Format SM by emptying logdir and truncating DB file")
    ("sm_truncate_log", po::value<bool>()->default_value(false)
        ->implicit_value(true),
        "Whether to truncate log partitions at SM shutdown")
    ("sm_truncate_archive", po::value<bool>()->default_value(false)
        ->implicit_value(true),
        "Whether to truncate log archive runs at SM shutdown")
    ("sm_log_partition_size", po::value<int>()->default_value(1024),
        "Size of a log partition in MB")
    ("sm_log_max_partitions", po::value<int>()->default_value(0),
        "Maximum number of partitions maintained in log directory")
    ("sm_log_delete_old_partitions", po::value<bool>()->default_value(true),
        "Whether to delete old log partitions as cleaner and chkpt make progress")
    ("sm_bufpoolsize", po::value<int>()->default_value(1024),
        "Size of buffer pool in MB")
    ("sm_fakeiodelay-enable", po::value<int>()->default_value(0),
        "Enables a artificial delay whenever there is a I/O operation")
    ("sm_fakeiodelay", po::value<uint>()->default_value(0),
            "Specify the imposed delay in usec")
    ("sm_errlog", po::value<string>()->default_value("shoremt.err.log"),
            "Path to the error log of the storage manager")
    ("sm_chkpt_interval", po::value<int>(),
            "Interval for checkpoint flushes")
    ("sm_log_fetch_buf_partitions", po::value<uint>()->default_value(0),
        "Number of partitions to buffer in memory for recovery")
    ("sm_log_page_flushers", po::value<uint>()->default_value(1),
        "Number of log page flushers")
    ("sm_preventive_chkpt", po::value<uint>()->default_value(1),
        "Disable/enable preventive checkpoints (0 to disable, 1 to enable)")
    ("sm_logbuf_seg_count", po::value<int>(),
        "Log Buffer Segment Count")
    ("sm_logbuf_flush_trigger", po::value<int>(),
        "?")
    ("sm_logbuf_block_size", po::value<int>(),
        "Log Buffer Block isze")
    ("sm_logbuf_part_size", po::value<int>(),
        "Log Buffer part size")
    ("sm_carray_slots", po::value<int>(),
        "")
    ("sm_vol_log_reads", po::value<bool>(),
        "Generate log records for every page read")
    ("sm_vol_log_writes", po::value<bool>(),
        "Generate log records for every page write")
    ("sm_vol_readonly", po::value<bool>(),
        "Volume will be opened in read-only mode and all writes from buffer pool \
         will be ignored (uses write elision and single-page recovery)")
    ("sm_vol_o_direct", po::value<bool>(),
        "Whether to open volume (i.e., db file) with O_DIRECT")
    ("sm_restart_instant", po::value<bool>(),
        "Enable instant restart")
    ("sm_restart_log_based_redo", po::value<bool>(),
        "Perform non-instant restart with log-based redo instead of page-based")
    ("sm_rawlock_gc_interval_ms", po::value<int>(),
        "Garbage Collection Interval in ms")
    ("sm_rawlock_lockpool_segsize", po::value<int>(),
        "Segment size Lockpool")
    ("sm_rawlock_xctpool_segsize", po::value<int>(),
        "Segment size Transaction Pool")
    ("sm_rawlock_gc_generation_count", po::value<int>(),
        "Garbage collection generation count")
    ("sm_rawlock_gc_init_generation_count", po::value<int>(),
        "Garbage collection initial generation count")
    ("sm_rawlock_lockpool_initseg", po::value<int>(),
        "Lock pool init segment")
    ("sm_rawlock_xctpool_segsize", po::value<int>(),
        "Transaction Pool Segment Size")
    ("sm_rawlock_gc_free_segment_count", po::value<int>(),
        "Garbage Collection Free Segment Count")
    ("sm_rawlock_gc_max_segment_count", po::value<int>(),
        "Garbage Collection Maximum Segment Count")
    ("sm_locktablesize", po::value<int>(),
        "Lock table size")
    ("sm_rawlock_xctpool_initseg", po::value<int>(),
        "Transaction Pool Initialization Segment")
    ("sm_cleaner_decoupled", po::value<bool>(),
        "Enable/Disable decoupled cleaner")
    ("sm_cleaner_interval_millisec", po::value<int>(),
        "Cleaner sleep interval in ms")
    ("sm_cleaner_workspace_size", po::value<int>(),
        "Size of cleaner write buffer")
    ("sm_cleaner_num_candidates", po::value<int>(),
        "Number of candidate frames considered by each cleaner round")
    ("sm_cleaner_policy", po::value<string>(),
        "Policy used by cleaner to select candidates")
    ("sm_cleaner_min_write_size", po::value<int>(),
        "Page cleaner only writes clusters of pages with this minimum size")
    ("sm_cleaner_min_write_ignore_freq", po::value<int>(),
        "Ignore min_write_size every N rounds of cleaning")
    ("sm_cleaner_ignore_metadata", po::value<bool>(),
        "Do not write metadata pages (stnode and alloc caches) in cleaner")
    ("sm_cleaner_async_candidate_collection", po::value<bool>(),
        "Collect candidate frames to be cleaned in an asynchronous thread")
    ("sm_archiver_workspace_size", po::value<int>(),
        "Workspace size archiver")
    // CS TODO: archiver currently only works with 1MB blocks
    // ("sm_archiver_block_size", po::value<int>()->default_value(1024*1024),
    //     "Archiver Block size")
    ("sm_archiver_bucket_size", po::value<int>()->default_value(128),
        "Archiver bucket size")
    ("sm_merge_factor", po::value<int>(),
        "Merging factor")
    ("sm_archiving_blocksize", po::value<int>(),
        "Archiving block size")
    ("sm_reformat_log", po::value<bool>(),
        "Enable/Disable reformat log")
    ("sm_logging", po::value<bool>()->default_value(true),
        "Enable/Disable logging")
    ("sm_decoupled_cleaner", po::value<bool>(),
        "Use log-based propagation to clean pages")
    ("sm_shutdown_clean", po::value<bool>(),
        "Force buffer before shutting down SM")
    ("sm_archiving", po::value<bool>(),
        "Enable/Disable archiving")
    ("sm_async_merging", po::value<bool>(),
        "Enable/Disable Asynchronous merging")
    ("sm_statistics", po::value<bool>(),
        "Enable/Disable display of statistics")
    ("sm_ticker_enable", po::value<bool>(),
        "Enable/Disable ticker (currently always enabled)")
    ("sm_ticker_msec", po::value<int>(),
        "Ticker interval in millisec")
    ("sm_prefetch", po::value<bool>(),
        "Enable/Disable prefetching")
    ("sm_backup_prefetcher_segments", po::value<int>(),
        "Segment size restore")
    ("sm_restore_segsize", po::value<int>(),
        "Segment size restore")
    ("sm_restore_prefetcher_window", po::value<int>(),
        "Segment size restore")
    ("sm_restore_instant", po::value<bool>(),
        "Enable/Disable instant restore")
    ("sm_restore_reuse_buffer", po::value<bool>(),
        "Enable/Disable reusage of buffer")
    ("sm_restore_multiple_segments", po::value<int>(),
        "Number of segments to attempt restore at once")
    ("sm_restore_min_read_size", po::value<int>(),
        "Attempt to read at least this many bytes when scanning log archive")
    ("sm_restore_max_read_size", po::value<int>(),
        "Attempt to read at most this many bytes when scanning log archive")
    ("sm_restore_preemptive", po::value<bool>(),
        "Use preemptive scheduling during restore")
    ("sm_restore_sched_singlepass", po::value<bool>(),
        "Use single-pass scheduling in restore")
    ("sm_restore_threads", po::value<int>(),
        "Number of restore threads to use")
    ("sm_restore_sched_ondemand", po::value<bool>(),
        "Support on-demand restore")
    ("sm_restore_sched_random", po::value<bool>(),
        "Use random page order in restore scheduler")
    ("sm_bufferpool_swizzle", po::value<bool>(),
        "Enable/Disable bufferpool swizzle")
    ("sm_archiver_eager", po::value<bool>(),
        "Enable/Disable eager archiving")
    ("sm_archiver_read_whole_blocks", po::value<bool>(),
        "Enable/Disable reading whole blocks in the archiver")
    ("sm_archiver_slow_log_grace_period", po::value<int>(),
        "Enable/Disable slow log grace period")
    ("sm_errlog_level", po::value<string>(),
        "Specify a errorlog level. Options:")
        //TODO Stefan Find levels and insert them
    ("sm_log_impl", po::value<string>(),
        "Choose log implementation. Options")
        //TODO Stefan Find Implementations
    ("sm_backup_dir", po::value<string>(),
        "Path to a backup directory")
    ("sm_bufferpool_replacement_policy", po::value<string>(),
        "Replacement Policy")
    ("sm_archdir", po::value<string>()->default_value("archive"),
        "Path to archive directory");
    options.add(smoptions);
}

void Command::helpOption()
{
    cerr << "Usage: zapps Command:" << commandString << " [options] "
                << endl << options << endl;
}

size_t LogScannerCommand::BLOCK_SIZE = 1024 * 1024;

BaseScanner* LogScannerCommand::getScanner(
        bitset<logrec_t::t_max_logrec>* filter)
{
    BaseScanner* s;
    if (isArchive) {
        if (merge) s = new MergeScanner(optionValues);
        else s = new LogArchiveScanner(optionValues);
    }
    else {
        s = new BlockScanner(optionValues, filter);
    }

    if (!filename.empty()) {
        s->setRestrictFile(logdir + "/" + filename);
    }

    return s;
}

void LogScannerCommand::setupOptions()
{
    setupSMOptions(options);
    po::options_description logscanner("Log Scanner Options");
    logscanner.add_options()
        ("logdir,l", po::value<string>(&logdir)->required(),
         "Directory containing log to be scanned")
        ("file,f", po::value<string>(&filename)->default_value(""),
            "Scan only a specific file inside the given directory")
        ("archive,a", po::value<bool>(&isArchive)->default_value(false)
         ->implicit_value(true),
            "Scan log archive files isntead of normal recovery log")
        ("merge,m", po::value<bool>(&merge)->default_value(false)
         ->implicit_value(true),
            "Merge archiver input so that global sort order is produced")
        ("limit,n", po::value<size_t>(&limit)->default_value(0),
             "Number of log records to scan")
        ;
    options.add(logscanner);
}

void Command::setSMOptions(sm_options& sm_opt, const po::variables_map& values)
{
    BOOST_FOREACH(const po::variables_map::value_type& pair, values)
    {
        const std::string& key = pair.first;
        try {
            sm_opt.set_int_option(key, values[key].as<int>());
        }
        catch(boost::bad_any_cast const& e) {
            try {
                cerr << "Set option " << key << " to " << values[key].as<bool>() << endl;
                sm_opt.set_bool_option(key, values[key].as<bool>());
            }
            catch(boost::bad_any_cast const& e) {
                try {
                    sm_opt.set_string_option(key, values[key].as<string>());
                }
                catch(boost::bad_any_cast const& e) {
                    try {
                        sm_opt.set_int_option(key, values[key].as<uint>());
                    }
                    catch(boost::bad_any_cast const& e) {
                        cerr << "Could not process option " << key
                            << " .. skippking." << endl;
                        continue;
                    }
                }
            }
        }
    };
}

max_stars_repo_name: lslersch/zero

max_issues_repo_name: lslersch/zero

max_forks_repo_name: lslersch/zero


text:
// Copyright (C) 2004-2008 The Trustees of Indiana University.

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#ifndef BOOST_GRAPH_DISTRIBUTED_DFS_HPP
#define BOOST_GRAPH_DISTRIBUTED_DFS_HPP

#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif

#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/overloading.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/distributed/concepts.hpp>
#include <boost/static_assert.hpp>
#include <boost/assert.hpp>
#include <boost/graph/parallel/process_group.hpp>
#include <boost/graph/parallel/container_traits.hpp>

namespace boost {
  namespace graph { namespace distributed { namespace detail {
    template<typename DistributedGraph, typename ColorMap, typename ParentMap,
             typename ExploreMap, typename VertexIndexMap, typename DFSVisitor>
    class parallel_dfs
    {
      typedef typename graph_traits<DistributedGraph>::vertex_iterator
        vertex_iterator;
      typedef typename graph_traits<DistributedGraph>::vertex_descriptor
        vertex_descriptor;
      typedef typename graph_traits<DistributedGraph>::out_edge_iterator
        out_edge_iterator;

      typedef typename boost::graph::parallel::process_group_type<DistributedGraph>
        ::type process_group_type;
      typedef typename process_group_type::process_id_type process_id_type;

      /**
       * The first vertex in the pair is the local node (i) and the
       * second vertex in the pair is the (possibly remote) node (j).
       */
      typedef boost::parallel::detail::untracked_pair<vertex_descriptor, vertex_descriptor> vertex_pair;

      typedef typename property_traits<ColorMap>::value_type color_type;
      typedef color_traits<color_type> Color;

      // Message types
      enum { discover_msg = 10, return_msg = 50, visited_msg = 100 , done_msg = 150};

    public:
      parallel_dfs(const DistributedGraph& g, ColorMap color,
                   ParentMap parent, ExploreMap explore,
                   VertexIndexMap index_map, DFSVisitor vis)
        : g(g), color(color), parent(parent), explore(explore),
          index_map(index_map), vis(vis), pg(process_group(g)),
          owner(get(vertex_owner, g)), next_out_edge(num_vertices(g))
      { }

      void run(vertex_descriptor s)
      {
        vertex_iterator vi, vi_end;
        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {
          put(color, *vi, Color::white());
          put(parent, *vi, *vi);
          put(explore, *vi, *vi);
          next_out_edge[get(index_map, *vi)] = out_edges(*vi, g).first;
          vis.initialize_vertex(*vi, g);
        }

        vis.start_vertex(s, g);

        if (get(owner, s) == process_id(pg)) {
          send_oob(pg, get(owner, s), discover_msg, vertex_pair(s, s));
        }

        bool done = false;
        while (!done) {
          std::pair<process_id_type, int> msg = *pg.poll(true);

          switch (msg.second) {
          case discover_msg:
            {
              vertex_pair p;
              receive_oob(pg, msg.first, msg.second, p);

              if (p.first != p.second) {
                // delete j from nomessage(j)
                if (get(color, p.second) != Color::black())
                  local_put(color, p.second, Color::gray());

                if (recover(p)) break;
              }

              if (get(color, p.first) == Color::white()) {
                put(color, p.first, Color::gray());
                put(parent, p.first, p.second);

                vis.discover_vertex(p.first, g);

                if (shift_center_of_activity(p.first)) break;

                out_edge_iterator ei, ei_end;
                for (boost::tie(ei,ei_end) = out_edges(p.first, g); ei != ei_end; ++ei)
                {
                  // Notify everyone who may not know that the source
                  // vertex has been visited. They can then mark the
                  // corresponding color map entry gray.
                  if (get(parent, p.first) != target(*ei, g)
                      && get(explore, p.first) != target(*ei, g)) {
                    vertex_pair visit(target(*ei, g), p.first);

                    send_oob(pg, get(owner, target(*ei, g)), visited_msg, visit);
                  }
                }
              }
            }
            break;

          case visited_msg:
            {
              vertex_pair p;
              receive_oob(pg, msg.first, msg.second, p);

              // delete j from nomessage(j)
              if (get(color, p.second) != Color::black())
                local_put(color, p.second, Color::gray());

              recover(p);
            }
            break;

          case return_msg:
            {
              vertex_pair p;
              receive_oob(pg, msg.first, msg.second, p);

              // delete j from nomessage(i)
              local_put(color, p.second, Color::black());

              shift_center_of_activity(p.first);
            }
            break;

          case done_msg:
            {
              receive_oob(pg, msg.first, msg.second, done);

              // Propagate done message downward in tree
              done = true;
              process_id_type id = process_id(pg);
              process_id_type left = 2*id + 1;
              process_id_type right = left + 1;
              if (left < num_processes(pg))
                send_oob(pg, left, done_msg, done);
              if (right < num_processes(pg))
                send_oob(pg, right, done_msg, done);
            }
            break;

          default:
            BOOST_ASSERT(false);
          }
        }
      }

    private:
      bool recover(const vertex_pair& p)
      {
        if (get(explore, p.first) == p.second) {
          return shift_center_of_activity(p.first);
        }
        else
          return false;
      }

      bool shift_center_of_activity(vertex_descriptor i)
      {
        for (out_edge_iterator ei = next_out_edge[get(index_map, i)],
                               ei_end = out_edges(i, g).second;
             ei != ei_end; ++ei) {
          vis.examine_edge(*ei, g);

          vertex_descriptor k = target(*ei, g);
          color_type target_color = get(color, k);
          if (target_color == Color::black()) vis.forward_or_cross_edge(*ei, g);
          else if (target_color == Color::gray()) vis.back_edge(*ei, g);
          else {
            put(explore, i, k);
            vis.tree_edge(*ei, g);
            vertex_pair p(k, i);
            send_oob(pg, get(owner, k), discover_msg, p);
            next_out_edge[get(index_map, i)] = ++ei;
            return false;
          }
        }

        next_out_edge[get(index_map, i)] = out_edges(i, g).second;
        put(explore, i, i);
        put(color, i, Color::black());
        vis.finish_vertex(i, g);

        if (get(parent, i) == i) {
          send_oob(pg, 0, done_msg, true);
          return true;
        }
        else {
          vertex_pair ret(get(parent, i), i);
          send_oob(pg, get(owner, ret.first), return_msg, ret);
        }
        return false;
      }

      const DistributedGraph& g;
      ColorMap color;
      ParentMap parent;
      ExploreMap explore;
      VertexIndexMap index_map;
      DFSVisitor vis;
      process_group_type pg;
      typename property_map<DistributedGraph, vertex_owner_t>::const_type owner;
      std::vector<out_edge_iterator> next_out_edge;
    };
  } // end namespace detail

  template<typename DistributedGraph, typename ColorMap, typename ParentMap,
           typename ExploreMap, typename VertexIndexMap, typename DFSVisitor>
  void
  tsin_depth_first_visit
    (const DistributedGraph& g,
     typename graph_traits<DistributedGraph>::vertex_descriptor s,
     DFSVisitor vis, ColorMap color, ParentMap parent, ExploreMap explore,
     VertexIndexMap index_map)
  {
    typedef typename graph_traits<DistributedGraph>::directed_category
      directed_category;
    BOOST_STATIC_ASSERT(
      (is_convertible<directed_category, undirected_tag>::value));

    set_property_map_role(vertex_color, color);
    graph::distributed::detail::parallel_dfs
      <DistributedGraph, ColorMap, ParentMap, ExploreMap, VertexIndexMap,
       DFSVisitor> do_dfs(g, color, parent, explore, index_map, vis);
    do_dfs.run(s);

    using boost::graph::parallel::process_group;
    synchronize(process_group(g));
  }

  template<typename DistributedGraph, typename DFSVisitor,
           typename VertexIndexMap>
  void
  tsin_depth_first_visit
    (const DistributedGraph& g,
     typename graph_traits<DistributedGraph>::vertex_descriptor s,
     DFSVisitor vis,
     VertexIndexMap index_map)
  {
    typedef typename graph_traits<DistributedGraph>::vertex_descriptor
      vertex_descriptor;

    std::vector<default_color_type> colors(num_vertices(g));
    std::vector<vertex_descriptor> parent(num_vertices(g));
    std::vector<vertex_descriptor> explore(num_vertices(g));
    tsin_depth_first_visit
      (g, s,
       vis,
       make_iterator_property_map(colors.begin(), index_map),
       make_iterator_property_map(parent.begin(), index_map),
       make_iterator_property_map(explore.begin(), index_map),
       index_map);
  }

  template<typename DistributedGraph, typename DFSVisitor,
           typename VertexIndexMap>
  void
  tsin_depth_first_visit
    (const DistributedGraph& g,
     typename graph_traits<DistributedGraph>::vertex_descriptor s,
     DFSVisitor vis)
  {
    tsin_depth_first_visit(g, s, vis, get(vertex_index, g));
  }
} // end namespace distributed

using distributed::tsin_depth_first_visit;

} // end namespace graph

template<typename DistributedGraph, typename DFSVisitor>
void
depth_first_visit
  (const DistributedGraph& g,
   typename graph_traits<DistributedGraph>::vertex_descriptor s,
   DFSVisitor vis)
{
  graph::tsin_depth_first_visit(g, s, vis, get(vertex_index, g));
}

} // end namespace boost

#endif // BOOST_GRAPH_DISTRIBUTED_DFS_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
// Copyright (C) 2009-2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/local_function

#include <boost/local_function.hpp>
#include <boost/typeof/typeof.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
#include <boost/detail/lightweight_test.hpp>
#include <vector>
#include <algorithm>

struct v;
BOOST_TYPEOF_REGISTER_TYPE(v) // Register before `bind this_` below.

struct v {
    std::vector<int> nums;

    v(const std::vector<int>& numbers): nums(numbers) {}

    void change_sign_all(const std::vector<int>& indices) {
        void BOOST_LOCAL_FUNCTION(bind this_, int i) { // Bind object `this`.
            this_->nums.at(i) = -this_->nums.at(i);
        } BOOST_LOCAL_FUNCTION_NAME(complement)

        std::for_each(indices.begin(), indices.end(), complement);
    }
};

int main(void) {
    std::vector<int> n(3);
    n[0] = 1; n[1] = 2; n[2] = 3;

    std::vector<int> i(2);
    i[0] = 0; i[1] = 2; // Will change n[0] and n[2] but not n[1].

    v vn(n);
    vn.change_sign_all(i);

    BOOST_TEST(vn.nums.at(0) == -1);
    BOOST_TEST(vn.nums.at(1) == 2);
    BOOST_TEST(vn.nums.at(2) == -3);
    return boost::report_errors();
}