Пример #1
0
static int parent_main(HANDLE rev)
{
	HANDLE dev;
	HANDLE ht[2];
	char * cmdline;
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	DWORD rc, exitcode;

	// Ignore ^C, ^BREAK in parent
	SetConsoleCtrlHandler(parent_console_handler, TRUE/*add*/);

	// Create event used by child to signal daemon_detach()
	if (!(dev = create_event(EVT_DETACHED, FALSE/*not signaled*/, TRUE, NULL/*must not exist*/))) {
		CloseHandle(rev);
		return 101;
	}

	// Restart process with same args
	cmdline = GetCommandLineA();
	memset(&si, 0, sizeof(si)); si.cb = sizeof(si);
	
	if (!CreateProcessA(
		NULL, cmdline,
		NULL, NULL, TRUE/*inherit*/,
		0, NULL, NULL, &si, &pi)) {
		fprintf(stderr, "CreateProcess(.,\"%s\",.) failed, Error=%ld\n", cmdline, GetLastError());
		CloseHandle(rev); CloseHandle(dev);
		return 101;
	}
	CloseHandle(pi.hThread);

	// Wait for daemon_detach() or exit()
	ht[0] = dev; ht[1] = pi.hProcess;
	rc = WaitForMultipleObjects(2, ht, FALSE/*or*/, INFINITE);
	if (!(/*WAIT_OBJECT_0(0) <= rc && */ rc < WAIT_OBJECT_0+2)) {
		fprintf(stderr, "WaitForMultipleObjects returns %lX\n", rc);
		TerminateProcess(pi.hProcess, 200);
	}
	CloseHandle(rev); CloseHandle(dev);

	// Get exit code
	if (!GetExitCodeProcess(pi.hProcess, &exitcode))
		exitcode = 201;
	else if (exitcode == STILL_ACTIVE) // detach()ed, assume OK
		exitcode = 0;

	CloseHandle(pi.hProcess);
	return exitcode;
}
Пример #2
0
void injectProcess(HANDLE proc) {
	HANDLE tid;
	BOOL is32;
	FARPROC addr;
	LPVOID arg;
	char dll[PATH_MAX];
	char *ext = 0;
	DWORD rc;
	extern IMAGE_DOS_HEADER __ImageBase;
	ASSERT(proc);
	memset(dll, 0, sizeof(dll));
	CHK(GetModuleFileNameA((HMODULE)&__ImageBase, dll, sizeof(dll)));
	if (!ext)
		ext = strstr(dll, ".exe");
	if (!ext)
		ext = strstr(dll, ".dll");
	if (!ext)
		ext = dll + strlen(dll);
	CHK(IsWow64Process(proc, &is32));
	CHK(0 != (arg = VirtualAllocEx(proc, 0, strlen(dll) + 1,
				       MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)));
	if (strcmp(ext, ".dll"))
		memcpy(ext, is32 ? "32.dll" : "64.dll", 6);
	if (is32) {
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		const char * helpername = "fsatracehelper.exe";
		char helper[PATH_MAX];
		char * p;
		memset(&si, 0, sizeof(si));
		memset(&pi, 0, sizeof(pi));
		si.cb = sizeof(si);
		memcpy(helper, dll, strlen(dll)+1);
		p = strrchr(helper, '\\');
		memcpy(p+1, helpername, strlen(helpername)+1);
		CHK(CreateProcessA(0, helper, 0, 0, 0, 0, 0, 0, &si, &pi));
		CHK(WAIT_OBJECT_0 == WaitForSingleObject(pi.hProcess, INFINITE));
		CHK(GetExitCodeProcess(pi.hProcess, &rc));
		addr = (FARPROC)(uintptr_t)rc;
	}
	else
		addr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
	CHK(addr);
	CHK(WriteProcessMemory(proc, arg, dll, strlen(dll) + 1, NULL));
	CHK(0 != (tid = CreateRemoteThread(proc, 0, 0,
					   (LPTHREAD_START_ROUTINE)addr, arg, 0, 0)));
	CHK(-1 != ResumeThread(tid));
	CHK(WAIT_OBJECT_0 == WaitForSingleObject(tid, INFINITE));
	CHK(CloseHandle(tid));
}
Пример #3
0
static int LLDebugExecuteFile(const std::string &filename,
							  unsigned short port) {
	PROCESS_INFORMATION pi;
	STARTUPINFOA si;

	// Initialize the infomation.
	memset(&pi, 0, sizeof(pi));
	memset(&si, 0, sizeof(si));
	si.cb = sizeof(si);
	si.wShowWindow = SW_SHOW;

	// Execution string. This must be mutable.
	char commandline[_MAX_PATH * 2];
	snprintf(commandline, sizeof(commandline), "\"%s\" %d",
		filename.c_str(), port);
	
	// Execute file.
	BOOL result = CreateProcessA(
		NULL, // filename
		commandline, // arguments
		NULL, // process attributes
		NULL, // thread attributes
		FALSE, // is inherit handle
		NORMAL_PRIORITY_CLASS, // attributes
		NULL, // pointer of environmental path
		NULL, // curret directory
		&si, // startup info
		&pi // process and thread info
		);

	if (!result) {
		LPTSTR lpBuffer;
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			NULL,
			GetLastError(),
			LANG_USER_DEFAULT,
			(LPTSTR)&lpBuffer,
			0,
			NULL);
		MessageBox(NULL, lpBuffer, TEXT("error message"), MB_ICONHAND|MB_OK);
		LocalFree(lpBuffer);
		return -1;
	}

	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);
	return 0;
}
Пример #4
0
static int cmd_available(void)
{
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;
    char cmd[] = "cmd /c exit 0";

    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);
    if (CreateProcessA(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
        return TRUE;
    }
    return FALSE;
}
Пример #5
0
    SDHANDLE SDAPI SDCreateProcess(const char * progName, const char * pCmdLine ,const char * pWorkDir, SProcessAttr * pAttr )
    {
#if (defined(WIN32) || defined(WIN64))
        STARTUPINFOA m_sinfo;
        PROCESS_INFORMATION m_pinfo;
        void * pEnv = NULL;
        bool inherithandle = false;
        uint32 createFlags =0;
        if (pAttr != NULL)
        {
            pEnv = (LPVOID)pAttr->environment.c_str();
            inherithandle = pAttr->inherithandle;
            createFlags = pAttr->createFlags;
        }

        memset((void*)&m_pinfo, 0, sizeof(PROCESS_INFORMATION));
        memset((void*)&m_sinfo, 0, sizeof(STARTUPINFO));
        m_sinfo.cb = sizeof(STARTUPINFO);
        if( !CreateProcessA( progName,
                             (LPSTR)pCmdLine,
                             NULL,
                             NULL,
                             inherithandle,
                             createFlags,
                             (LPVOID)pEnv,
                             pWorkDir,
                             &m_sinfo,
                             &m_pinfo)
          )
        {
            return SDINVALID_HANDLE;
        }
		return (SDHANDLE)s_processIndexer.Alloc(m_pinfo); 
#else
        pid_t m_pid;
        if ( (m_pid = fork()) < 0 )
        {
			return s_processIndexer.Alloc(m_pid); 
        }
        else if(m_pid == 0)
        {
            execv(pWorkDir, NULL);
            _exit(-1);
        }
		return s_processIndexer.Alloc(m_pid); 
#endif

    }
Пример #6
0
static BOOL
create_process (const char *program, char *args,
		DWORD flags, PROCESS_INFORMATION *pi)
{
  BOOL ret;

#ifdef _WIN32_WCE
  wchar_t *p, *wprogram, *wargs;
  size_t argslen;

  wprogram = alloca ((strlen (program) + 1) * sizeof (wchar_t));
  mbstowcs (wprogram, program, strlen (program) + 1);

  for (p = wprogram; *p; ++p)
    if (L'/' == *p)
      *p = L'\\';

  argslen = strlen (args);
  wargs = alloca ((argslen + 1) * sizeof (wchar_t));
  mbstowcs (wargs, args, argslen + 1);

  ret = CreateProcessW (wprogram, /* image name */
			wargs,    /* command line */
			NULL,     /* security, not supported */
			NULL,     /* thread, not supported */
			FALSE,    /* inherit handles, not supported */
			flags,    /* start flags */
			NULL,     /* environment, not supported */
			NULL,     /* current directory, not supported */
			NULL,     /* start info, not supported */
			pi);      /* proc info */
#else
  STARTUPINFOA si = { sizeof (STARTUPINFOA) };

  ret = CreateProcessA (program,  /* image name */
			args,     /* command line */
			NULL,     /* security */
			NULL,     /* thread */
			TRUE,     /* inherit handles */
			flags,    /* start flags */
			NULL,     /* environment */
			NULL,     /* current directory */
			&si,      /* start info */
			pi);      /* proc info */
#endif

  return ret;
}
Пример #7
0
static void test_debug_heap( const char *argv0, DWORD flags )
{
    char keyname[MAX_PATH];
    char buffer[MAX_PATH];
    PROCESS_INFORMATION	info;
    STARTUPINFOA startup;
    BOOL ret;
    DWORD err;
    HKEY hkey;
    const char *basename;

    if ((basename = strrchr( argv0, '\\' ))) basename++;
    else basename = argv0;

    sprintf( keyname, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\%s",
             basename );
    if (!strcmp( keyname + strlen(keyname) - 3, ".so" )) keyname[strlen(keyname) - 3] = 0;

    err = RegCreateKeyA( HKEY_LOCAL_MACHINE, keyname, &hkey );
    if (err == ERROR_ACCESS_DENIED)
    {
        skip("Not authorized to change the image file execution options\n");
        return;
    }
    ok( !err, "failed to create '%s' error %u\n", keyname, err );
    if (err) return;

    if (flags == 0xdeadbeef)  /* magic value for unsetting it */
        RegDeleteValueA( hkey, "GlobalFlag" );
    else
        RegSetValueExA( hkey, "GlobalFlag", 0, REG_DWORD, (BYTE *)&flags, sizeof(flags) );

    memset( &startup, 0, sizeof(startup) );
    startup.cb = sizeof(startup);

    sprintf( buffer, "%s heap.c 0x%x", argv0, flags );
    ret = CreateProcessA( NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &info );
    ok( ret, "failed to create child process error %u\n", GetLastError() );
    if (ret)
    {
        winetest_wait_child_process( info.hProcess );
        CloseHandle( info.hThread );
        CloseHandle( info.hProcess );
    }
    RegDeleteValueA( hkey, "GlobalFlag" );
    RegCloseKey( hkey );
    RegDeleteKeyA( HKEY_LOCAL_MACHINE, keyname );
}
Пример #8
0
static void
run_client(const char *test)
{
  char cmdline[MAX_PATH];
  PROCESS_INFORMATION info;
  STARTUPINFOA startup;

  memset(&startup, 0, sizeof startup);
  startup.cb = sizeof startup;

  make_cmdline(cmdline, test);
  ok(CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
  winetest_wait_child_process( info.hProcess );
  ok(CloseHandle(info.hProcess), "CloseHandle\n");
  ok(CloseHandle(info.hThread), "CloseHandle\n");
}
Пример #9
0
int spawn_shell(PROCESS_INFORMATION *pi, HANDLE *out_read, HANDLE *in_write)
{
	SECURITY_ATTRIBUTES sattr;
	STARTUPINFOA si;
	HANDLE in_read, out_write;

	memset(&si, 0x00, sizeof(SECURITY_ATTRIBUTES));
	memset(pi, 0x00, sizeof(PROCESS_INFORMATION));
    
	// create communication pipes  
	memset(&sattr, 0x00, sizeof(SECURITY_ATTRIBUTES));
	sattr.nLength = sizeof(SECURITY_ATTRIBUTES); 
	sattr.bInheritHandle = TRUE; 
	sattr.lpSecurityDescriptor = NULL; 

	if (!CreatePipe(out_read, &out_write, &sattr, 0)) {
		return STATUS_PROCESS_NOT_CREATED;
	}
	if (!SetHandleInformation(*out_read, HANDLE_FLAG_INHERIT, 0)) {
		return STATUS_PROCESS_NOT_CREATED;
	}

	if (!CreatePipe(&in_read, in_write, &sattr, 0)) {
		return STATUS_PROCESS_NOT_CREATED;
	}
	if (!SetHandleInformation(*in_write, HANDLE_FLAG_INHERIT, 0)) {
		return STATUS_PROCESS_NOT_CREATED;
	}

	// spawn process
	memset(&si, 0x00, sizeof(STARTUPINFO));
	si.cb = sizeof(STARTUPINFO); 
	si.hStdError = out_write;
	si.hStdOutput = out_write;
	si.hStdInput = in_read;
	si.dwFlags |= STARTF_USESTDHANDLES;

	if (!CreateProcessA(NULL, "cmd", NULL, NULL, TRUE, 0, NULL, NULL, (LPSTARTUPINFOA) &si, pi)) {
		return STATUS_PROCESS_NOT_CREATED;
	}

	CloseHandle(out_write);
	CloseHandle(in_read);

	return STATUS_OK;
}
Пример #10
0
static int mysystem(const char *command)
{
  int ret;
  STARTUPINFOA        si; //  = { sizeof(si)};
  si.cb = sizeof(si);
  PROCESS_INFORMATION pi;
  char cmd[4096];

  //strcpy(cmd,command);
  ExpandEnvironmentStringsA(command,cmd,sizeof(cmd)-1);
  ret = (int) CreateProcessA( NULL, cmd
                           , NULL, NULL
                           , FALSE, CREATE_NO_WINDOW
                           , NULL, NULL
                           , &si, &pi);
  return ret;
}
Пример #11
0
// --------------------------------------------------------------------------------
//	Executes the given executable with the given arguments.
//
//   path      : Path to executable to run.
//   arguments : Arguments to pass to executable.
//   directory : Working directory.
//
//   Returns : True if successful, otherwise false.
// --------------------------------------------------------------------------------
bool FileHelper::Execute(std::string path, std::string arguments, std::string directory)
{
    STARTUPINFOA       siStartupInfo;
    PROCESS_INFORMATION piProcessInfo;

    memset(&siStartupInfo, 0, sizeof(siStartupInfo));
    memset(&piProcessInfo, 0, sizeof(piProcessInfo));

    siStartupInfo.cb = sizeof(siStartupInfo);

	std::string finalArg = std::string("Shell " + arguments);
	char argArray[256];
	char* argArrayPtr = (char*)(&argArray);

	if (finalArg.size() < 256)
	{
		finalArg.copy(argArrayPtr, finalArg.size());
		argArray[finalArg.size()] = '\0';
	}
    int res = CreateProcessA(path.c_str(),  
                    (char*)(&argArray),                 
                     0,
                     0,
                     FALSE,
                     CREATE_DEFAULT_ERROR_MODE,
                     0,
                     directory == "" ? 0 : directory.c_str(),                            
                     &siStartupInfo,
                     &piProcessInfo);
	
	if (res == 0)
		return false;

	WaitForSingleObject(piProcessInfo.hProcess, INFINITE);

	return true;
	
	/*
	HINSTANCE res = ShellExecuteA(NULL, "open", path.c_str(), arguments.c_str(), NULL, SW_SHOWNORMAL);

	if (reinterpret_cast<int>(res) > 32)
		return true;
	
	return false;
	*/
}
int LLProcessLauncher::launch(void)
{
	// If there was already a process associated with this object, kill it.
	kill();
	orphan();

	int result = 0;
	
	PROCESS_INFORMATION pinfo;
	STARTUPINFOA sinfo;
	memset(&sinfo, 0, sizeof(sinfo));
	
	std::string args = mExecutable;
	for(int i = 0; i < (int)mLaunchArguments.size(); i++)
	{
		args += " ";
		args += mLaunchArguments[i];
	}
	
	// So retarded.  Windows requires that the second parameter to CreateProcessA be a writable (non-const) string...
	char *args2 = new char[args.size() + 1];
	strcpy(args2, args.c_str());

	if( ! CreateProcessA( NULL, args2, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo ) )
	{
		// TODO: do better than returning the OS-specific error code on failure...
		result = GetLastError();
		if(result == 0)
		{
			// Make absolutely certain we return a non-zero value on failure.
			result = -1;
		}
	}
	else
	{
		// foo = pinfo.dwProcessId; // get your pid here if you want to use it later on
		// CloseHandle(pinfo.hProcess); // stops leaks - nothing else
		mProcessHandle = pinfo.hProcess;
		CloseHandle(pinfo.hThread); // stops leaks - nothing else
	}		
	
	delete[] args2;
	
	return result;
}
Пример #13
0
char* rdp_rds_module_start(RDS_MODULE_COMMON* module)
{
	BOOL status;
	rdsModuleRdp* rdp;
	char lpCommandLine[256];
	const char* endpoint = "RDP";
	long xres, yres,colordepth;
	char* pipeName = (char*) malloc(256);

	rdp = (rdsModuleRdp*) module;

	rdp->SessionId = rdp->commonModule.sessionId;

	WLog_Print(rdp->log, WLOG_DEBUG, "RdsModuleStart: SessionId: %d Endpoint: %s",
			(int) rdp->commonModule.sessionId, endpoint);

	freerds_named_pipe_get_endpoint_name((int) rdp->commonModule.sessionId, endpoint, pipeName, 256);
	freerds_named_pipe_clean(pipeName);

	ZeroMemory(&(rdp->si), sizeof(STARTUPINFO));
	rdp->si.cb = sizeof(STARTUPINFO);
	ZeroMemory(&(rdp->pi), sizeof(PROCESS_INFORMATION));

	initResolutions(rdp->commonModule.baseConfigPath, &g_Config,
			&rdp->commonModule.envBlock, &xres, &yres, &colordepth);

	sprintf_s(lpCommandLine, sizeof(lpCommandLine), "%s /tmp/rds.rdp /size:%dx%d",
			"freerds-rdp", (int) xres, (int) yres);

	WLog_Print(rdp->log, WLOG_DEBUG, "Starting process with command line: %s", lpCommandLine);

	status = CreateProcessA(NULL, lpCommandLine,
			NULL, NULL, FALSE, 0, rdp->commonModule.envBlock, NULL,
			&(rdp->si), &(rdp->pi));

	WLog_Print(rdp->log, WLOG_DEBUG, "Process created with status: %d", status);

	if (!WaitNamedPipeA(pipeName, 5 * 1000))
	{
		fprintf(stderr, "WaitNamedPipe failure: %s\n", pipeName);
		return NULL;
	}

	return pipeName;
}
Пример #14
0
BOOL MSVCMemoryDump::executeProcess(const std::string & commandLine) {
	STARTUPINFOA si;
	PROCESS_INFORMATION pi;
	GetStartupInfoA(&si);

	BOOL success = CreateProcessA(NULL,
		(char *) commandLine.c_str(),	//Name of app to launch
		NULL,	//Default process security attributes
		NULL,	//Default thread security attributes
		FALSE,	//Don't inherit handles from the parent
		0,	//Normal priority
		NULL,	//Use the same environment as the parent
		NULL,	//Launch in the current directory
		&si,	//Startup Information
		&pi);	//Process information stored upon return

	return success;
}
Пример #15
0
int cef_rds_module_start(rdsModule* module)
{
	BOOL status;
	rdsModuleCef* cef;
	rdpSettings* settings;
	rdsConnector* connector;
	char lpCommandLine[256];
	const char* endpoint = "CEF";

	cef = (rdsModuleCef*) module;
	connector = (rdsConnector*) module;

	WLog_Print(cef->log, WLOG_DEBUG, "RdsModuleStart: SessionId: %d Endpoint: %s",
			(int) module->SessionId, endpoint);

	settings = connector->settings;

	freerds_named_pipe_clean(module->SessionId, endpoint);

	ZeroMemory(&(cef->si), sizeof(STARTUPINFO));
	cef->si.cb = sizeof(STARTUPINFO);
	ZeroMemory(&(cef->pi), sizeof(PROCESS_INFORMATION));

	sprintf_s(lpCommandLine, sizeof(lpCommandLine), "%s /session-id:%d /width:%d /height:%d",
			"freerds-cef", (int) module->SessionId, settings->DesktopWidth, settings->DesktopHeight);

	WLog_Print(cef->log, WLOG_DEBUG, "Starting process with command line: %s", lpCommandLine);

	status = CreateProcessA(NULL, lpCommandLine,
			NULL, NULL, FALSE, 0, NULL, NULL,
			&(cef->si), &(cef->pi));

	WLog_Print(cef->log, WLOG_DEBUG, "Process created with status: %d", status);

	module->hClientPipe = freerds_named_pipe_connect(module->SessionId, "CEF", 5 * 1000);

	if (!module->hClientPipe)
	{
		WLog_Print(cef->log, WLOG_ERROR, "Failed to connect to service");
		return -1;
	}

	return 0;
}
Пример #16
0
int WINAPI mWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
	PSTR szCmdParam, int iCmdShow)
{
    //if (!stricmp(szCmdParam, "-n")) //phc
	//editnpc = 1;
    //if (!stricmp(szCmdParam, "-r")) //phc
	random = 1;					  //phc	

    // First check to see if the file exists.
    //
    while (GetFileAttributesA("cityofheroes.exe") == INVALID_FILE_ATTRIBUTES) {
		PromptUserForCohLocation();
    }

    STARTUPINFO startup;
    memset(&startup, 0, sizeof(startup));
    startup.cb = sizeof(STARTUPINFO);
    memset(&pinfo, 0, sizeof(pinfo));

    if(!CreateProcessA("cityofheroes.exe", "cityofheroes.exe -project coh -noverify", NULL, NULL, FALSE, CREATE_NEW_PROCESS_GROUP | CREATE_SUSPENDED | DETACHED_PROCESS, NULL, NULL, (LPSTARTUPINFOA)&startup, &pinfo)) {
		MessageBoxA(NULL, "Failed to launch process!", "Error", MB_OK | MB_ICONEXCLAMATION);
		return 0;
    }

    // delete old crap previous version used
	BOOL blAtr = GetFileAttributesA("data\\charcreate.txt");
    if (blAtr)
		DeleteFileA("data\\charcreate.txt");

    RunPatch();

	//Inject my Dll

	DWORD dwPID = pinfo.dwProcessId ;
	m_hTargetProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);

	InjectDLL(_T("HookCostume.dll"));

	CloseHandle(m_hTargetProcess);

    ResumeThread(pinfo.hThread);
    return 0;
}
void CWE272_Least_Privilege_Violation__w32_char_CreateProcess_15_bad()
{
    switch(6)
    {
    case 6:
    {
        STARTUPINFOA si;
        PROCESS_INFORMATION pi;
        /* FLAW: The commandLine parameter to CreateProcess() contains a space in it and does not
           surround the executable path with quotes.  A malicious executable could be run because
           of the way the function parses spaces. The process will attempt to run "Program.exe,"
           if it exists, instead of the intended "GoodApp.exe" */
        if( !CreateProcessA(NULL,
                            "C:\\Program Files\\GoodApp arg1 arg2",
                            NULL,
                            NULL,
                            FALSE,
                            0,
                            NULL,
                            NULL,
                            &si,
                            &pi))
        {
            printLine("CreateProcess failed");
            return;
        }
        else
        {
            printLine("CreateProcess successful");
        }
        /* Wait until child process exits. */
        WaitForSingleObject(pi.hProcess, INFINITE);
        /* Close process and thread handles.*/
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}
Пример #18
0
/**************************************************************************
 *           WINOLDAP entry point
 */
void WINAPI WINOLDAP_EntryPoint( CONTEXT86 *context )
{
    PDB16 *psp;
    INT len;
    LPSTR cmdline;
    PROCESS_INFORMATION info;
    STARTUPINFOA startup;
    DWORD count, exit_code = 1;

    InitTask16( context );

    TRACE( "(ds=%x es=%x fs=%x gs=%x, bx=%04x cx=%04x di=%04x si=%x)\n",
            context->SegDs, context->SegEs, context->SegFs, context->SegGs,
            context->Ebx, context->Ecx, context->Edi, context->Esi );

    psp = GlobalLock16( context->SegEs );
    len = psp->cmdLine[0];
    cmdline = HeapAlloc( GetProcessHeap(), 0, len + 1 );
    memcpy( cmdline, psp->cmdLine + 1, len );
    cmdline[len] = 0;

    memset( &startup, 0, sizeof(startup) );
    startup.cb = sizeof(startup);

    if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
                        0, NULL, NULL, &startup, &info ))
    {
        /* Give 10 seconds to the app to come up */
        if (wait_input_idle( info.hProcess, 10000 ) == WAIT_FAILED)
            WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
        ReleaseThunkLock( &count );

        WaitForSingleObject( info.hProcess, INFINITE );
        GetExitCodeProcess( info.hProcess, &exit_code );
        CloseHandle( info.hThread );
        CloseHandle( info.hProcess );
    }
    else
        ReleaseThunkLock( &count );

    HeapFree( GetProcessHeap(), 0, cmdline );
    ExitThread( exit_code );
}
Пример #19
0
void mpk_import_create_process(mpk_import_command_line *cmdl, HANDLE process_group, memory_arena *memory_arena) {
  m_memory_arena_undo_allocations_at_scope_exit(memory_arena);
  STARTUPINFO su_info = { sizeof(su_info) };
  su_info.dwFlags = STARTF_USESHOWWINDOW;
  su_info.wShowWindow = SW_HIDE;
  PROCESS_INFORMATION ps_info;
  int n = snprintf(nullptr, 0, m_mpk_import_command_line_parse_str, m_mpk_import_command_line_snprintf_unpack(cmdl));
  char *cmdl_str = memory_arena_allocate<char>(memory_arena, n + 1);
  snprintf(cmdl_str, n + 1, m_mpk_import_command_line_parse_str, m_mpk_import_command_line_snprintf_unpack(cmdl));
  if (!CreateProcessA("mpk_import.exe", cmdl_str, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &su_info, &ps_info)) {
    m_last_error_str(err);
    m_die("cannot create new mpk import process, %s", err);
  }
  if (!AssignProcessToJobObject(process_group, ps_info.hProcess)) {
    m_last_error_str(err);
    m_die("cannot assign new mpk import process to process group, %s", err);
  }
  CloseHandle(ps_info.hProcess);
}
Пример #20
0
int system_( const char *cmd ){

#if _WIN32

	bool inherit=false;
	DWORD flags=CREATE_NO_WINDOW;
	STARTUPINFOA si={sizeof(si)};
	PROCESS_INFORMATION pi={0};
	
	bbString tmp=BB_T( "cmd /S /C\"" )+BB_T( cmd )+BB_T( "\"" );
	
	if( GetStdHandle( STD_OUTPUT_HANDLE ) ){
	
		inherit=true;
		si.dwFlags=STARTF_USESTDHANDLES;
		si.hStdInput=GetStdHandle( STD_INPUT_HANDLE );
		si.hStdOutput=GetStdHandle( STD_OUTPUT_HANDLE );
		si.hStdError=GetStdHandle( STD_ERROR_HANDLE );
	}
	
	if( GetConsoleWindow() ){

		flags=0;
	}
	
	if( !CreateProcessA( 0,(LPSTR)tmp.c_str(),0,0,inherit,flags,0,0,&si,&pi ) ) return -1;

	WaitForSingleObject( pi.hProcess,INFINITE );
	
	int res=GetExitCodeProcess( pi.hProcess,(DWORD*)&res ) ? res : -1;
	
	CloseHandle( pi.hProcess );
	CloseHandle( pi.hThread );

	return res;

#else

	return system( cmd );

#endif

}
Пример #21
0
void sys_execute(const char *p_command, const char *p_argument)
{
	char t_command_line[1024];
	sprintf(t_command_line, "\"%s\" %s", p_command, p_argument);

	STARTUPINFOA t_startup_info;
	memset(&t_startup_info, 0, sizeof(STARTUPINFOA));
	t_startup_info . cb = sizeof(STARTUPINFOA);
	t_startup_info . dwFlags = STARTF_USESHOWWINDOW;
	t_startup_info . wShowWindow = SW_HIDE;

	PROCESS_INFORMATION t_process_info;
	if (CreateProcessA(p_command, t_command_line, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &t_startup_info, &t_process_info) != 0)
	{
		CloseHandle(t_process_info . hThread);
		WaitForSingleObject(t_process_info . hProcess, INFINITE);
		CloseHandle(t_process_info . hProcess);
	}
}
Пример #22
0
int main() {

STARTUPINFO si = {};
PROCESS_INFORMATION pi = {};
char cmd[] = "opengl1.exe";

HANDLE read_h, write_h;
SECURITY_ATTRIBUTES sa = {};
sa.nLength = sizeof sa;
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

if(! CreatePipe( &read_h, &write_h, NULL, 0 ) ) {
  printf("error %x\n", GetLastError() );
  return 1;
}
SetHandleInformation( write_h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );

si.cb = sizeof si;
si.hStdOutput = write_h;
si.dwFlags = STARTF_USESTDHANDLES;

BOOL result = CreateProcessA( NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi );
if(!result) {
  printf("error %x\n", GetLastError() );
  return 1;
}

CloseHandle( write_h );

DWORD bytes_read;
while( ReadFile( read_h, buf, sizeof buf, &bytes_read, NULL ) ) {
  if( bytes_read == 0 ) break;
  buf[ bytes_read ] = '\0';
  printf("%s", buf );
}

CloseHandle( read_h );
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );

return 0;
}
Пример #23
0
JNIEXPORT void JNICALL 
Java_org_gudy_azureus2_platform_win32_access_impl_AEWin32AccessInterface_createProcessA(
	JNIEnv*		env,
	jclass		cla, 
	jstring		_command_line, 
	jboolean	_inherit_handles )
{
	char		command_line[16000];

	STARTUPINFOA			start_info;
	PROCESS_INFORMATION		proc_info;

	if ( !jstringToCharsA( env, _command_line, command_line, sizeof( command_line ))){

		return;
	}

	memset( &start_info, 0, sizeof( STARTUPINFOA ));

	start_info.cb = sizeof( STARTUPINFOA );

	if ( CreateProcessA(
			NULL,				// LPCTSTR lpApplicationName,
			command_line,		// LPTSTR lpCommandLine,
			NULL,				// LPSECURITY_ATTRIBUTES lpProcessAttributes,
			NULL,				// LPSECURITY_ATTRIBUTES lpThreadAttributes,
			_inherit_handles,	// BOOL bInheritHandles,
			DETACHED_PROCESS,	// DWORD dwCreationFlags,
			NULL,				// LPVOID lpEnvironment,
			NULL,				// LPCTSTR lpCurrentDirectory,
			&start_info,		// LPSTARTUPINFO lpStartupInfo,
			&proc_info )){		// LPPROCESS_INFORMATION lpProcessInformation


		CloseHandle( proc_info.hThread );
        CloseHandle( proc_info.hProcess );

	}else{

		throwException( env, "createProcess", "CreateProcess failed" );
	}
};
Пример #24
0
/*
** Start up a client process for iClient, if it is not already
** running.  If the client is already running, then this routine
** is a no-op.
*/
static void startClient(int iClient){
  runSql("INSERT OR IGNORE INTO client VALUES(%d,0)", iClient);
  if( sqlite3_changes(g.db) ){
    char *zSys;
    int rc;
    zSys = sqlite3_mprintf("%s \"%s\" --client %d --trace %d",
                 g.argv0, g.zDbFile, iClient, g.iTrace);
    if( g.bSqlTrace ){
      zSys = sqlite3_mprintf("%z --sqltrace", zSys);
    }
    if( g.bSync ){
      zSys = sqlite3_mprintf("%z --sync", zSys);
    }
    if( g.zVfs ){
      zSys = sqlite3_mprintf("%z --vfs \"%s\"", zSys, g.zVfs);
    }
    if( g.iTrace>=2 ) logMessage("system('%q')", zSys);
#if !defined(_WIN32)
    zSys = sqlite3_mprintf("%z &", zSys);
    rc = system(zSys);
    if( rc ) errorMessage("system() fails with error code %d", rc);
#else
    {
      STARTUPINFOA startupInfo;
      PROCESS_INFORMATION processInfo;
      memset(&startupInfo, 0, sizeof(startupInfo));
      startupInfo.cb = sizeof(startupInfo);
      memset(&processInfo, 0, sizeof(processInfo));
      rc = CreateProcessA(NULL, zSys, NULL, NULL, FALSE, 0, NULL, NULL,
                        &startupInfo, &processInfo);
      if( rc ){
        CloseHandle(processInfo.hThread);
        CloseHandle(processInfo.hProcess);
      }else{
        errorMessage("CreateProcessA() fails with error code %lu",
                     GetLastError());
      }
    }
#endif
    sqlite3_free(zSys);
  }
}
Пример #25
0
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
BOOL CreateChildProcess(Config* pconfig) {
    PROCESS_INFORMATION* pproc_info;
    STARTUPINFOA start_info;
    BOOL success = FALSE;
    HANDLE parent_std_out = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE parent_std_err = GetStdHandle(STD_ERROR_HANDLE);

    // Set up members of the PROCESS_INFORMATION structure.
    pproc_info = calloc(1, sizeof(PROCESS_INFORMATION));

    // Set up members of the _STARTUPINFOW structure.
    // This structure specifies the STDIN and STDOUT handles for redirection.
    ZeroMemory( &start_info, sizeof(STARTUPINFOA));
    start_info.cb = sizeof(STARTUPINFOA);
    start_info.hStdError = parent_std_err;
    start_info.hStdOutput = parent_std_out;
    start_info.hStdInput = g_child_std_in_rd;
    start_info.dwFlags |= STARTF_USESTDHANDLES;

    // Create the child process.
    success = CreateProcessA(NULL,
                             pconfig->process_cmd_line_,     // command line
                             NULL,          // process security attributes
                             NULL,          // primary thread security attributes
                             TRUE,          // handles are inherited
                             CREATE_NEW_PROCESS_GROUP,             // creation flags
                             NULL,          // use parent's environment
                             NULL,          // use parent's current directory
                             &start_info,  // _STARTUPINFOW pointer
                             pproc_info);  // receives PROCESS_INFORMATION

    // If an error occurs, exit the application.
    if (!success) {
        free(pproc_info);
        g_pchild_proc_info = NULL;
        ErrorExit(TEXT("CreateProcess"));
    } else {
        g_pchild_proc_info = pproc_info;
    }

    return success;
}
Пример #26
0
LinphoneManager::LinphoneManager()
{
	m_linphoneStatus = LINPHONE_STATUS_NOT_INIT;
	pthread_mutex_init(&m_linphoneStatusMutex,NULL);
	SECURITY_ATTRIBUTES rPipeSa;
	SECURITY_ATTRIBUTES wPipeSa;
	rPipeSa.nLength = sizeof(SECURITY_ATTRIBUTES);
	rPipeSa.lpSecurityDescriptor = NULL;
	rPipeSa.bInheritHandle = TRUE;
	wPipeSa.nLength = sizeof(SECURITY_ATTRIBUTES);
	wPipeSa.lpSecurityDescriptor = NULL;
	wPipeSa.bInheritHandle = TRUE;
	if(!CreatePipe(&m_pipeRead[0],&m_pipeWrite[0],&rPipeSa,0))
	{
		log_printf(LOG_ALL_OUT,LOG_LEVEL_ERROR,"error at create pipe\n");
	}
	if(!CreatePipe(&m_pipeRead[1],&m_pipeWrite[1],&wPipeSa,0))
	{
		log_printf(LOG_ALL_OUT,LOG_LEVEL_ERROR,"error at create pipe\n");
	}
	STARTUPINFOA si;
	si.cb = sizeof(STARTUPINFOA);
	GetStartupInfoA(&si);
	si.hStdError = m_pipeWrite[0];
	si.hStdOutput = m_pipeWrite[0];
	si.hStdInput = m_pipeRead[1];
	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
	log_printf(LOG_ALL_OUT,LOG_LEVEL_INFO,"start to create linphone process.\n");
	if (!CreateProcessA(NULL,LINPHONEC_LOCATION,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&m_linphoneProcess)) 
	{
		log_printf(LOG_ALL_OUT,LOG_LEVEL_ERROR,"error at create process\n");
	}
	CloseHandle(m_pipeWrite[0]);
	CloseHandle(m_pipeRead[1]);
	SetLinphoneStatus(LINPHONE_STATUS_ON_IDLE);
	int ret = pthread_create(&m_readLinphoneOutput,NULL,ReadLinphoneOutputProc,this);
	if(0 != ret)
	{
		log_printf(LOG_ALL_OUT,LOG_LEVEL_ERROR,"Create read linphone output thread failed,%d\n",ret);
	}
}
Пример #27
0
/**
 * Handles exceptions (useful for debugging).
 * Issues a DebugBreak() call if the process is being debugged (not really
 * useful - if the process is being debugged, this handler won't be invoked
 * anyway). If it is not, runs a debugger from GNUNET_DEBUGGER env var,
 * substituting first %u in it for PID, and the second one for the event,
 * that should be set once the debugger attaches itself (otherwise the
 * only way out of WaitForSingleObject() is to time out after 1 minute).
 */
LONG __stdcall
GNWinVEH (PEXCEPTION_POINTERS ExceptionInfo)
{
  char debugger[MAX_PATH + 1];
  char *debugger_env = NULL;
  if (IsDebuggerPresent ())
  {
    DebugBreak ();
    return EXCEPTION_CONTINUE_EXECUTION;
  }
  debugger_env = getenv ("GNUNET_DEBUGGER");
  if (debugger_env != NULL)
  {
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    HANDLE event;
    SECURITY_ATTRIBUTES sa;
    memset (&si, 0, sizeof (si));
    si.cb = sizeof (si);
    memset (&pi, 0, sizeof (pi));
    memset (&sa, 0, sizeof (sa));
    sa.nLength = sizeof (sa);
    sa.bInheritHandle = TRUE;
    event = CreateEvent (&sa, FALSE, FALSE, NULL);
    snprintf (debugger, MAX_PATH + 1, debugger_env, GetCurrentProcessId (), (uintptr_t) event);
    debugger[MAX_PATH] = '\0';
    if (0 != CreateProcessA (NULL, debugger, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
    {
      CloseHandle (pi.hProcess);
      CloseHandle (pi.hThread);
      WaitForSingleObject (event, 60000);
      CloseHandle (event);
      if (IsDebuggerPresent ())
      {
        return EXCEPTION_CONTINUE_EXECUTION;
      }
    }
    else
      CloseHandle (event);
  }
  return EXCEPTION_CONTINUE_SEARCH;
}
Пример #28
0
int execute_apktool(const char* path, const char* args)
{
	STARTUPINFOA si;
	PROCESS_INFORMATION pi;
	char cmd[MAX_PATH];
	BOOL ret;

	memset(&pi, 0, sizeof(pi));
	memset(&si, 0, sizeof(si));
	si.cb = sizeof(si);
	snprintf(cmd, sizeof(cmd), "cmd /C %s %s", path, args);

	ret = CreateProcessA(NULL, cmd, NULL, NULL, TRUE, 
		DETACHED_PROCESS, NULL, NULL, &si, &pi);
	WaitForSingleObject(pi.hProcess, INFINITE);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	return ret ? 0 : 1;
}
Пример #29
0
std::string createOcclusionGeometry(const std::string &meshname, aiNode *node, aiMesh *mesh)
{
	if(mesh->mNumFaces < 150) return "";

	STARTUPINFOA si = {};

	si.cb = sizeof(STARTUPINFOA);
	si.hStdOutput = (HANDLE)STD_OUTPUT_HANDLE;
	si.hStdInput  = (HANDLE)STD_INPUT_HANDLE;
	si.hStdError  = (HANDLE)STD_ERROR_HANDLE;
	si.dwFlags = STARTF_USESTDHANDLES;

	PROCESS_INFORMATION pi = {};

	std::string occlusionName = std::string("/Occlusion/") + node->mName.data + ".boccl";

	char args[1024];
	sprintf(
		args, 
		" -cli %s%s .%s", 
		g_Endianness == BigEndian ? "-bigendian " : "", 
		meshname.c_str(), 
		occlusionName.c_str()
	);

	BOOL result = CreateProcessA(
		(outdir + "/Oxel.exe").c_str(), 
		args, 
		NULL, NULL, FALSE, 0, NULL, outdir.c_str(), &si, &pi);

	if(result)
	{
		::WaitForSingleObject(pi.hProcess, INFINITE);
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
		printf("Done generating occlusion data %s\n", node->mName.data);
		return outdir + occlusionName;
	}

	return "";
}
Пример #30
-1
/**
 * @brief 运行进程函数
 * 创建经编译的代码的可执行文件进程
 *
 * @param exe 可执行文件文件名
 * @param input 进程输入文件名
 * @param output 进程输出文件名
 * @param cs 用于接收代码状态的引用
 * @param hInput 用于接收输入文件句柄
 * @param hOutput 用于接收输出文件句柄
 * @return 若进程创建成功则返回进程句柄,否则返回NULL
 */
HANDLE CNBUTOJCore::RunCode(const char *exe, const char *input, const char *output, CodeState &cs, HANDLE &hInput, HANDLE &hOutput, PROCESS_INFORMATION &inProcInfo)
{
    SECURITY_ATTRIBUTES sa;
    sa.bInheritHandle = true;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;

    /** 打开得到输入输出文件句柄 */
    hInput = hOutput = NULL;
    hInput = CreateFile(input, GENERIC_READ, NULL, &sa, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, NULL);
    hOutput = CreateFile(output, GENERIC_WRITE | GENERIC_READ, NULL,
        &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    //HANDLE hError = CreateFile(".err", GENERIC_WRITE | GENERIC_READ, NULL,
    //    &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if(NULL == hInput || NULL == hOutput)
    {
        cs.state = SYSTEM_ERROR;
        strcpy(cs.err_code, "File error.");

        return NULL;
    }

    PROCESS_INFORMATION ProcInfo;
    STARTUPINFO StartInfo = { sizeof(StartInfo) };
    StartInfo.cb = sizeof(StartInfo);
    StartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    StartInfo.hStdInput = hInput;
    StartInfo.hStdOutput = hOutput;
    StartInfo.wShowWindow = SW_HIDE;
    //StartInfo.hStdError = hError;

    /** 运行程序 */
    bool flag = CreateProcessA(exe, NULL, NULL,
        NULL, true, DEBUG_ONLY_THIS_PROCESS, NULL, NULL, &StartInfo, &ProcInfo);

    /** 若运行不成功 */
    if(!flag)
    {
        cs.state = SYSTEM_ERROR;
        strcpy(cs.err_code, "Can't create process.");

        return NULL;
    }

    cs.state = RUNNING;
    inProcInfo = ProcInfo;

    return ProcInfo.hProcess;
}