////////////////////////////////////////////////////////////////////////////////
// Set the trace facility to be used
////////////////////////////////////////////////////////////////////////////////
Uint32 Tracer::setTraceFacility(const String& traceFacility)
{
    Uint32 retCode = 0;
    Tracer* instance = _getInstance();

    if (traceFacility.size() != 0)
    {
        Uint32 index = 0;
        while (TRACE_FACILITY_LIST[index] != 0 )
        {
            if (String::equalNoCase( traceFacility,TRACE_FACILITY_LIST[index]))
            {
                if (index != instance->_traceFacility)
                {
                    instance->_setTraceHandler(index);
                }
                retCode = 1;
                break;
            }
            index++;
        }
    }

    return retCode;
}
Exemple #2
0
void 
Controller::render(){
	Tracer* trace = new Tracer(root);
	trace->setDimensions(500,500);
	trace->InitRender();
	trace->Render();
}
Exemple #3
0
	Ref<Object> Tracer::dump(Frame * frame)
	{
		Tracer * tracer = NULL;
		
		frame->extract()(tracer, "self");
		
		StringStreamT buffer;
		tracer->dump(frame, buffer);
		
		return new(frame) String(buffer.str());
	}
Exemple #4
0
void closer (t_Tracer_OpenTr *open)
{
    Debugger                *c;
    PROCESS_INFORMATION     ProcInfo;
    char                    bla[30];
    
    if (open->Definition->Name == "CreateProcessA")
    {
        printf("MAIN: Process created (CreateProcessA)\n");

        if (!ReadProcessMemory(dbg.getProcessHandle(),
                               (LPCVOID)(open->OutArgs[9].data.address),
                               &ProcInfo,
                               sizeof(ProcInfo),
                               NULL))
        {
            printf("Failed to read process memory at %08X\n", open->OutArgs[9].data.address);
        }
        else
        {
            c = new (Debugger);

            sprintf(bla,"Child %u",ProcInfo.dwProcessId);
            c->attach(ProcInfo.dwProcessId);
            c->log.Name= bla;

            Children.push_back(c);
        }
    }
    else if (open->Definition->Name == "CreateProcessAsUserA")
    {
        printf("MAIN: Process created (CreateProcessAsUserA)\n");

        if (!ReadProcessMemory(dbg.getProcessHandle(),
                               (LPCVOID)(open->OutArgs[10].data.address),
                               &ProcInfo,
                               sizeof(ProcInfo),
                               NULL))
        {
            printf("Failed to read process memory at %08X\n", open->OutArgs[10].data.address);
        }
        else
        {
            c = new (Debugger);

            sprintf(bla,"Child %u",ProcInfo.dwProcessId);
            c->attach(ProcInfo.dwProcessId);
            c->log.Name= bla;

            Children.push_back(c);
        }
    } 
}
void Tracer::setTraceLevel(TraceLevel tracelevel, bool recursive)
{
    m_tracelevel = tracelevel;

    if (recursive) {
        // set the tracelevl of all children recursively
        Tracer* child;
        for (child = m_children->first(); child; child = m_children->next()) {
            child->setTraceLevel(tracelevel, true);
        }
    }
}
TEST(HooksTest, UnknownChildHook)
{
    pid_t child_pid = fork();
    if (child_pid == 0) {
        _exit(0);
    }

    ASSERT_GE(child_pid, 0);

    std::optional<pid_t> exited_pid;
    std::optional<pid_t> unknown_pid;

    Tracer tracer;

    // Tracee must remain alive long enough for child_pid to exit
    auto tracee = tracer.fork([] { while (true) pause(); });
    ASSERT_TRUE(tracee);

    auto tracee_tid = tracee.value()->tid;

    Hooks hooks;

    hooks.syscall_entry = [&](auto t, auto &info) {
        if (unknown_pid) {
            SysCall sc("exit_group", info.syscall.abi());
            assert(sc);
            (void) t->modify_syscall_args(sc.num(), {});
        }
        return action::Default{};
    };

    hooks.tracee_exit = [&](auto pid, auto) {
        exited_pid = pid;
        return action::Default{};
    };

    hooks.unknown_child = [&](auto pid, auto) {
        unknown_pid = pid;

        // tracee must be a valid pointer because this hook would not have been
        // called if the only tracee exited or died
        (void) tracee.value()->interrupt();
    };

    ASSERT_TRUE(tracer.execute(hooks));

    ASSERT_EQ(exited_pid, tracee_tid);
    ASSERT_EQ(unknown_pid, child_pid);
}
//set the trace file number for rolling only when the tracing is on a file
void Tracer::setMaxTraceFileNumber(const String &maxTraceFileNumber)
{
    Tracer *inst = _getInstance();

    if ( inst->getTraceFacility() == TRACE_FACILITY_FILE )
    {
        Uint32 numberOfTraceFiles = 0;
        tracePropertyToUint32(maxTraceFileNumber, numberOfTraceFiles);

        //Safe to typecast here as we know that handler is of type file
        TraceFileHandler *hdlr = (TraceFileHandler*) (inst->_traceHandler);

        hdlr->setMaxTraceFileNumber(numberOfTraceFiles);
     }
}
//set the trace file size only when the tracing is on a file
void Tracer::setMaxTraceFileSize(const String &size) 
{  
    Tracer *inst = _getInstance();
    if ( inst->getTraceFacility() == TRACE_FACILITY_FILE )
    {
        Uint32 traceFileSizeKBytes = 0;
        tracePropertyToUint32(size, traceFileSizeKBytes);

        //Safe to typecast here as we know that handler is of type file
        TraceFileHandler *hdlr = (TraceFileHandler*) (inst->_traceHandler);

        hdlr->setMaxTraceFileSize(traceFileSizeKBytes*1024);

    }
} 
Exemple #9
0
void operator delete[](void* p)  
{  
        if (Tracer::Ready)  
                gNewTracer.Remove(p);  
        cout << "delete[](void* p)"<<endl;  
        free(p);  
}  
Exemple #10
0
void* operator new[] (size_t size)  
{  
        void* p = malloc(size);  
        if (Tracer::Ready)  
                gNewTracer.Add(p, "?", 0);  
        return p;  
}  
Exemple #11
0
void operator delete[](void* p, const char* file, int line)  
{  
        if (Tracer::Ready)  
                gNewTracer.Remove(p);  
        cout <<"delete[](void* p, const char* file, int line)" <<endl;  
        free(p);  
}  
Exemple #12
0
void* operator new [](size_t size, const char* file, int line)  
{  
        void* p = malloc(size);  
        if (Tracer::Ready)  
                gNewTracer.Add(p, file, line);  
        return p;  
}  
Exemple #13
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// ps_base_address()
//
// search through all loaded modules for a string match and return it's base address.
//
bool ps_base_address (char *module, DWORD *address, DWORD *size)
{
    map <DWORD,t_Debugger_memory*>::const_iterator  it;
    
    dbg.ReBuildMemoryMap();

    // determine the base address of the executable section for the loaded module.
    for (it = dbg.MemoryMap.begin(); it != dbg.MemoryMap.end(); ++it)
    {
        // match the module name.
        if (stricmp(it->second->Name.c_str(), module) != 0)
            continue;

        // ensure we found the correct section.
        if ((it->second->basics.Protect & PAGE_EXECUTE)           ||
            (it->second->basics.Protect & PAGE_EXECUTE_READ)      ||
            (it->second->basics.Protect & PAGE_EXECUTE_READWRITE) ||
            (it->second->basics.Protect & PAGE_EXECUTE_WRITECOPY))
        {
            // module executable section found.
            *address = it->second->address;
            *size    = it->second->basics.RegionSize;
            return true;
        }
    }

    return false;
}
void Tracer::dump(QString indention) const
{
    // print some useful infos about this tracer
    kdbgstream(indention, 0, 999, true)
            << "- "
            << *m_tracerpartname
            << " [" << TRACE_LEVEL_NAME[m_tracelevel] << "] "
            << "(classname: " << *m_classname << "), "
            << "fulltracername: " << *m_tracername
            << endl;

    // call dump on each child
    indention.append("  ");
    Tracer* child;
    for (child = m_children->first(); child; child = m_children->next()) {
        child->dump(indention);
    }
}
int main(int argn, char* argv[])
{
	po::variables_map vm = parse_program_options(argn, argv);

	if(vm.empty() || vm.count("help"))
	{
		return 0;
	}

	pid_t child_pid = fork();

	if(child_pid == 0)
	{
		// Make args string vector into null-terminated char* array
		std::vector<std::string> args_vec = vm["commands"].as<std::vector<std::string>>();
		std::vector<char*> args;

		for(auto& arg : args_vec)
		{
			args.push_back(const_cast<char*>(arg.c_str()));
		}

		args.push_back(nullptr);

		// Run given process
		if(!run_child(args_vec.front(), args.data()))
		{
			std::cerr << "Error : Failed to execute and trace the given commands." << std::endl;
		}
	}
	else if(child_pid == -1)
	{
		std::cerr << "Error : Failed to execute the given commands." << std::endl;
	}
	else
	{
		Tracer tracer;
		tracer.do_trace(child_pid, vm);
	}

	return 0;
}
TEST(HooksTest, TraceeExitHook)
{
    std::optional<int> exit_code;

    Hooks hooks;

    hooks.tracee_exit = [&](auto, auto ec) {
        exit_code = ec;
        return action::Default{};
    };

    Tracer tracer;

    ASSERT_TRUE(tracer.fork([&] {
        _exit(10);
    }));

    ASSERT_TRUE(tracer.execute(hooks));

    ASSERT_EQ(exit_code, 10);
}
TEST(HooksTest, TraceeDeathHook)
{
    std::optional<int> death_signal;

    Hooks hooks;

    hooks.tracee_death = [&](auto, auto signal) {
        death_signal = signal;
        return action::Default{};
    };

    Tracer tracer;

    ASSERT_TRUE(tracer.fork([&] {
        raise(SIGTERM);
    }));

    ASSERT_TRUE(tracer.execute(hooks));

    ASSERT_EQ(death_signal, SIGTERM);
}
int main()
{
  Signal<Vector,int> sig1( "sig1" );
  Vector v1(2); v1.fill(1.1); sig1 = v1;

  Signal<Vector,int> sig2( "sig2" );
  Vector v2(4); v2.fill(2.); sig2 = v2;

  Signal<Vector,int> sig3( "sig3" );
  Vector v3(6); v3.fill(3.); sig3 = v3;

  SignalTimeDependent<double,int> sigM( f,sotNOSIGNAL,"sigM" );
  sigM.access(0);
  
  Tracer* tracer = new Tracer( "trace" );
  tracer->addSignalToTrace( sig1 );
  tracer->openFiles( "/tmp/sot-core","tr_",".dat" );
  
  tracer->addSignalToTrace( sig2 );

  return 0;
}
Exemple #19
0
int main(int argc, char* argv[])
{
    if (argc < 3) {
        std::cerr << "Usage: "<<argv[0]<<" <host> <port>"<< endl;
        return 1;
    }
    serverIp = argv[1];
    serverPort = argv[2];

    try {
        io_service io_service;

        PutTraceReq putReq;
        Tracer* tracerPtr = putReq.mutable_tracer();
        tracerPtr->set_uid("190836141");
        tracerPtr->set_id("1778");
        tracerPtr->set_type("device_log");
        tracerPtr->set_time(time(0));
        tracerPtr->set_src("internal");
        tracerPtr->set_key("online_status");
        tracerPtr->set_value("this is the value");
        tracerPtr->set_status("0");

        eachPut(io_service, putReq);

        GetTraceReq getReq;
        getReq.set_uid("190836141");
        eachGet(io_service, getReq);

        io_service.run();
    }
    catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}
Exemple #20
0
bool Client::IsVisible (const Vector &pos) const
{
   Tracer trace (GetHeadOrigin (), pos, NO_BOTH, m_ent);

   return ! (trace.Fire () != 1.0);
}
//
// public static methods
//
Tracer* Tracer::getInstance(const char* tracername, const char* classname)
{
    QString strTracername(tracername);
    QString strClassname(classname);

    // if neither tracername nor classname is specified we return the root-tracer
    if (strTracername.isEmpty() && strClassname.isEmpty()) {
        return getRootTracer();
    }

    Tracer* currentTracer = getRootTracer();
    QString currentTracerName = QString("");
    
    // split the tracername into its parts
    QStringList parts = QStringList::split(TRACER_NAME_SEPARATOR, strTracername, false);

    // if specified the classname is handled as last part of the tracername
    if (!strClassname.isEmpty()) {
        parts.append(strClassname);
    }

    int partsCount = parts.count();

    // loop over the tracename parts and
    // try to get the tracer matching the tracername and classname
    // as soon as we don't find a matching subtracer we begin to create new tracers...
    for (int i = 0; i < partsCount; i++) {
        QString part = parts[i];
        
        // create the tracername of the tracer we would like at this point
        if (i > 0) {
            currentTracerName = currentTracerName.append(TRACER_NAME_SEPARATOR);
        }
        currentTracerName = currentTracerName.append(part);

        // try to get a matching tracer for the currentTracerName
        Tracer* matchingChild = currentTracer->getChild(part);
        if (matchingChild) {
            currentTracer = matchingChild;
        } else {
            //no matching subtracer found --> create one!

            Tracer* child;
            if (i + 1 == partsCount) {
                // this is the last tracer to instantiate --> create WITH classname
                child = new Tracer(currentTracerName, part, strClassname);
            } else {
                // this is a missing supertracer of the tracer to create --> create without classname
                child = new Tracer(currentTracerName, part, "");
            }

            // link the new tracer into the tracer tree
            currentTracer->m_children->append(child);
            child->m_parent = currentTracer;

            // tracers inherit the tracelevel of the parent
            child->m_tracelevel = currentTracer->m_tracelevel;
            
            currentTracer = child;
        }
    }

    // if a classname is specified but the resulting tracer has no one set
    // the tracer was already instantiated without a classname set
    // this most likely occurs when the tracer was configured by a traceconfigfile
    // --> force the classname
    if (!strClassname.isEmpty() && currentTracer->m_classname->isEmpty()) {
        currentTracer->m_classname = new QString(strClassname);
    }
    

    return currentTracer;
}
Exemple #22
0
int main (int argc, char** argv)
{

	/*---------------------- Initialize OpenGL and OpenCL ----------------------*/

	if (init_gl(argc,argv,&glinfo, window_size, "RT") != 0){
		std::cerr << "Failed to initialize GL" << std::endl;
		exit(1);
	} else { 
		std::cout << "Initialized GL succesfully" << std::endl;
	}

	if (init_cl(glinfo,&clinfo) != CL_SUCCESS){
		std::cerr << "Failed to initialize CL" << std::endl;
		exit(1);
	} else { 
		std::cout << "Initialized CL succesfully" << std::endl;
	}
	print_cl_info(clinfo);

        /* Initialize device interface */
        if (device.initialize(clinfo)) {
                std::cerr << "Failed to initialize device interface" << std::endl;
                exit(1);
        }
        /* Initialize generic gpu library */
        DeviceFunctionLibrary::initialize(clinfo);

	/*---------------------- Create shared GL-CL texture ----------------------*/
	gl_tex = create_tex_gl(window_size[0],window_size[1]);
        tex_id = device.new_memory();
        DeviceMemory& tex_mem = device.memory(tex_id);
        if (tex_mem.initialize_from_gl_texture(gl_tex)) {
                std::cerr << "Failed to create memory object from gl texture" << std::endl;
                exit(1);
        }

	/*---------------------- Set up scene ---------------------------*/
	frames = 15;
	const std::string pack = "pack1OBJ";
	// const std::string pack = "pack2OBJ";
	double wave_attenuation = 1.f;

        scenes.resize(frames);
	for (uint32_t i = 0; i < frames ; ++i) {

                scenes[i].initialize();
		std::stringstream grid_path,visual_path;
		grid_path << "models/obj/" << pack << "/gridFluid" << i+1 << ".obj";
		mesh_id grid_mid = scenes[i].load_obj_file_as_aggregate(grid_path.str());
		object_id grid_oid = scenes[i].add_object(grid_mid);
		Object& grid = scenes[i].object(grid_oid);
		grid.mat.diffuse = White;
		grid.mat.reflectiveness = 0.95f;
		grid.mat.refractive_index = 1.5f;
		grid.geom.setScale(makeVector(1.f,wave_attenuation,1.f));

		/* ---- Solids ------ */
		// visual_path << "models/obj/" << pack << "/visual" << visual_frame << ".obj";
		// mesh_id visual_mid = scenes[i].load_obj_file_as_aggregate(visual_path.str());
		// object_id visual_oid = scenes[i].geometry.add_object(visual_mid);
		// Object& visual = scenes[i].geometry.object(visual_oid);
		// visual.mat.diffuse = Red;

		// for (uint32_t j = 0; j < bridge_parts ; ++j) {
		// 	std::stringstream bridge_path;
		// 	bridge_path << "models/obj/" << pack << "/bridge" << j << i+1 << ".obj";
		// 	mesh_id bridge_mid = scenes[i].load_obj_file_as_aggregate(bridge_path.str());
		// 	object_id bridge_oid = scenes[i].geometry.add_object(bridge_mid);
		// 	Object& bridge = scenes[i].geometry.object(bridge_oid);
		// 	bridge.mat.diffuse = Green;
		// }

		// mesh_id teapot_mesh_id = scenes[i].load_obj_file_as_aggregate("models/obj/teapot2.obj");
		// mesh_id teapot_mesh_id = scenes[i].load_obj_file_as_aggregate("models/obj/teapot-low_res.obj");
		// object_id teapot_obj_id = scenes[i].geometry.add_object(teapot_mesh_id);
		// Object& teapot_obj = scenes[i].geometry.object(teapot_obj_id);
		// teapot_obj.geom.setPos(makeVector(-1.f,0.f,0.f));
		// teapot_obj.geom.setScale(makeVector(3.f,3.f,3.f));
		// teapot_obj.mat.diffuse = Green;
		// teapot_obj.mat.shininess = 1.f;
		// teapot_obj.mat.reflectiveness = 0.3f;

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

                // scenes[i].set_accelerator_type(KDTREE_ACCELERATOR);
                scenes[i].set_accelerator_type(BVH_ACCELERATOR);
		scenes[i].create_aggregate_mesh();
		scenes[i].create_aggregate_accelerator();
		Mesh& scene_mesh = scenes[i].get_aggregate_mesh();
                if (scenes[i].transfer_aggregate_mesh_to_device() 
                    || scenes[i].transfer_aggregate_accelerator_to_device())
                        std::cerr << "Failed to transfer scene info to device"<< std::endl;


		/*---------------------- Print scene data ----------------------*/
		std::cerr << "Scene " << i << " stats: " << std::endl;
		std::cerr << "\tTriangle count: " << scene_mesh.triangleCount() << std::endl;
		std::cerr << "\tVertex count: " << scene_mesh.vertexCount() << std::endl;
		std::cerr << std::endl;
	}


	/*---------------------- Set initial Camera paramaters -----------------------*/
	camera.set(makeVector(0,3,-30), makeVector(0,0,1), makeVector(0,1,0), M_PI/4.,
		   window_size[0] / (float)window_size[1]);

	/*---------------------------- Set tile size ------------------------------*/
	best_tile_size = clinfo.max_compute_units * clinfo.max_work_item_sizes[0];
	best_tile_size *= 64;
	best_tile_size = std::min(pixel_count, best_tile_size);

	/*---------------------- Initialize ray bundles -----------------------------*/
	int32_t ray_bundle_size = best_tile_size * 4;

	if (ray_bundle_1.initialize(ray_bundle_size)) {
		std::cerr << "Error initializing ray bundle 1" << std::endl;
		std::cerr.flush();
		exit(1);
	}

	if (ray_bundle_2.initialize(ray_bundle_size)) {
		std::cerr << "Error initializing ray bundle 2" << std::endl;
		std::cerr.flush();
		exit(1);
	}
	std::cout << "Initialized ray bundles succesfully" << std::endl;

	/*---------------------- Initialize hit bundle -----------------------------*/
	int32_t hit_bundle_size = ray_bundle_size;

	if (hit_bundle.initialize(hit_bundle_size)) {
		std::cerr << "Error initializing hit bundle" << std::endl;
		std::cerr.flush();
		exit(1);
	}
	std::cout << "Initialized hit bundle succesfully" << std::endl;

	/*----------------------- Initialize cubemap ---------------------------*/
	if (cubemap.initialize("textures/cubemap/Path/posx.jpg",
                               "textures/cubemap/Path/negx.jpg",
                               "textures/cubemap/Path/posy.jpg",
                               "textures/cubemap/Path/negy.jpg",
                               "textures/cubemap/Path/posz.jpg",
                               "textures/cubemap/Path/negz.jpg")) {  
		std::cerr << "Failed to initialize cubemap." << std::endl;
		exit(1);
	}
	std::cerr << "Initialized cubemap succesfully." << std::endl;

	/*------------------------ Initialize FrameBuffer ---------------------------*/
	if (framebuffer.initialize(window_size)) {
		std::cerr << "Error initializing framebuffer." << std::endl;
		exit(1);
	}
	std::cout << "Initialized framebuffer succesfully." << std::endl;

	/* ------------------ Initialize ray tracer kernel ----------------------*/
	if (tracer.initialize()){
		std::cerr << "Failed to initialize tracer." << std::endl;
		return 0;
	}
	std::cerr << "Initialized tracer succesfully." << std::endl;


	/* ------------------ Initialize Primary Ray Generator ----------------------*/
	if (prim_ray_gen.initialize()) {
		std::cerr << "Error initializing primary ray generator." << std::endl;
		exit(1);
	}
	std::cout << "Initialized primary ray generator succesfully." << std::endl;


	/* ------------------ Initialize Secondary Ray Generator ----------------------*/
	if (sec_ray_gen.initialize()) {
		std::cerr << "Error initializing secondary ray generator." << std::endl;
		exit(1);
	}
	sec_ray_gen.set_max_rays(ray_bundle_1.count());
	std::cout << "Initialized secondary ray generator succesfully." << std::endl;

	/*------------------------ Initialize RayShader ---------------------------*/
	if (ray_shader.initialize()) {
		std::cerr << "Error initializing ray shader." << std::endl;
		exit(1);
	}
	std::cout << "Initialized ray shader succesfully." << std::endl;

	/*----------------------- Enable timing in all clases -------------------*/
	framebuffer.timing(true);
	prim_ray_gen.timing(true);
	sec_ray_gen.timing(true);
	tracer.timing(true);
	ray_shader.timing(true);

	/*------------------------- Count mem usage -----------------------------------*/
	int32_t total_cl_mem = 0;
	total_cl_mem += pixel_count * 4; /* 4bpp texture */
	// for (uint32_t i = 0; i < frames; ++i)  
	// 	total_cl_mem += scene_info[i].size();
	total_cl_mem += ray_bundle_1.mem().size() + ray_bundle_2.mem().size();
	total_cl_mem += hit_bundle.mem().size();
	total_cl_mem += cubemap.positive_x_mem().size() * 6;
	total_cl_mem += framebuffer.image_mem().size();

	std::cout << "\nMemory stats: " << std::endl;
	std::cout << "\tTotal opencl mem usage: " 
		  << total_cl_mem/1e6 << " MB." << std::endl;
	// for (uint32_t i = 0; i < frames; ++i)  
	// 	std::cout << "\tScene " << i << " mem usage: " << scene_info[i].size()/1e6 << " MB." << std::endl;

	std::cout << "\tFramebuffer+Tex mem usage: " 
		  << (framebuffer.image_mem().size() + pixel_count * 4)/1e6
		  << " MB."<< std::endl;
	std::cout << "\tCubemap mem usage: " 
		  << (cubemap.positive_x_mem().size()*6)/1e6 
		  << " MB."<< std::endl;
	std::cout << "\tRay mem usage: " 
		  << (ray_bundle_1.mem().size()*2)/1e6
		  << " MB."<< std::endl;
	std::cout << "\tRay hit info mem usage: " 
		  << hit_bundle.mem().size()/1e6
		  << " MB."<< std::endl;

        /* !! ---------------------- Test area ---------------- */
	std::cerr << std::endl;
	std::cerr << "Misc info: " << std::endl;

	std::cerr << "Tile size: " << best_tile_size << std::endl;
	std::cerr << "Tiles: " << pixel_count / (float)best_tile_size << std::endl;
	std::cerr << "color_cl size: "
		  << sizeof(color_cl)
		  << std::endl;
	std::cerr << "directional_light_cl size: "
		  << sizeof(directional_light_cl)
		  << std::endl;

	std::cerr << "ray_cl size: "
		  << sizeof(ray_cl)
		  << std::endl;
	std::cerr << "sample_cl size: "
		  << sizeof(sample_cl)
		  << std::endl;
	std::cerr << "sample_trace_info_cl size: "
		  << sizeof(sample_trace_info_cl)
		  << std::endl;

	/*------------------------ Set GLUT and misc functions -----------------------*/
	rt_time.snap_time();
	seq_time.snap_time();

	glutKeyboardFunc(gl_key);
	glutMotionFunc(gl_mouse);
	glutDisplayFunc(gl_loop);
	glutIdleFunc(gl_loop);
	glutMainLoop();	

	clinfo.release_resources();

	return 0;
}
Exemple #23
0
void gl_loop()
{
	static int i = 0;
	static int dir = 1;
	static int total_ray_count = 0;
	static double min_time=-1;
	static double max_time=-1;

	double prim_gen_time = 0;
	double sec_gen_time = 0;
	double prim_trace_time = 0;
	double sec_trace_time = 0;
	double prim_shadow_trace_time = 0;
	double sec_shadow_trace_time = 0;
	double shader_time = 0;
	double fb_clear_time = 0;
	double fb_copy_time = 0;

	glClear(GL_COLOR_BUFFER_BIT);

        if (device.acquire_graphic_resource(tex_id) ||
            cubemap.acquire_graphic_resources()) {
                std::cerr << "Error acquiring texture resource." << std::endl;
                exit(1);
        }

        for (size_t i = 0; i < scenes.size(); ++i) {
                Scene& scene = scenes[i];
                if (scene.acquire_graphic_resources()) {
                        std::cerr << "Error acquiring texture resource." << std::endl;
                        exit(1);
                }
        }

        if (framebuffer.clear()) {
		std::cerr << "Failed to clear framebuffer." << std::endl;
		exit(1);
	}
	fb_clear_time = framebuffer.get_clear_exec_time();

	cl_int arg = i%STEPS;
	int32_t tile_size = best_tile_size;

	directional_light_cl light;
	light.set_dir(1.f,-1.f,0.f);
	light.set_color(1.f,1.f,1.f);
	// light.set_dir(0.05f * (arg - 8.f) , -0.6f, 0.2f);
	// light.set_color(0.05f * (fabsf(arg)) + 0.1f, 0.2f, 0.05f * fabsf(arg+4.f));

	Scene &scene = scenes[current_frame];

	scene.set_dir_light(light);
	color_cl ambient;
	ambient[0] = ambient[1] = ambient[2] = 0.1f;
	scene.set_ambient_light(ambient);

	int32_t sample_count = pixel_count * prim_ray_gen.get_spp();
	for (int32_t offset = 0; offset < sample_count; offset+= tile_size) {

		
		RayBundle* ray_in =  &ray_bundle_1;
		RayBundle* ray_out = &ray_bundle_2;

		if (sample_count - offset < tile_size)
			tile_size = sample_count - offset;

		if (prim_ray_gen.generate(camera, *ray_in, window_size,
                                          tile_size, offset)) {
			std::cerr << "Error seting primary ray bundle" << std::endl;
			exit(1);
		}
		prim_gen_time += prim_ray_gen.get_exec_time();

		total_ray_count += tile_size;

		if (tracer.trace(scene, tile_size, *ray_in, hit_bundle)){
		// if (tracer.trace(scene, bvh_mem, tile_size, *ray_in, hit_bundle)){
			std::cerr << "Failed to trace." << std::endl;
			exit(1);
		}
		prim_trace_time += tracer.get_trace_exec_time();

		if (tracer.shadow_trace(scene, tile_size, *ray_in, hit_bundle)){
		//if (tracer.shadow_trace(scene, bvh_mem, tile_size, *ray_in, hit_bundle)){
			std::cerr << "Failed to shadow trace." << std::endl;
			exit(1);
		}
		prim_shadow_trace_time += tracer.get_shadow_exec_time();

		if (ray_shader.shade(*ray_in, hit_bundle, scene,
                                     cubemap, framebuffer, tile_size, true)){
			std::cerr << "Failed to update framebuffer." << std::endl;
			exit(1);
		}
		shader_time += ray_shader.get_exec_time();

		size_t sec_ray_count = tile_size;
		for (uint32_t i = 0; i < MAX_BOUNCE; ++i) {

			sec_ray_gen.generate(scene, *ray_in, sec_ray_count, 
					     hit_bundle, *ray_out, &sec_ray_count);
			sec_gen_time += sec_ray_gen.get_exec_time();

			std::swap(ray_in,ray_out);

			if (!sec_ray_count)
				break;
			if (sec_ray_count == ray_bundle_1.count())
				std::cerr << "Max sec rays reached!\n";

			total_ray_count += sec_ray_count;

			// if (tracer.trace(scene, bvh_mem, sec_ray_count, 
			if (tracer.trace(scene, sec_ray_count, 
                                         *ray_in, hit_bundle, true)) {
                                std::cerr << "Failed to trace." << std::endl;
                                exit(1);
                        }
			sec_trace_time += tracer.get_trace_exec_time();


			// if (tracer.shadow_trace(scene, bvh_mem, sec_ray_count, 
			if (tracer.shadow_trace(scene, sec_ray_count, 
                                                *ray_in, hit_bundle, true)) {
                                std::cerr << "Failed to shadow trace." << std::endl;
                                exit(1);
                        }
			sec_shadow_trace_time += tracer.get_shadow_exec_time();

			if (ray_shader.shade(*ray_in, hit_bundle, scene,
                                             cubemap, framebuffer, sec_ray_count)){
				std::cerr << "Ray shader failed execution." << std::endl;
				exit(1);
			}
			shader_time += ray_shader.get_exec_time();
		}

	}

	if (framebuffer.copy(device.memory(tex_id))){
		std::cerr << "Failed to copy framebuffer." << std::endl;
		exit(1);
	}
	fb_copy_time = framebuffer.get_copy_exec_time();
	double total_msec = rt_time.msec_since_snap();

	if (min_time < 0)
		min_time = total_msec;
	else
		min_time = std::min(min_time,total_msec);

	if (max_time < 0)
		max_time = total_msec;
	else
		max_time = std::max(max_time,total_msec);

        if (device.release_graphic_resource(tex_id) ||
            cubemap.release_graphic_resources()) {
                std::cerr << "Error releasing texture resource." << std::endl;
                exit(1);
        }

        for (size_t i = 0; i < scenes.size(); ++i) {
                if (scenes[i].release_graphic_resources()) {
                        std::cerr << "Error releasing texture resource." << std::endl;
                        exit(1);
                }
        }

        ////////////////// Immediate mode textured quad
	glBindTexture(GL_TEXTURE_2D, gl_tex);

	glBegin(GL_TRIANGLE_STRIP);

	glTexCoord2f(1.0,1.0);
	glVertex2f(1.0,1.0);

	glTexCoord2f(1.0,0.0);
	glVertex2f(1.0,-1.0);

	glTexCoord2f(0.0,1.0);
	glVertex2f(-1.0,1.0);

	glTexCoord2f(0.0,0.0);
	glVertex2f(-1.0,-1.0);

	glEnd();
	////////////////////////////////////////////

	i += dir;
	if (!(i % (STEPS-1))){
		dir *= -1;
	}		
	std::cout << "Time elapsed: " 
		  << total_msec << " milliseconds " 
		  << "\t" 
		  << (1000.f / total_msec)
		  << " FPS"
		  << "\t"
		  << total_ray_count
		  << " rays casted "
		  << "\t(" << pixel_count << " primary, " 
		  << total_ray_count-pixel_count << " secondary)"
		  << "               \r" ;
	std::flush(std::cout);
	rt_time.snap_time();
	total_ray_count = 0;

	std::cout << "\nPrim Gen time: \t" << prim_gen_time  << std::endl;
	std::cout << "Sec Gen time: \t" << sec_gen_time << std::endl;
	std::cout << "Tracer time: \t" << prim_trace_time + sec_trace_time  
		  << " (" <<  prim_trace_time << " - " << sec_trace_time 
		  << ")" << std::endl;
	std::cout << "Shadow time: \t" << prim_shadow_trace_time + sec_shadow_trace_time 
		  << " (" <<  prim_shadow_trace_time 
		  << " - " << sec_shadow_trace_time << ")" << std::endl;
	std::cout << "Shader time: \t " << shader_time << std::endl;
	std::cout << "Fb clear time: \t" << fb_clear_time << std::endl;
	std::cout << "Fb copy time: \t" << fb_copy_time << std::endl;
	std::cout << std::endl;

	glutSwapBuffers();
	current_frame = (current_frame+motion_rate)%frames;
	if (current_frame == 0) {
		double t = seq_time.msec_since_snap();
		     
		std::cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << std::endl;
		std::cout << "Sequence stats:" << std::endl << std::endl;
		std::cout << "Frames: " << frames << std::endl;
		std::cout << "Sequence render time: " << t << "msec\t(" 
			  << frames*1000.f/t << " FPS)" <<   std::endl;
		std::cout << "Mean / Min / Max render time: " 
			  <<  t/frames << " / " 
			  <<  min_time << " / " 
			  <<  max_time << " msec" << std::endl;
		std::cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << std::endl;
		max_time = -1;
		min_time = -1;
		seq_time.snap_time();
	}

}
Exemple #24
0
 void
 TraceError(const wxString & message)
 {
   if (tracer)
     tracer->TraceError(message);
 }
Exemple #25
0
// this function is called to process every breakpoint entry, so it should be as fast as possible.
void normal_break (DEBUG_EVENT *db)
{
    t_disassembly dis;
    DWORD         address;
    HANDLE        process;
    HANDLE        thread;
    node          *bp_node;
    bool          stalking = false;
    DWORD         tick_count;
    CONTEXT       context;
    LDT_ENTRY     selector_entry;
    DWORD         fs_base;
    DWORD         stack_top;
    DWORD         stack_bottom;

    tick_count = GetTickCount();
    address    = (DWORD)(db->u.Exception.ExceptionRecord.ExceptionAddress);
    thread     = dbg.FindThread((DWORD)db->dwThreadId)->hThread;
    process    = dbg.getProcessHandle();

    // bring the called function to the top of the list.
    //function_list = splay(address, function_list);

    // ensure the breakpoint lies in a module we are stalking.
    for (node *cursor = bp_modules; cursor != NULL; cursor = cursor->next)
    {
        if (address >= cursor->base && address <= cursor->base + cursor->size)
        {
                stalking = true;
                break;
        }
    }

    // if we're not stalking the current module, return now.
    if (!stalking)
        return;

    //
    // if we're recording, log the entry to the appropriate recorder file.
    //

    if (recorder_mode != NOT_RECORDING)
    {
        //function_list->recorded[recorder_mode]++;
        //printf("T:%04x [R%d] %08X %-25s [%5u] ", db->dwThreadId, recorder_mode, address, function_list->name, function_list->recorded[recorder_mode]);

        if (disassemble_flag)
            printf("%08x T:%08x [R%d] %08X ", tick_count, db->dwThreadId, recorder_mode, address);

        if ((bp_node = ps_node_find_by_address(address, bp_modules)) != NULL)
            fprintf(recorder, "%08x:%08x:%s:%08x:%08x\n", tick_count, db->dwThreadId, bp_node->name, bp_node->base, address - bp_node->base);
    }
    // else, not recording.
    else
    {
        if (disassemble_flag)
            printf("%08x T:%08x [bp] %08X ", tick_count, db->dwThreadId, address);
    }

    // if enabled, print the disassembly at the breakpoint address.
    if (disassemble_flag)
    {
        // XXX - wonder if there is any significant speed increase when we skip just the disassembly output.
        if (dbg.Disassemble(thread, address, &dis))
            printf("%s\n", dis.mnemonic.c_str());
        else
            printf("\n");
    }

    // if we are recording and register enumeration / dereferencing is enabled, process the registers we are interested in.
    if (recorder_mode != NOT_RECORDING && reg_enum_flag)
    {
        context.ContextFlags = CONTEXT_FULL;

        // get the thread context (containing the register values).
        if (GetThreadContext(thread, &context) == 0)
            return;

        // get the thread selector entry and calculate the 32-bit address for the FS register.
        if (GetThreadSelectorEntry(thread, context.SegFs, &selector_entry) == 0)
            return;

        fs_base = selector_entry.BaseLow + (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24);
        
        // determine the top/bottom of the debuggee's stack.
        ReadProcessMemory(process, (void *)(fs_base + 4), &stack_top,    4, NULL);
        ReadProcessMemory(process, (void *)(fs_base + 8), &stack_bottom, 4, NULL);

        ps_analyze_register(process, tick_count, address, bp_node, stack_top, stack_bottom, context.Eax, "EAX");
        ps_analyze_register(process, tick_count, address, bp_node, stack_top, stack_bottom, context.Ebx, "EBX");
        ps_analyze_register(process, tick_count, address, bp_node, stack_top, stack_bottom, context.Ecx, "ECX");
        ps_analyze_register(process, tick_count, address, bp_node, stack_top, stack_bottom, context.Edx, "EDX");
        ps_analyze_register(process, tick_count, address, bp_node, stack_top, stack_bottom, context.Esi, "ESI");
        ps_analyze_register(process, tick_count, address, bp_node, stack_top, stack_bottom, context.Edi, "EDI");
    }

    // to restore the break point we just processed:
    //      - save the breakpoint address.
    //      - enable single stepping.
    //      - let the single step handler restore the breakpoint and disable single stepping.
    if (!dbg.one_time)
    {
        dbg.breakpoint_restore        = address;
        dbg.breakpoint_restore_thread = thread;
        dbg.SetSingleStep(thread, true);
    }
}
Exemple #26
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// callback functions
//
void initial_break (DEBUG_EVENT *db)
{
    char  line[256], module[128];
    DWORD f_offset, offset, base, size;
    int loaded = 0;
    node *bp_node;

    dbg.ActivateTraces();

    printf("initial break, tid = %04x.\n\n", dbg.FindThread( (DWORD)db->dwThreadId )->hThread);

    if (!dbg.get_thandle())
    {
        printf("manually setting thread handle.\n");
        dbg.set_thandle(dbg.FindThread( (DWORD)db->dwThreadId )->hThread);
    }

    // if an initial breakpoint list was provided, process it.
    if (bpl != NULL)
    {
        printf("loading breakpoints from %s\n", breakpoint_list);

        // process the breakpoint list line by line.
        for (int i = 0; fgets(line, sizeof(line), bpl) != NULL; i++)
        {
            // line format: module name:function offset:offset
            // ignore malformatted lines.
            if (sscanf(line, "%127[^:]:%08x:%08x", module, &f_offset, &offset) == 0)
                continue;
            
            // determine if this module already exists in our linked list.
            // if not attempt to locate the module in memory.
            if ((bp_node = ps_node_find_by_name(module, bp_modules)) == NULL)
            {
                // attempt to determine the module address / size.
                if (!ps_base_address(module, &base, &size))
                {
                    printf("failed locating base address for module %s\n", module);
                    continue;
                }

                // add a bp_node to the linked list.
                bp_node = (node *) malloc(sizeof(node));
                
                bp_node->base = base;
                bp_node->size = size;
                
                strncpy(bp_node->name, module, sizeof(bp_node->name) - 1);

                ps_node_add(bp_node, &bp_modules, &num_bp_modules);
            }

            // the '-25' means we want to reserve 25 left justified characters for the name.
            // the '.25' specifies that we want the string truncated after 25 characters.
            //printf("Setting breakpoint @%08x [%-25.25s] ... ", address, name);

            if (!dbg.bpx(bp_node->base + offset))
            {
                //printf("failed setting breakpoint @ 0x%08x\n", bp_node->base + offset);
                continue;
            }

            // at this point a breakpoint was successfully loaded.
            loaded++;

            if (i % 100 == 0)
                printf("setting breakpoint %d\r", i);

            // add function to splay tree.
            //if (offset == f_offset)
            //    function_list = splay_insert(address, name, function_list);
        }

        printf("done. %d of %d breakpoints set.\n", loaded, i);
        fclose(bpl);
    }
    // display the command menu.
    ps_commands();
}
Exemple #27
0
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// ps_load_dll_callback()
//
// callback function for when a new dll is loaded into the target process.
//
void ps_load_dll_callback (PEfile *pe)
{
    FILE *fp;
    char filename[MAX_PATH];
    char  line[256], module[128];
    DWORD f_offset, offset, base, size;
    int loaded = 0;
    node *bp_node;
    map <DWORD,t_Debugger_memory*>::const_iterator  it;

    strncpy(module, pe->internal_name.c_str(), sizeof(module) - 1);

    // determine if this module already exists in our linked list.
    // if not attempt to locate the module in memory.
    if ((bp_node = ps_node_find_by_name(module, bp_modules)) == NULL)
    {
        // attempt to determine the module address / size.
        if (!ps_base_address(module, &base, &size))
        {
            printf("failed locating base address for module %s\n", module);
            return;
        }
    }

    // if a breakpoint list exists for the recently loaded module then parse it and set breakpoints.
    _snprintf(filename, sizeof(filename) - 1, "%s.bpl", module);

    if ((fp = fopen(filename, "r+")) == NULL)
        return;

    // add the bp_node to the linked list.
    bp_node = (node *) malloc(sizeof(node));
    
    bp_node->base = base;
    bp_node->size = size;
    
    strncpy(bp_node->name, module, sizeof(bp_node->name) - 1);

    ps_node_add(bp_node, &bp_modules, &num_bp_modules);

    // pe->winpe->ImageBase + pe->section[0]->VirtualAddress == 'base' but that's only in situations where
    // the first section is the executable section. most dlls are simply imagebase+0x1000 but we don't want
    // to make either assumption.
    // XXX - there is definetely a more elegant way of determining 'base'.
    printf("processing breakpoints for module %s at %08x\n", module, base);

    // process the breakpoint list line by line.
    for (int i = 0; fgets(line, sizeof(line), fp) != NULL; i++)
    {
        // line format: module name:function offset:offset
        // ignore malformatted lines.
        if (sscanf(line, "%127[^:]:%08x:%08x", module, &f_offset, &offset) == 0)
            continue;

        if (!dbg.bpx(bp_node->base + offset))
        {
            //printf("failed setting breakpoint @ 0x%08x\n", base + offset);
            continue;
        }

        // at this point a breakpoint was successfully loaded.
        loaded++;

        if (i % 100 == 0)
            printf("setting breakpoint %d\r", i);
    }

    printf("done. %d of %d breakpoints set.\n\n", loaded, i);
    fclose(fp);

    return;
}
Exemple #28
0
void foo(Tracer t){
	Tracer trace("foo");
	t.show();
}
Exemple #29
0
Tracer bar(Tracer const &t){
	Tracer trace("bar");
	t.show();
	return trace;
}
Exemple #30
0
int main (int argc, char **argv)
{
    unsigned int cit;
    int          option;
    char         filename[MAX_PATH];
    char         command_line[MAX_PATH];            // win2k max = MAX_PATH, otherwise could be 32k.
    map <DWORD,t_Debugger_memory*>::const_iterator  it;

    // init target char buf.
    memset(target, 0, sizeof(target));

    // Set the debugger's log level. (disable logging)
    dbg.log.set(LOG_SHUTUP);
    dbg.SetGlobalLoglevel(LOG_SHUTUP);

    //
    // do the command line argument thing.
    //

    for (int i = 1; i < argc; i++)
    {
        //
        // attach to a pid.
        //

        if (stricmp(argv[i], "-a") == 0 && i + 1 < argc)
        {
            if (!dbg.attach(atoi(argv[i+1])))
            {
                printf("[ERROR] No process with the ID %u\n", atoi(argv[i+1]));
                return 1;
            }

            // update the target name.
            strncpy(target, argv[i+1], sizeof(target) - 1);

            i++;
        }

        //
        // load a file. (no arguments)
        //

        else if (stricmp(argv[i], "-l") == 0 && i + 1 < argc)
        {
            if (!dbg.load(argv[i+1]))
            {
                printf("[ERROR] Could not load %s\n", argv[i+1]);
                return 1;
            }

            // update the target name.
            strncpy(target, argv[i+1], sizeof(target) - 1);
            
            // cut off the target name at the first dot.
            //char *dot = strchr(target, '.');
            //*dot = 0;

            i++;
        }

        //
        // load a file with arguments.
        //

        else if (stricmp(argv[i], "-la") == 0 && i + 1 < argc)
        {
            _snprintf(command_line, sizeof(command_line), "%s %s", argv[i+1], argv[i+2]);

            if (!dbg.load(argv[i+1], command_line))
            {
                printf("[ERROR] Could not load %s %s\n", argv[i+1], argv[i+2]);
                return 1;
            }

            // update the target name.
            _snprintf(target, sizeof(target), command_line);

            i += 2;
        }

        //
        // select a breakpoint list.
        //

        else if (stricmp(argv[i], "-b") == 0 && i + 1 < argc)
        {
            breakpoint_list = argv[i+1];

            // we open the file now with a global file handle and set the breakpoints after all
            // the modules have been loaded and parsed in the initial breakpoint handler.
            if ((bpl = fopen(breakpoint_list, "r+")) == NULL)
            {
                printf("\n[ERROR] Failed opening breakpoing list: %s\n", breakpoint_list);
                return 1;
            }

            i++;
        }

        //
        // select a starting recorder mode.
        //

        else if (stricmp(argv[i], "-r") == 0 && *target != NULL && i + 1 < argc)
        {
            recorder_mode = atoi(argv[i+1]);

            // create / open recorder file.
            sprintf(filename, "%s.%d", target, recorder_mode);
            recorder = fopen(filename, "a+");

            // create / open the register recorder file if register enumeration hasn't been disabled.
            if (reg_enum_flag)
            {
                sprintf(filename, "%s-regs.%d", target, recorder_mode);
                recorder_regs = fopen(filename, "a+");
            }

            i++;
        }

        //
        // set "one-time" mode. ie: do not restore breakpoints.
        //

        else if (stricmp(argv[i], "--one-time") == 0)
        {
            dbg.one_time = true;
        }

        //
        // disable register enumeration / dereferencing.
        //

        else if (stricmp(argv[i], "--no-regs") == 0)
        {
            reg_enum_flag = false;
        }

        //
        // invalid option.
        //

        else
            ps_usage();
    }

    //
    // command line sanity checking.
    //

    if (*target == NULL)
        ps_usage();

    //
    // print banner and start working.
    //

    printf("\nprocess stalker\n"
           "pedram amini <*****@*****.**>\n"
           "compiled on "__DATE__"\n"
           "target: %s\n\n", target);

    // assign functions to handle breakpoints.
    dbg.set_inital_breakpoint_handler(&initial_break);
    dbg.set_breakpoint_handler(&normal_break);
    dbg.SetCloseRecordFunction(&closer);
    dbg.set_load_dll_handler(&ps_load_dll_callback);

    // assign a function to handle exit event.
    dbg.set_exit_handler(&itsdone);

    dbg.Analysis.StackDelta  = true;
    dbg.Analysis.StackDeltaV = 2048;

    // 
    // application main loop.
    //

    while (!main_terminate)
    {
        dbg.run(1000);

        for (cit = 0; cit < Children.size(); cit++)
                Children[cit]->run(1000);

        if (_kbhit())
        {
            option = getch();

            switch(option)
            {
                // activate a recorder.
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    // convert character option into integer option for recorder mode.
                    option -= 48;
                    
                    // close any previously open recorder file.
                    if (recorder_mode != NOT_RECORDING)
                    {
                        fclose(recorder);

                        if (reg_enum_flag)
                            fclose(recorder_regs);
                    }

                    printf("entering recorder mode %d, register enumeration is %s.\n", option, (reg_enum_flag ? "enabled" : "disabled"));
                    recorder_mode = option;

                    // create/open recorder file.
                    sprintf(filename, "%s.%d", target, option);
                    recorder = fopen(filename, "a+");

                    // create/open the register recording file if the register enumeration flag is raised.
                    if (reg_enum_flag)
                    {
                        sprintf(filename, "%s-regs.%d", target, option);
                        recorder_regs = fopen(filename, "a+");
                    }
                    break;

                // detach from debuggee.
                case 'd':
                    if (!dbg.pDebugActiveProcessStop || !dbg.pDebugSetProcessKillOnExit)
                    {
                        printf("\ndetaching is not possible on the current os ... request ignored.\n");
                        break;
                    }

                    main_terminate = true;
                    printf("\nclosing any open recorder and detaching ...\n");

                    if (recorder_mode != NOT_RECORDING)
                    {
                        fclose(recorder);

                        if (reg_enum_flag)
                            fclose(recorder_regs);
                    }

                    dbg.detach();

                    break;

                // display available options.
                case 'h':
                    ps_commands();
                    break;
                
                // display memory map for executable sections of each module.
                case 'm':
                    dbg.ReBuildMemoryMap();

                    printf("\n---------- MODULE LIST ----------\n");

                    for (it = dbg.MemoryMap.begin(); it != dbg.MemoryMap.end(); ++it)
                    {
                        // determine the correct section)
                        if ((it->second->basics.Protect & PAGE_EXECUTE)           ||
                            (it->second->basics.Protect & PAGE_EXECUTE_READ)      ||
                            (it->second->basics.Protect & PAGE_EXECUTE_READWRITE) ||
                            (it->second->basics.Protect & PAGE_EXECUTE_WRITECOPY))
                        {
                            // module executable section found.
                            printf("module %08x %s\n", it->second->address, it->second->Name.c_str());
                        }
                    }

                    printf("\nstalking:\n");

                    for (node *cursor = bp_modules; cursor != NULL; cursor = cursor->next)
                        printf("%08x - %08x [%08x] %s\n", cursor->base, cursor->base + cursor->size, cursor->size, cursor->name);

                    printf("---------- MODULE LIST ----------\n\n");

                    break;

                // quit program.
                case 'q':   
                    main_terminate = true;
                    printf("\nclosing any open recorder and quiting ...\n");

                    if (recorder_mode != NOT_RECORDING)
                    {
                        fclose(recorder);

                        if (reg_enum_flag)
                            fclose(recorder_regs);
                    }

                    break;
                
                // toggle verbosity. ie: display per breakpoint disassembly.
                case 'v':
                    disassemble_flag = !disassemble_flag;

                    printf("turning breakpoint disassembly: %s\n", (disassemble_flag) ? "ON" : "OFF");
                    break;

                // close active recorder mode.
                case 'x':
                    if (recorder_mode == NOT_RECORDING)
                        break;
                    
                    fclose(recorder);

                    if (reg_enum_flag)
                        fclose(recorder_regs);

                    printf("closing recorder mode %d\n", recorder_mode);
                    recorder_mode = NOT_RECORDING;
                    break;
                
                default:
                    ps_commands();
            }   // switch
        }       // _kbhit
    }           // while

    // Debugger class will handle it's own cleanup.
    // XXX - we don't free the bp_module list.
    return 0;
};