Example #1
0
void
CallManager::placeCallFirstAccount (const std::string& callID,
                                    const std::string& to)
{

    if (to == "") {
        _warn ("CallManager: Warning: No number entered, call stopped");
        return;
    }

    std::vector< std::string > accountOrder = Manager::instance().loadAccountOrder();
    std::vector< std::string >::iterator iter;

    Account *account;

    _debug ("AccountOrder size: %d", accountOrder.size());

    if (accountOrder.size() > 0) {

        iter = accountOrder.begin();

        while (iter != accountOrder.end()) {
            account = Manager::instance().getAccount (*iter);

            if ( (*iter != IP2IP_PROFILE) && account->isEnabled()) {
                Manager::instance().outgoingCall (*iter, callID, to);
                return;
            }

            iter++;
        }
    } else {
        _error ("AccountOrder is empty");
        // If accountOrder is empty fallback on accountList (which has no preference order)
        std::vector< std::string > accountList = Manager::instance().getAccountList();
        iter = accountList.begin();


        _error ("AccountList size: %d", accountList.size());

        if (accountList.size() > 0) {
            while (iter != accountList.end()) {
                _error ("iter");
                account = Manager::instance().getAccount (*iter);

                if ( (*iter != IP2IP_PROFILE) && account->isEnabled()) {
                    _error ("makecall");
                    Manager::instance().outgoingCall (*iter, callID, to);
                    return;
                }

                iter++;
            }

        }
    }

    _warn ("CallManager: Warning: No enabled account found, call stopped");

}
Example #2
0
static void up_calibratedelay(void)
{
  int i;

  _warn("Beginning 100s delay\n");
  for (i = 0; i < 100; i++)
    {
      up_mdelay(1000);
    }

  _warn("End 100s delay\n");
}
void set_random_seed_for_testing(const fc::sha512& new_seed)
{
    _warn();
    RAND_set_rand_method(&deterministic_rand_vtable);
    seed = new_seed;
    return;
}
Example #4
0
void c_rpc_server::rpc_start(bool network_listen, const std::string &listen_address, const unsigned short port) {
	if (network_listen) {
		// start waiting for new connection
		_note("Starting RPC server listening on address="<<listen_address<<" port="<<port);
		m_acceptor.async_accept(m_socket, [this](boost::system::error_code error) {
			this->accept_handler(error);
		});
	}
	else _warn("RPC server started, but not listening on network");

	_fact("Starting RPC thread");
	m_thread = std::thread([this]() {
		dbg("RPC thread start (inside)");
		try {
			boost::system::error_code ec;
			dbg("io_service run");
			m_io_service.run(ec);
			dbg("end of io_service run");
			if (ec) {
				dbg("error code " << ec.message());
			}
			dbg("io_service reset");
			m_io_service.reset();
		} catch (const std::exception &e) {
			dbg("io_service exception" << e.what());
		} catch (...) {
			dbg("catch unhandled exception");
		}

		dbg("RPC thread stop");
	}); // lambda
}
Example #5
0
static void
_warn2(struct request *r, char *msg1, char *msg2)
{
	char buf[MSG_SIZE];

	_warn(r, log_strcpy2(buf, sizeof buf, msg1, msg2));
}
Example #6
0
void
svc_run()
{
	fd_set readfds, cleanfds;
	struct timeval timeout;

	timeout.tv_sec = 30;
	timeout.tv_usec = 0;

	for (;;) {
		rwlock_rdlock(&svc_fd_lock);
		readfds = svc_fdset;
		cleanfds = svc_fdset;
		rwlock_unlock(&svc_fd_lock);
		switch (_select(svc_maxfd+1, &readfds, NULL, NULL, &timeout)) {
		case -1:
			FD_ZERO(&readfds);
			if (errno == EINTR) {
				continue;
			}
			_warn("svc_run: - select failed");
			return;
		case 0:
			__svc_clean_idle(&cleanfds, 30, FALSE);
			continue;
		default:
			svc_getreqset(&readfds);
		}
	}
}
Example #7
0
void AudioRecord::recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2 UNUSED)
{

    if (recordingEnabled_) {

        _debug ("Recording enabled");

        if (fp == 0) {
            _debug ("AudioRecord: Can't record data, a file has not yet been opened!");
            return;
        }


        if (sndFormat_ == INT16) {   // TODO change INT16 to SINT16
            for (int k=0; k<nSamples_1; k++) {

                mixBuffer_[k] = (buffer_1[k]+buffer_2[k]);


                if (fwrite (&mixBuffer_[k], 2, 1, fp) != 1)
                    _warn ("AudioRecord: Could not record data!");
                else {
                    fflush (fp);
                }
            }
        }

        byteCounter_ += (unsigned long) (nSamples_1*sizeof (SFLDataFormat));

    }

    return;
}
Example #8
0
void c_rpc_server::c_session::read_handler_hmac(const boost::system::error_code &error, std::size_t bytes_transferred) {
	_dbg("readed " << bytes_transferred << " bytes of hmac authenticator");
	_dbg("authenticate message");
	if (error) {
		_dbg("asio error " << error.message());
		delete_me();
		return;
	}
	int ret = crypto_auth_hmacsha512_verify(m_hmac_authenticator.data(),
	                                        reinterpret_cast<const unsigned char *>(m_received_data.data()),
	                                        m_received_data.size(),
	                                        m_hmac_key.data()
	);
	if (ret == -1) {
		_warn("hmac authentication error");
		delete_me();
		return;
	}
	assert(ret == 0);
	try {
		execute_rpc_command(m_received_data);
	} catch (const std::exception &e) {
		_erro( "exception read_handler " << e.what());
		_erro( "close connection\n" );
		delete_me();
		return;
	}
}
Example #9
0
bool AudioRecord::openExistingRawFile()
{
    fp = fopen (fileName_, "ab+");

    if (!fp) {
        _warn ("AudioRecord: could not create RAW file!");
        return false;
    }

    return true;
}
Example #10
0
void AudioRecord::closeWavFile()
{
    if (fp == 0) {
        _debug ("AudioRecord: Can't closeWavFile, a file has not yet been opened!");
        return;
    }

    _debug ("AudioRecord: Close wave file");


    SINT32 bytes = byteCounter_ * channels_;

    fseek (fp, 40, SEEK_SET); // jump to data length

    if (ferror (fp))
        _warn ("AudioRecord: Error: can't reach offset 40 while closing");

    fwrite (&bytes, sizeof (SINT32), 1, fp);

    if (ferror (fp))
        _warn ("AudioRecord: Error: can't write bytes for data length ");


    bytes = byteCounter_ * channels_ + 44; // + 44 for the wave header

    fseek (fp, 4, SEEK_SET); // jump to file size

    if (ferror (fp))
        _warn ("AudioRecord: Error: can't reach offset 4");

    fwrite (&bytes, 4, 1, fp);

    if (ferror (fp))
        _warn ("AudioRecord: Error: can't reach offset 4");


    if (fclose (fp) != 0)
        _warn ("AudioRecord: Error: can't close file");


}
void network_throttle::logger_handle_net(const std::string &filename, double time, size_t size) {
    boost::mutex mutex;
    mutex.lock(); {
        std::fstream file;
        file.open(filename.c_str(), std::ios::app | std::ios::out );
        file.precision(6);
        if(!file.is_open())
            _warn("Can't open file " << filename);
        file << static_cast<int>(time) << " " << static_cast<double>(size/1024) << "\n";
        file.close();
    }  mutex.unlock();
}
Example #12
0
bool AudioRecord::setWavFile()
{
    _debug ("AudioRecord: Create new wave file %s, sampling rate: %d", savePath_.c_str(), sndSmplRate_);

    fp = fopen (savePath_.c_str(), "wb");

    if (!fp) {
        _warn ("AudioRecord: Error: could not create WAV file.");
        return false;
    }

    struct wavhdr hdr = {"RIF", 44, "WAV", "fmt", 16, 1, 1,
        sndSmplRate_, 0, 2, 16, "dat", 0
    };

    hdr.riff[3] = 'F';
    hdr.wave[3] = 'E';
    hdr.fmt[3]  = ' ';
    hdr.data[3] = 'a';

    hdr.num_chans = channels_;

    if (sndFormat_ == INT16) {   //  TODO need to write INT16 to SINT16
        hdr.bits_per_samp = 16;
    }

    hdr.bytes_per_samp = (SINT16) (channels_ * hdr.bits_per_samp / 8);

    hdr.bytes_per_sec = (SINT32) (hdr.sample_rate * hdr.bytes_per_samp);


    if (fwrite (&hdr, 4, 11, fp) != 11) {
        _warn ("AudioRecord: Error: could not write WAV header for file. ");
        return false;
    }

    _debug ("AudioRecord: created WAV file successfully.");

    return true;
}
c_tuntap_linux_obj::c_tuntap_linux_obj() :
	m_tun_fd(open("/dev/net/tun", O_RDWR)),
	m_io_service(),
	m_tun_stream(m_io_service, m_tun_fd)
{
	_fact("tuntap opened with m_tun_fd=" << m_tun_fd);
	_try_sys(m_tun_fd != -1);
	_check_sys(m_tun_stream.is_open());
	try {
		//set_sockopt_timeout( m_tun_stream.native_handle() , sockopt_timeout_get_default() );
	} catch(const std::exception &ex) { _warn("Can not set timtout for tuntap: " << ex.what()); }
	_goal("tuntap is opened correctly");
}
static int  deterministic_rand_bytes(unsigned char *buf, int num)
{
  _warn();
  while (num)
  {
    seed = fc::sha512::hash(seed);

    int bytes_to_copy = std::min<int>(num, sizeof(seed));
    memcpy(buf, &seed, bytes_to_copy);
    num -= bytes_to_copy;
    buf += bytes_to_copy;
  }
  return 1;
}
Example #15
0
// Fired after all test activities have ended.
void TestsEnvReseter::OnTestProgramEnd(const ::testing::UnitTest& unit_test) {
	_UNUSED(unit_test);
	g_dbg_level_set(40, "Show again some debug after the tests");

	auto skipped = instance().m_count_tests_skipped;
	if (skipped>0) {
		std::cout << banner_skip() << " Tests skipped: " << skipped
		<< "." << std::endl;
		_warn("Skipped some tests.");
	}
	else std::cout << "(No tests were skipped, this is good)" << std::endl;

	std::cout << std::endl;
}
Example #16
0
bool wrap_thread::try_join(std::chrono::duration<double> duration) {
	std::chrono::seconds dest_time = std::chrono::duration_cast<std::chrono::seconds>(duration);

	if(!m_future.valid())
		return true;

	std::future_status status = m_future.wait_for(dest_time);
	if (status != std::future_status::ready) {
		_warn("try_join: can not end thread in given time");
		return true;
	} else {
		m_time_stopped = t_sysclock::now();
		_info("Successfully joined wrap_thread");
		m_future.get();
		return false;
	}
	return true;
}
Example #17
0
bool AudioRecord::setRawFile()
{

    fp = fopen (savePath_.c_str(), "wb");

    if (!fp) {
        _warn ("AudioRecord: Could not create RAW file!");
        return false;
    }

    if (sndFormat_ != INT16) {   // TODO need to change INT16 to SINT16
        sndFormat_ = INT16;
        _debug ("AudioRecord::setRawFile() : using 16-bit signed integer data format for file.");
    }

    _debug ("AudioRecord:setRawFile() : created RAW file.");

    return true;
}
Example #18
0
void c_the_program::options_parse_first() {
	_goal("Will parse commandline, got args count: " << argt.size() << " and exec="<<argt_exec );
	for (const auto & str : argt)
	{
		_fact("commandline option: " << str << " ;");
		if (str.size() == 0) _warn("Empty commandline arg");
	}
	_check(m_boostPO_desc);
	namespace po = boost::program_options;

	// back to argc/argv, so that boost::program_options can parse it
	c_string_string_Cstyle args_cstyle( argt_exec , argt );
	const int argc = args_cstyle.get_argc();
	const char ** argv = args_cstyle.get_argv();

	po::store(po::parse_command_line(argc, argv, *m_boostPO_desc) , m_argm); // *** parse commandline, and store result
	_dbg1( "Parsing with options: " << *m_boostPO_desc );
	_goal("BoostPO parsed argm size=" << m_argm.size());
	for(auto &arg: m_argm) _info("Argument in argm: " << arg.first );
}
Example #19
0
bool AudioRecord::openExistingWavFile()
{
    _info ("%s(%s)\n", __PRETTY_FUNCTION__, fileName_);

    fp = fopen (fileName_, "rb+");

    if (!fp) {
        _warn ("AudioRecord: Error: could not open WAV file!");
        return false;
    }

    if (fseek (fp, 40, SEEK_SET) != 0) // jump to data length
        _warn ("AudioRecord: Error: Couldn't seek offset 40 in the file ");

    if (fread (&byteCounter_, 4, 1, fp))
        _warn ("AudioRecord: Error: bytecounter Read successfully ");

    if (fseek (fp, 0 , SEEK_END) != 0)
        _warn ("AudioRecord: Error: Couldn't seek at the en of the file ");


    if (fclose (fp) != 0)
        _warn ("AudioRecord: Error: Can't close file r+ ");



    fp = fopen (fileName_, "ab+");

    if (!fp) {
        _warn ("AudioRecord: Error: Could not createopen WAV file ab+!");
        return false;
    }

    if (fseek (fp, 4 , SEEK_END) != 0)
        _warn ("AudioRecord: Error: Couldn't seek at the en of the file ");

    return true;

}
Example #20
0
void AudioRecord::recData (SFLDataFormat* buffer, int nSamples)
{

    if (recordingEnabled_) {

        if (fp == 0) {
            _debug ("AudioRecord: Can't record data, a file has not yet been opened!");
            return;
        }



        if (sndFormat_ == INT16) {   // TODO change INT16 to SINT16
            if (fwrite (buffer, sizeof (SFLDataFormat), nSamples, fp) != (unsigned int) nSamples)
                _warn ("AudioRecord: Could not record data! ");
            else {
                fflush (fp);
                byteCounter_ += (unsigned long) (nSamples*sizeof (SFLDataFormat));
            }
        }
    }

    return;
}
Example #21
0
void __start(void)
{
  const uint32_t *src;
  uint32_t *dest;

  /* Disable the watchdog timer */

  kinetis_wddisable();

  /* Clear .bss.  We'll do this inline (vs. calling memset) just to be
   * certain that there are no issues with the state of global variables.
   */

  for (dest = &_sbss; dest < &_ebss; )
    {
      *dest++ = 0;
    }

  /* Move the initialized data section from his temporary holding spot in
   * FLASH into the correct place in SRAM.  The correct place in SRAM is
   * give by _sdata and _edata.  The temporary location is in FLASH at the
   * end of all of the other read-only data (.text, .rodata) at _eronly.
   */

  for (src = &_eronly, dest = &_sdata; dest < &_edata; )
    {
      *dest++ = *src++;
    }

  /* Copy any necessary code sections from FLASH to RAM.  The correct
   * destination in SRAM is given by _sramfuncs and _eramfuncs.  The
   * temporary location is in flash after the data initialization code
   * at _framfuncs
   */

#ifdef CONFIG_ARCH_RAMFUNCS
  for (src = &_framfuncs, dest = &_sramfuncs; dest < &_eramfuncs; )
    {
      *dest++ = *src++;
    }
#endif

  /* Perform clock and Kinetis module initialization (This depends on
   * RAM functions having been copied to RAM).
   */

  kinetis_clockconfig();

  /* Configure the uart and perform early serial initialization so that we
   * can get debug output as soon as possible (This depends on clock
   * configuration).
   */

  kinetis_lowsetup();
#ifdef USE_EARLYSERIALINIT
  up_earlyserialinit();
#endif

  /* For the case of the separate user-/kernel-space build, perform whatever
   * platform specific initialization of the user memory is required.
   * Normally this just means initializing the user space .data and .bss
   * segments.
   */

#ifdef CONFIG_BUILD_PROTECTED
  kinetis_userspace();
#endif

  /* Initialize other on-board resources */

  kinetis_boardinitialize();

  /* Show reset status */

  _warn("Reset status: %02x:%02x\n",
        getreg8(KINETIS_SMC_SRSH), getreg8(KINETIS_SMC_SRSL));

  /* Then start NuttX */

  os_start();

  /* Shouldn't get here */

  for (; ; );
}
Example #22
0
static void _umount (const char *target) {
	if (umount2(target, MNT_DETACH) < 0) {
		_warn("forced unmount of %s", target);
		umount2(target, MNT_FORCE);
	}
}
// These don't need to do anything if you don't have anything for them to do.
static void deterministic_rand_cleanup() { _warn(); }
static void deterministic_rand_add(const void *buf, int num, double add_entropy) { _warn(); }
static int  deterministic_rand_status() { _warn(); return 1; }
static void deterministic_rand_seed(const void *buf, int num) { _warn(); }
Example #27
0
std::wstring c_tun_device_windows::get_device_guid() {
	const std::wstring adapterKey = L"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}";
	_fact("Looking for device guid" << to_string(adapterKey));
	LONG status = 1;
	HKEY key = nullptr;
	status = RegOpenKeyExW(HKEY_LOCAL_MACHINE, adapterKey.c_str(), 0, KEY_READ, &key);
	if (status != ERROR_SUCCESS) throw std::runtime_error("RegOpenKeyEx error, error code " + std::to_string(status));
	hkey_wrapper key_wrapped(key);
	std::vector<std::wstring> subkeys_vector;
	try {
		subkeys_vector = get_subkeys(key_wrapped.get());
	} catch (const std::exception &e) {
		key_wrapped.close();
		throw e;
	}
	_dbg1("found " << subkeys_vector.size() << " reg keys");
	key_wrapped.close();
	for (const auto & subkey : subkeys_vector) { // foreach sub key
		if (subkey == L"Properties") continue;
		std::wstring subkey_reg_path = adapterKey + L"\\" + subkey;
		_fact(to_string(subkey_reg_path));
		status = RegOpenKeyExW(HKEY_LOCAL_MACHINE, subkey_reg_path.c_str(), 0, KEY_QUERY_VALUE, &key);
		if (status != ERROR_SUCCESS) throw std::runtime_error("RegOpenKeyEx error, error code " + std::to_string(status));
		// get ComponentId field
		DWORD size = 256;
		std::wstring componentId(size, '\0');
		 // this reinterpret_cast is not UB(3.10.10) because LPBYTE == unsigned char *
		 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx
		status = RegQueryValueExW(key, L"ComponentId", nullptr, nullptr, reinterpret_cast<LPBYTE>(&componentId[0]), &size);
		if (status != ERROR_SUCCESS) {
			RegCloseKey(key);
			continue;
		}
		key_wrapped.set(key);
		std::wstring netCfgInstanceId;
		try {
			if (componentId.substr(0, 8) == L"root\\tap" || componentId.substr(0, 3) == L"tap") { // found TAP
				_note(to_string(subkey_reg_path));
				size = 256;
				netCfgInstanceId.resize(size, '\0');
				// this reinterpret_cast is not UB(3.10.10) because LPBYTE == unsigned char *
				// https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx
				status = RegQueryValueExW(key_wrapped.get(), L"NetCfgInstanceId", nullptr, nullptr, reinterpret_cast<LPBYTE>(&netCfgInstanceId[0]), &size);
				if (status != ERROR_SUCCESS) throw std::runtime_error("RegQueryValueEx error, error code " + std::to_string(GetLastError()));
				netCfgInstanceId.erase(size / sizeof(wchar_t) - 1); // remove '\0'
				_note(to_string(netCfgInstanceId));
				key_wrapped.close();
				HANDLE handle = open_tun_device(netCfgInstanceId);
				if (handle == INVALID_HANDLE_VALUE) continue;
				else {
					BOOL ret = CloseHandle(handle);
					if (ret == 0) throw std::runtime_error("CloseHandle error, " + std::to_string(GetLastError()));
				}
				return netCfgInstanceId;
			}
		} catch (const std::out_of_range &e) {
			_warn(std::string("register value processing error ") + e.what());
			_note("componentId = " + to_string(componentId));
			_note("netCfgInstanceId " + to_string(netCfgInstanceId));
		}
		key_wrapped.close();
	}
	_erro("Can not find device in windows registry");
	throw std::runtime_error("Device not found");
}
Example #28
0
void c_simulation::main_loop () {
	//	PALETTE palette;
	//BITMAP *img_bgr = load_bitmap("dat/bgr-bright.tga", NULL); // TODO:
    s_font_allegl.reset (allegro_gl_convert_allegro_font(font,AGL_FONT_TYPE_TEXTURED,500.0), [](FONT *f){allegro_gl_destroy_font(f);});

    for(auto &obj : m_world->m_objects) {
        obj->set_font(s_font_allegl);
    }
	int viewport_x = 0, viewport_y = 0;

	//show_mouse(m_screen);

	set_close_button_callback(c_close_button_handler);

	bool print_connect_line = false;
	bool start_simulation = false;
	bool simulation_pause = true;
	shared_ptr<c_cjddev> connect_node;
	std::chrono::steady_clock::time_point last_click_time =
		std::chrono::steady_clock::now() - std::chrono::milliseconds(1000);

	m_gui = make_shared<c_gui>();


	// prepare drawtarget surface to draw to
	switch (m_drawtarget_type) {
		case e_drawtarget_type_allegro:
			m_drawtarget = make_shared<c_drawtarget_allegro>(m_frame); 
		break;
		case e_drawtarget_type_opengl:
			m_drawtarget = make_shared<c_drawtarget_opengl>(); 
		break;
		default:
			_erro("Warning: unsupported drawtarget");
	}

	m_drawtarget->m_gui = m_gui;



	//	bool allegro_keys_any_was=false; // is any key pressed right now (for key press/release)
	long loop_miliseconds = 0;
	long unsigned int frame_checkpoint = 0; /// needed for speed control (without world_draw manipulate in spacetime!)
	_UNUSED(frame_checkpoint);

	bool use_input_allegro = true; // always for now.  input from Allegro
	bool use_draw_allegro = m_drawtarget_type == e_drawtarget_type_allegro; // draw in allegro
	bool use_draw_opengl = m_drawtarget_type == e_drawtarget_type_opengl; // draw in opengl


	_note("Entering main simulation loop");

	// The main drawing is done inside this loop.
	
	///@see rendering.txt/[[drawing_main]]
    float view_angle = 0.0;
    //float camera_offset = 1.0;

    float zoom = 1.0;
    float camera_step_z=-11.0;
    // === main loop ===
    while (!m_goodbye && !close_button_pressed) {

		auto start_time = std::chrono::high_resolution_clock::now();

		// --- process the keyboard/inputs ---
		if (use_input_allegro) {
				// TODO move this code here, but leave the variables in higher scope
		}

			poll_keyboard();
			auto allegro_keys = key;
			auto allegro_shifts = key_shifts;
			//		bool allegro_keys_any_is=false;
			//		for (size_t i=0; i<sizeof(allegro_keys)/sizeof(allegro_keys[0]); ++i) allegro_keys_any_is=true;
			// the direct raw position
			const int allegro_mouse_x = mouse_x;
			const int allegro_mouse_y = mouse_y;
			const int allegro_mouse_b = mouse_b; // buttons

			// the position in display port GUI
			const int gui_mouse_x = allegro_mouse_x; 
			const int gui_mouse_y = allegro_mouse_y;
			const int gui_mouse_b = allegro_mouse_b; // buttons
			
			// the position in the world coordinates
			const int gui_cursor_x = m_gui->view_x_rev(gui_mouse_x);
			const int gui_cursor_y = m_gui->view_y_rev(gui_mouse_y);
			const int gui_cursor_z = 0; // m_gui->view_z_rev(gui_mouse_z);
			
			_UNUSED(gui_mouse_b);
			_UNUSED(gui_cursor_x);
			_UNUSED(gui_cursor_y);
			_UNUSED(gui_cursor_z);

            //_dbg1("mouse_x mouse_y: " << gui_mouse_x << " " << gui_mouse_y);

			int allegro_char = 0;
			if (keypressed()) {
				allegro_char = readkey();
			}
		// end of input

		// draw background of frame
		if (use_draw_allegro) {
			clear_to_color(m_frame, makecol(0, 128, 0));
            blit(c_bitmaps::get_instance().m_background, m_frame, 0, 0, viewport_x, viewport_y, c_bitmaps::get_instance().m_background->w, c_bitmaps::get_instance().m_background->h);
		}
        if (use_draw_opengl) {
            glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
            //glDisable(GL_DEPTH_TEST);      // ??? Enables Depth Testing
            //glEnable(GL_DEPTH_TEST);
            //glDepthFunc(GL_LEQUAL);                         // The Type Of Depth Testing To Do
            //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
             //glLoadIdentity();
            // glTranslatef(m_gui->camera_x, m_gui->camera_y,camera_offset);

            // minimum and maximum value for zoom in/out and rotate the scene
//            if (camera_offset >= 10.0) camera_offset = 10.0;
//            if (camera_offset <= 0.5) camera_offset = 0.5;
            if (view_angle >= 70) view_angle = 70;
            if(view_angle <= 0) view_angle = 0;

            if( zoom <= 0.1 ) zoom = 0.1;  //because of glFrustum -> when left=right, or bottom=top there's error GL_INVALID_VALUE, so we can't multiply e.g left,right by 0

            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glFrustum(-1.0*zoom, 1.0*zoom, -1.0*zoom, 1.0*zoom, 1.0,60.0);
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();

            //glTranslatef(0.0f,0.0f,-11.0);
            glTranslatef(0.0f,0.0f,camera_step_z);
            glRotatef(-view_angle, 1,0,0);
            glScalef(10,10,10);

            // drawing backgound
            glPushMatrix();
            //glScalef(1,1,1);
            glBindTexture(GL_TEXTURE_2D,c_bitmaps::get_instance().m_background_opengl);
            glEnable(GL_BLEND);
            //float q=1.0/zoom;
            float q=1.0;
            glBegin(GL_QUADS);
                glTexCoord2f(0,q); glVertex3f(-1.0f,1.0f, 0.0f);
                glTexCoord2f(q,q); glVertex3f(1.0f,1.0f, 0.0f);
                glTexCoord2f(q,0); glVertex3f(1.0f,-1.0f,0.0f);
                glTexCoord2f(0,0); glVertex3f(-1.0f,-1.0f,0.0f);
            glEnd();
            glDisable(GL_BLEND);
            glBindTexture(GL_TEXTURE_2D, 0);   // texture
            glPopMatrix();
		}
		
		// clear additional things
		if (use_draw_allegro) {
			clear_to_color(smallWindow, makecol(128, 128, 128));
		}

		// main controll keys
		if (allegro_keys[KEY_ESC]) {
			_note("User exits the simulation from user interface");
			m_goodbye = true;
		}

		if ((allegro_char & 0xff) == 'n' && !start_simulation) {
			std::cout << "ADD " << std::endl;
			_warn("THIS CODE IS NOT IMPLEMENTED NOW");
			/*
			m_world->m_objects.push_back(
				make_shared<c_cjddev>(
					cjddev_detail_random_name(), 
					// gui_mouse_x, gui_mouse_y,
					gui_cursor_x, gui_cursor_y,
					cjddev_detail_random_addr()));
					*/
		}

        if(allegro_keys[KEY_F1]){
            //auto ptr = get_move_object(gui_mouse_x,gui_mouse_y);


						//  TODO  -in allegro?   -not entire screen?    
						/*
            try{
                if(ptr != NULL){
                    int col_num =0;
                    textout_ex(smallWindow, font, ptr->get_name().c_str(), 0, 0, makecol(0, 0, 255), -1);

                        if(c_cjddev* tmp = dynamic_cast<c_cjddev *>(ptr.get()) ){
                            char* addr =(char *) malloc(45);
                             sprintf(addr,"address: %ld",tmp->get_address());
                             textout_ex(smallWindow, font,addr , 10, col_num+=10, makecol(0, 0, 255), -1);
                             sprintf(addr,"neighbors: %d",(int)tmp->get_neighbors().size());
                             textout_ex(smallWindow, font,addr , 10, col_num+=10, makecol(0, 0, 255), -1);
                             sprintf(addr,"waitng: %d",(int)tmp->num_of_wating());
                             textout_ex(smallWindow, font,addr , 10, col_num+=10, makecol(0, 0, 255), -1);

//                    		textout_ex(smallWindow, font, ptr->get_name().c_str(), 0, 0, makecol(0, 0, 255), -1);{
                            free (addr);
                        }

												if (use_draw_allegro) { 
													// draw the information window
                        	blit (smallWindow,m_frame,0,0,m_frame->w-200,m_frame->h-200,screen->w/8, screen->h/4);
												}

                    }
            }
						catch(...) {}
						*/

//            std::cout<<ptr->get_name().c_str()<<std::endl;
        }
				

        if(allegro_keys[KEY_F2]){
//            BITMAP* screen = gui_get_screen();
          int m_x =0;
          int m_y =0;
          static unsigned int num =0;
            if(num>=m_world->m_objects.size()){
                num=0;
            }
           try{

//                auto obj = m_world->m_objects.at(0);
//                m_x = m_world->m_objects.at(num)->get_x() - (screen->w/2);
//                m_y = m_world->m_objects.at(num)->get_y() - (screen->h/2);
                  m_x =  m_world->m_objects.at(num)->get_x()*m_gui->camera_zoom - (allegro_mouse_x);
                  m_y =  m_world->m_objects.at(num)->get_y()*m_gui->camera_zoom - (allegro_mouse_y);


                //    std::cout<< screen->w<<" "<<screen->h<<" "<<screen->x_ofs<<" "<<screen->y_ofs<<std::endl;

                    m_gui->camera_x = m_x ;
                    m_gui->camera_y = m_y;


                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                    num++;
            }catch(...)
            {

            }

        }


		// animation & tick
		if (m_frame_number % g_max_anim_frame == 0 && !simulation_pause) {
			frame_checkpoint = m_frame_number;
			m_world->tick(); // <===
		}


		// === main user interface ===

		// the mode
		typedef enum { e_mode_node, e_mode_camera } t_mode;
		t_mode mode;
		mode = e_mode_node; // by default we will move/edit etc the node (or entityt)
		if (allegro_shifts & KB_SHIFT_FLAG) mode = e_mode_camera; // with key SHIFT we move camera instea

		// mode: camera movement etc
		if (mode == e_mode_camera) {
			if (allegro_keys[KEY_LEFT]) m_gui->camera_x -= 10;
			if (allegro_keys[KEY_RIGHT]) m_gui->camera_x += 10;
            if (allegro_keys[KEY_UP]) m_gui->camera_y -= 10;
			if (allegro_keys[KEY_DOWN]) m_gui->camera_y += 10;

			const double zoom_speed = 1.1;
            if (allegro_keys[KEY_PGUP]) m_gui->camera_zoom *= zoom_speed;
			if (allegro_keys[KEY_PGDN]) m_gui->camera_zoom /= zoom_speed;
		}

        // rotate and zoom in/out the scene
        if(allegro_keys[KEY_Z]) {
            //camera_offset+=0.1;
            zoom+=0.1;
            _dbg1("zoom: " << zoom);
        }

        if(allegro_keys[KEY_X]) {
            //camera_offset-=0.1;
            zoom-=0.1;
            _dbg1("zoom: " << zoom);
        }
        if(allegro_keys[KEY_C]) {
            view_angle+=1.0;
            //farVal+=10;
            _dbg1("view_angle: " << view_angle);
        }
        if(allegro_keys[KEY_V]) {
            view_angle-=1.0;
            _dbg1("view_angle: " << view_angle);
        }
        if(allegro_keys[KEY_Q]) {
            camera_step_z+=0.1;
        }
        if(allegro_keys[KEY_W]) {
            camera_step_z -= 0.1;

            if(camera_step_z <= -11.0) camera_step_z=-11.0;
        }

		// === text debug on screen ===

		string mouse_pos_str = std::to_string(gui_mouse_x) + " " + std::to_string(gui_mouse_y);
		string fps_str = "fps ???";
		if (loop_miliseconds != 0) {
			fps_str = "fps: " + std::to_string(1000 / loop_miliseconds);
		}

		const int txt_h = 12; // line height (separation between lines)
		int txt_x = 10, txt_y = 10; // starting position of text

		if (use_draw_allegro) {

			string pck_speed_str = "sending packets speed - " + std::to_string(450 - g_max_anim_frame);
			textout_ex(m_frame, font, mouse_pos_str.c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);
			textout_ex(m_frame, font, fps_str.c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);
			textout_ex(m_frame, font, ("Frame nr.: " +
																 std::to_string(m_frame_number)).c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);

			textout_ex(m_frame, font, pck_speed_str.c_str(), 100, 10, makecol(0, 0, 255), -1);

					if(allegro_keys[KEY_H])
			{
				int tex_y = 10;
				int lineh = 10;
				textout_ex(m_frame, font, "s - start", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "p - pause", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "f - send FTP", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "t - select target", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "r - select source", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "d - remove node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "n - add node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "enter/esc - exit", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "Arrows: move selected node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
				textout_ex(m_frame, font, "SHIFT-Arrows: move the camera", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
							textout_ex(m_frame, font, "SHIFT-PageUp/Down: zimm in/out", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
							textout_ex(m_frame, font, "F1: info about node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
							textout_ex(m_frame, font, "F2: next node", 1140, tex_y+=lineh, makecol(0, 0, 255), -1);
					} else{

							textout_ex(m_frame, font, "h - help", 1140, 30, makecol(0, 0, 255), -1);
					}
		}
		if (use_draw_opengl) {
			// TODO @opengl
            //textout_ex(m_frame, font, mouse_pos_str.c_str(), txt_x, txt_y += txt_h, makecol(0, 0, 255), -1);
            float offset = 0.03;
            float tex_y = 0.9;
            float tex_x = 0.7;
            string pck_speed_str = "sending packets speed - " + std::to_string(450 - g_max_anim_frame);
            glColor4f(0.0,0.0,1.0,0.0);
            //glScalef(0.2f,0.2f,0.2f);
            //glLoadIdentity();
            glPushMatrix();
            glEnable(GL_BLEND);
            allegro_gl_printf_ex(s_font_allegl.get(), -0.9, tex_y, 0.0, mouse_pos_str.c_str());
            allegro_gl_printf_ex(s_font_allegl.get(), -0.9, tex_y-=offset, 0.0, fps_str.c_str());
            allegro_gl_printf_ex(s_font_allegl.get(), -0.9, tex_y-=offset, 0.0, ("Frame nr.: " + std::to_string(m_frame_number)).c_str());
            allegro_gl_printf_ex(s_font_allegl.get(), -0.7, 0.97, 0.0, pck_speed_str.c_str());
            glDisable(GL_BLEND);
            glPopMatrix();

            if(allegro_keys[KEY_H]) {
                _dbg1("KEY_H - opengl");
                //glLoadIdentity();
                glPushMatrix();
                glEnable(GL_BLEND);
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y, 0.0,"s - start");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"p - pause");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"f - send FTP");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"t - select target");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"r - select source");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"d - remove node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"n - add node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"enter/esc - exit");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"Arrows: move selected node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"SHIFT-Arrows: move the camera");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"SHIFT-PageUp/Down: zoom in/out");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"F1: info about node");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y-=offset, 0.0,"F2: next node");
                glDisable(GL_BLEND);
                glPopMatrix();

            } else {
                //glLoadIdentity();
                glPushMatrix();
                glEnable(GL_BLEND);
                //allegro_gl_printf(s_font_allegl.get(), 0.8, 0.9, 0.0,0xFF0000,"h - help");
                allegro_gl_printf_ex(s_font_allegl.get(), tex_x, tex_y, 0.0,"h - help");
                //glBlendFunc(GL_ONE, GL_ZERO);
                glDisable(GL_BLEND);
                glPopMatrix();
            }
		}


		//_dbg3("m_world->m_objects.size(): " << m_world->m_objects.size());
		//_dbg3("get_move_object ret: " << get_move_object(gui_mouse_x, gui_mouse_y));
		int move_object_index = get_move_object(gui_mouse_x, gui_mouse_y); ///< -1 if 'empty'

		if (move_object_index != -1) { // working with selected object
			m_gui->m_selected_object = m_world->m_objects.begin();
			std::advance(m_gui->m_selected_object, move_object_index);
			auto selected_object = m_gui->m_selected_object;
			(*selected_object)->m_selected = true;
			c_entity *selected_object_raw = dynamic_cast<c_entity *>((*selected_object).get());
			c_osi2_switch *selected_switch = dynamic_cast<c_osi2_switch *>((*selected_object).get());
			
		//	selected_switch->send_hello_to_neighbors(); // TODO
			
			//shared_ptr<c_cjddev> selected_device = std::dynamic_pointer_cast<c_cjddev>(selected_object);
			if (selected_object != m_world->m_objects.end()) { // editing the selected object
				// TODO: add connect
				/*if (gui_mouse_b == 1 && !print_connect_line) {
					print_connect_line = true;
					connect_node = std::dynamic_pointer_cast<c_cjddev>(selected_object);
					last_click_time = std::chrono::steady_clock::now();
				}

				if (gui_mouse_b == 1 && print_connect_line &&
				    std::chrono::steady_clock::now() - last_click_time > std::chrono::milliseconds(500)) {
					// assert( connect_node && selected_object  );
					connect_node->add_neighbor(std::dynamic_pointer_cast<c_cjddev>(selected_object));
					(std::dynamic_pointer_cast<c_cjddev>(selected_object))->add_neighbor(std::dynamic_pointer_cast<c_cjddev>(connect_node));
					print_connect_line = false;
				}*/

				if (mode == e_mode_node) { // working with selected object - moving
					if (!print_connect_line) {
						int speed = 5;
						if (allegro_keys[KEY_LEFT])
							selected_object_raw->m_x += -speed;
						if (allegro_keys[KEY_RIGHT])
							selected_object_raw->m_x += speed;
						if (allegro_keys[KEY_DOWN])
							selected_object_raw->m_y += speed;
						if (allegro_keys[KEY_UP])
							selected_object_raw->m_y += -speed;
					}
				} // moving selected object
			}
/*
			if ((allegro_char & 0xff) == 's' && !start_simulation) {
				if (!m_gui->m_source || !m_gui->m_target) {
					std::cout << "please choose target and source node\n";
				} else {
					m_gui->m_source->buy_net(m_gui->m_target->get_address());
					start_simulation = true;
					simulation_pause = false;
				}
			}

			if ((allegro_char & 0xff) == 'd' && selected_device && !start_simulation) {
				for (shared_ptr<c_cjddev> &it : selected_device->get_neighbors()) {
					selected_device->remove_neighbor(it);
					it->remove_neighbor(selected_device);
				}

				for (auto it = m_world->m_objects.begin(); it != m_world->m_objects.end(); ++it) {
					if (it->get() == selected_device.get()) {
						m_world->m_objects.erase(it);
						break;
					}
				}
			}

			if ((allegro_char & 0xff) == 't' && selected_device && !start_simulation) {
				m_gui->m_target = selected_device;
			}

			if ((allegro_char & 0xff) == 'r' && selected_device && !start_simulation) {
				m_gui->m_source = selected_device;
			}

			if ((allegro_char & 0xff) == 'f') {
				if (!m_gui->m_source || !m_gui->m_target)
					std::cout << "please choose target and source node\n";
				else {
					m_gui->m_source->send_ftp_packet(m_gui->m_target->get_address(), "FTP data");
					last_click_time = std::chrono::steady_clock::now();
				}
			}
*/

			// === animation clock controll ===
			if ((allegro_char & 0xff) == 'p') {
				simulation_pause = !simulation_pause;
				last_click_time = std::chrono::steady_clock::now();
			}

			if (allegro_keys[KEY_MINUS_PAD] && g_max_anim_frame < 400 &&
			    std::chrono::steady_clock::now() - last_click_time > std::chrono::milliseconds(loop_miliseconds)) {
				//std::cout << m_frame_number-frame_checkpoint << " - " << g_max_anim_frame << " mod: " << (m_frame_number-frame_checkpoint) % g_max_anim_frame <<  std::endl;
				g_max_anim_frame += 1;
				last_click_time = std::chrono::steady_clock::now();
			}

			if (allegro_keys[KEY_PLUS_PAD] && g_max_anim_frame > 10 &&
			    std::chrono::steady_clock::now() - last_click_time > std::chrono::milliseconds(loop_miliseconds)) {
				//std::cout << m_frame_number-frame_checkpoint << " + " << g_max_anim_frame << " mod: " << (m_frame_number-frame_checkpoint) % g_max_anim_frame <<  std::endl;
				g_max_anim_frame -= 1;
				last_click_time = std::chrono::steady_clock::now();
			}
			
		}

		// === animation clock operations ===
		
        m_world->draw(*m_drawtarget.get()); // <===== DRAW THE WORLD

		/*
		if ((m_frame_number - frame_checkpoint) < g_max_anim_frame) {
			m_world->draw(*m_drawtarget.get(), (m_frame_number - frame_checkpoint) % g_max_anim_frame); // <==
		} else {
			m_world->draw(*m_drawtarget.get(), g_max_anim_frame);
		}
		*/

		if (print_connect_line) { // the line the creates new connections
			if (use_draw_allegro) {
				line(m_frame, connect_node->m_x, connect_node->m_y, allegro_mouse_x, allegro_mouse_y, makecol(0, 255, 255));
			}
            // TODO @opengl
            if (use_draw_opengl) {
                glColor3f(0.0f,1.0f,1.0f);
                glLineWidth(1.0);
                glScalef(1.0f,1.0f,1.0f);

                const int vx = m_gui->view_x(connect_node->m_x), vy = m_gui->view_y(connect_node->m_y); // position in viewport - because camera position
                //float start_line_x = ((connect_node->m_x)-0.5*SCREEN_W)/(0.5*SCREEN_W);
                //float start_line_y = -((connect_node->m_y)-0.5*SCREEN_H)/(0.5*SCREEN_H);
                float start_line_x = (vx-0.5*SCREEN_W)/(0.5*SCREEN_W);
                float start_line_y = -(vy-0.5*SCREEN_H)/(0.5*SCREEN_H);
                float end_line_x = (allegro_mouse_x-0.5*SCREEN_W)/(0.5*SCREEN_W);
                float end_line_y = -(allegro_mouse_y-0.5*SCREEN_H)/(0.5*SCREEN_H);

                //_dbg1("connect_node: " << connect_node->m_x << " " << connect_node->m_y);
                //_dbg1("allegro_mouse: " << allegro_mouse_x << " " << allegro_mouse_y);
                //_dbg1("start_line: " << start_line_x << " " << start_line_y);
                //_dbg1("end_line: " << end_line_x << " " << end_line_y);

                //glLoadIdentity();
                glPushMatrix();
                glBegin(GL_LINES);
                glVertex3f(start_line_x,start_line_y,0.0f);
                glVertex3f(end_line_x,end_line_y,0.0f);
                glEnd();
                glPopMatrix();
            }
		}
		if (allegro_mouse_b == 2) { // end/stop the line that creates new connections
			print_connect_line = false;
		}




		{
			auto x = allegro_mouse_x, y = allegro_mouse_y;
			int r = 5, rr = 4;

			if (use_draw_allegro) {
				line(m_frame, x - rr, y, x + rr, y, makecol(0, 0, 0));
				line(m_frame, x, y - rr, x, y + rr, makecol(0, 0, 0));
				circle(m_frame, x, y, r, makecol(255, 255, 255));
			}
			// TODO @opengl
            if(use_draw_opengl) {
                float opengl_mouse_x = (x-SCREEN_W*0.5)/(0.5*SCREEN_W);
                float opengl_mouse_y = -(y-SCREEN_H*0.5)/(0.5*SCREEN_H);
                float cursor_size=0.01;

                //_dbg1("mouse_x mouse_y: " << mouse_x << " " << mouse_y);
                //_dbg1("screenW screenH: " << SCREEN_W << " " << SCREEN_H);
                //glLoadIdentity();
                //glScalef(1/camera_offset, 1/camera_offset, 1.0);
                //glScalef(1.0*zoom, 1.0*zoom, 1.0*zoom);
                glPushMatrix();
                glScalef(1.0f,1.0f,1.0f);
                glTranslatef(opengl_mouse_x,opengl_mouse_y,0.0f);
                //glTranslatef(m_gui->view_x_rev(mouse_x),m_gui->view_y_rev(mouse_y),0.0f);
                glColor3f(0.0, 0.0, 0.0);

                // draw cursor
                glBegin(GL_LINES);
                glVertex2f(-1.0f*cursor_size,0.0f);
                glVertex2f(1.0f*cursor_size,0.0f);
                glVertex2f(0.0f,-1.0f*cursor_size);
                glVertex2f(0.0f,1.0f*cursor_size);
                glEnd();
                glPopMatrix();
            }

		}


		// === show frame ===

		if (use_draw_allegro) {
			//_dbg1("Allegro: frame done. fps = " << fps_str);
			scare_mouse();
			blit(m_frame, m_screen, 0, 0, 0, 0, m_frame->w, m_frame->h);
			unscare_mouse();
			if (!simulation_pause) {
				++m_frame_number;
			}
		}
		if (use_draw_opengl) {
            //_dbg1("OpenGL: frame flip. fps = " << fps_str);
			allegro_gl_flip();
		}

		for (auto &object : m_world->m_objects) {
			object->m_selected = false;
		}
		
//		std::this_thread::sleep_for(std::chrono::milliseconds(10));
		auto stop_time = std::chrono::high_resolution_clock::now();
		auto diff = stop_time - start_time;
		loop_miliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count();
	}

	std::ofstream out_file("../layout/current/out.map.txt");
	out_file << *m_world << std::endl;
}
Example #29
0
void c_tun_device_empty::set_mtu(uint32_t mtu) {
	_warn("Called set_mtu on empty device");
	_UNUSED(mtu);
}
Example #30
0
void
_mcleanup(void)
{
	int fd;
	int fromindex;
	int endfrom;
	u_long frompc;
	int toindex;
	struct rawarc rawarc;
	struct gmonparam *p = &_gmonparam;
	struct gmonhdr gmonhdr, *hdr;
	struct clockinfo clockinfo;
	char outname[128];
	int mib[2];
	size_t size;
#ifdef DEBUG
	int log, len;
	char buf[200];
#endif

	if (p->state == GMON_PROF_ERROR)
		ERR("_mcleanup: tos overflow\n");

	size = sizeof(clockinfo);
	mib[0] = CTL_KERN;
	mib[1] = KERN_CLOCKRATE;
	if (sysctl(mib, 2, &clockinfo, &size, NULL, 0) < 0) {
		/*
		 * Best guess
		 */
		clockinfo.profhz = hertz();
	} else if (clockinfo.profhz == 0) {
		if (clockinfo.hz != 0)
			clockinfo.profhz = clockinfo.hz;
		else
			clockinfo.profhz = hertz();
	}

	moncontrol(0);
	if (getenv("PROFIL_USE_PID"))
		snprintf(outname, sizeof(outname), "%s.%d.gmon",
		    _getprogname(), getpid());
	else
		snprintf(outname, sizeof(outname), "%s.gmon", _getprogname());

	fd = _open(outname, O_CREAT|O_TRUNC|O_WRONLY|O_CLOEXEC, 0666);
	if (fd < 0) {
		_warn("_mcleanup: %s", outname);
		return;
	}
#ifdef DEBUG
	log = _open("gmon.log", O_CREAT|O_TRUNC|O_WRONLY|O_CLOEXEC, 0664);
	if (log < 0) {
		_warn("_mcleanup: gmon.log");
		return;
	}
	len = sprintf(buf, "[mcleanup1] kcount 0x%p ssiz %lu\n",
	    p->kcount, p->kcountsize);
	_write(log, buf, len);
#endif
	hdr = (struct gmonhdr *)&gmonhdr;
	bzero(hdr, sizeof(*hdr));
	hdr->lpc = p->lowpc;
	hdr->hpc = p->highpc;
	hdr->ncnt = p->kcountsize + sizeof(gmonhdr);
	hdr->version = GMONVERSION;
	hdr->profrate = clockinfo.profhz;
	_write(fd, (char *)hdr, sizeof *hdr);
	_write(fd, p->kcount, p->kcountsize);
	endfrom = p->fromssize / sizeof(*p->froms);
	for (fromindex = 0; fromindex < endfrom; fromindex++) {
		if (p->froms[fromindex] == 0)
			continue;

		frompc = p->lowpc;
		frompc += fromindex * p->hashfraction * sizeof(*p->froms);
		for (toindex = p->froms[fromindex]; toindex != 0;
		     toindex = p->tos[toindex].link) {
#ifdef DEBUG
			len = sprintf(buf,
			"[mcleanup2] frompc 0x%lx selfpc 0x%lx count %lu\n" ,
				frompc, p->tos[toindex].selfpc,
				p->tos[toindex].count);
			_write(log, buf, len);
#endif
			rawarc.raw_frompc = frompc;
			rawarc.raw_selfpc = p->tos[toindex].selfpc;
			rawarc.raw_count = p->tos[toindex].count;
			_write(fd, &rawarc, sizeof rawarc);
		}
	}
	_close(fd);
}