Exemplo n.º 1
0
void CChordEaseApp::WinHelp(DWORD dwData, UINT nCmd) 
{
//printf("dwData=%d:%d nCmd=%d\n", HIWORD(dwData), LOWORD(dwData), nCmd);
	CPathStr	HelpPath(GetAppFolder());
	HelpPath.Append(CString(m_pszAppName) + _T(".chm"));
	HWND	hMainWnd = GetMain()->m_hWnd;
	UINT	ResID = LOWORD(dwData);
	int	HelpID = FindHelpID(ResID);
	HWND	hWnd = 0;	// assume failure
	if (HelpID)	// if context help ID was found
		hWnd = ::HtmlHelp(hMainWnd, HelpPath, HH_HELP_CONTEXT, HelpID);
	if (!hWnd) {	// if context help wasn't available or failed
		hWnd = ::HtmlHelp(hMainWnd, HelpPath, HH_DISPLAY_TOC, 0);	// show contents
		if (!hWnd) {	// if help file not found
			CString	s;
			AfxFormatString1(s, IDS_APP_HELP_FILE_MISSING, HelpPath);
			AfxMessageBox(s);
			return;
		}
	}
	// ThreadBoost DLL boosts priority of MIDI input callbacks, but also boosts
	// other normal threads, including HtmlHelp's, which is counterproductive
	if (m_ThreadBoost.IsLoaded()) {	// if boosting normal priority threads
		DWORD	ThreadID = GetWindowThreadProcessId(hWnd, NULL);
		// obtain set info access to HtmlHelp's thread and set its priority to normal
		CSafeHandle	hThread(OpenThread(THREAD_SET_INFORMATION, FALSE, ThreadID));
		if (hThread == NULL || !::SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL))
			AfxMessageBox(GetLastErrorString());
	}
	m_HelpInit = TRUE;
}
Exemplo n.º 2
0
	Process Process::Create(const TChar* commandLine, CreationFlags flags)
	{
		STARTUPINFO startupInfo = {0};
		startupInfo.cb = sizeof(startupInfo);

		PROCESS_INFORMATION processInfo = {0};
		String buffer(commandLine);

		BOOL success = CreateProcess(
			NULL,                    // The name of the module to be executed
			buffer.GetBuffer(),      // The command line to be executed
			NULL,                    // Process handle is not inheritable
			NULL,                    // Thread handle is not inheritable
			FALSE,                   // Set handle inheritance to FALSE
			(DWORD)flags,            // Creation flags
			NULL,                    // Use parent's environment block
			NULL,                    // Use parent's starting directory 
			&startupInfo,            // Pointer to STARTUPINFO structure
			&processInfo);           // Pointer to PROCESS_INFORMATION structure
		
		if (!success)
		{
			THROW_LAST_ERROR_EXCEPTION();
		}

		Handle hThread(processInfo.hThread);
		Handle hProcess(processInfo.hProcess);
		return Process(processInfo.dwProcessId, std::move(hProcess));
	}
NS_IMETHODIMP
InjectCrashRunnable::Run()
{
  if (mInjectorPath.IsEmpty())
    return NS_OK;

  nsAutoHandle hProcess(
    OpenProcess(PROCESS_CREATE_THREAD |
                PROCESS_QUERY_INFORMATION |
                PROCESS_DUP_HANDLE |
                PROCESS_VM_OPERATION |
                PROCESS_VM_WRITE |
                PROCESS_VM_READ, FALSE, mPID));
  if (!hProcess) {
    NS_WARNING("Unable to open remote process handle for crashreporter injection.");
    return NS_OK;
  }

  void* proc = LoadRemoteLibraryAndGetAddress(hProcess, mInjectorPath.get(),
                                              "Start");
  if (!proc) {
    NS_WARNING("Unable to inject crashreporter DLL.");
    return NS_OK;
  }

  HANDLE hRemotePipe =
    CrashGenerationClient::DuplicatePipeToClientProcess(
      NS_ConvertASCIItoUTF16(GetChildNotificationPipe()).get(),
      hProcess);
  if (INVALID_HANDLE_VALUE == hRemotePipe) {
    NS_WARNING("Unable to duplicate crash reporter pipe to process.");
    return NS_OK;
  }

  nsAutoHandle hThread(CreateRemoteThread(hProcess, NULL, 0,
                                          (LPTHREAD_START_ROUTINE) proc,
                                          (void*) hRemotePipe, 0, NULL));
  if (!hThread) {
    NS_WARNING("Unable to CreateRemoteThread");

    // We have to close the remote pipe or else our crash generation client
    // will be stuck unable to accept other remote requests.
    HANDLE toClose = INVALID_HANDLE_VALUE;
    if (DuplicateHandle(hProcess, hRemotePipe, ::GetCurrentProcess(),
                        &toClose, 0, FALSE,
                        DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
      CloseHandle(toClose);
      return NS_OK;
    }
  }

  return NS_OK;
}
Exemplo n.º 4
0
//--------------------------------------------------------------------------
VeThreadHandle VeCreateThread(VeThreadCallback pfuncThreadProc,
	void* pvParam, int32_t i32Priority, size_t stStackSize) noexcept
{
#ifdef  BUILD_PLATFORM_WIN
	VeThreadHandle hRes = (VeThreadHandle)_beginthreadex(NULL,
		(unsigned int)stStackSize, pfuncThreadProc, pvParam, 0, NULL);
	SetThreadPriority(hRes, i32Priority);
	return hRes;
#else
	VeThreadHandle hThread(0);
	pthread_attr_t kAttr;
	pthread_attr_init(&kAttr);
	sched_param kParam;
	pthread_attr_getschedparam(&kAttr, &kParam);
	kParam.sched_priority = i32Priority;
	pthread_attr_setschedparam(&kAttr, &kParam);
	pthread_attr_setstacksize(&kAttr, stStackSize ? stStackSize : 4096);
	pthread_create(&hThread, &kAttr, pfuncThreadProc, pvParam);
	return hThread;
#endif
}
Exemplo n.º 5
0
//--------------------------------------------------------------------------
VeThreadHandle VeCreateThread(VeThreadCallback pfuncThreadProc,
                              void* pvParam, VeUInt32 u32Priority, VeSizeT stStackSize)
{
#if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM)
    VeThreadHandle hRes = (VeThreadHandle)_beginthreadex(NULL,
                          (unsigned int)stStackSize, pfuncThreadProc, pvParam, 0, NULL);
    SetThreadPriority(hRes, u32Priority);
    return hRes;
#else
    VeThreadHandle hThread(0);
    pthread_attr_t kAttr;
    pthread_attr_init(&kAttr);
    sched_param kParam;
    pthread_attr_getschedparam(&kAttr, &kParam);
    kParam.sched_priority = u32Priority;
    pthread_attr_setschedparam(&kAttr, &kParam);
    pthread_attr_setstacksize(&kAttr, stStackSize ? stStackSize : 4096);
    pthread_create(&hThread, &kAttr, pfuncThreadProc, pvParam);
    return hThread;
#endif
}
Exemplo n.º 6
0
int wmain(int argc, wchar_t* argv[])
{
    // Initialize COM and deinitialize when we go out of scope
    HRESULT hrCoInit = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    shared_ptr<HRESULT> spCoInit(&hrCoInit, [](const HRESULT* hrCom) -> void { if (SUCCEEDED(*hrCom)) { ::CoUninitialize(); } });
    {
        // Set a close handler to shutdown the chrome instance we launch
        ::SetConsoleCtrlHandler(OnClose, TRUE);

        // Launch chrome
        {
            CString chromePath;

            // Find the chrome install location via the registry
            CString keyPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";

            CRegKey regKey;

            // First see if we can find where Chrome is installed from the registry. This will only succeed if Chrome is installed for all users
            if (regKey.Open(HKEY_LOCAL_MACHINE, keyPath, KEY_READ) == ERROR_SUCCESS)
            {
                ULONG bufferSize = MAX_PATH;
                CString path;
                LRESULT result = regKey.QueryStringValue(nullptr, path.GetBufferSetLength(bufferSize), &bufferSize);
                path.ReleaseBufferSetLength(bufferSize);
                if (result == ERROR_SUCCESS)
                {
                    chromePath = path;
                }
            }

            if (chromePath.GetLength() == 0)
            {
                // If Chrome is only installed for the current user, look in \AppData\Local\Google\Chrome\Application\ for Chrome.exe
                CString appPath;
                ::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appPath.GetBuffer(MAX_PATH + 1));
                appPath.ReleaseBuffer();
                chromePath = appPath + L"\\Google\\Chrome\\Application\\chrome.exe";
            }

            // Get a temp location
            CString temp;
            Helpers::ExpandEnvironmentString(L"%Temp%", temp);

            // Set arguments for the chrome that we launch
            CString arguments;
            arguments.Format(L"about:blank --remote-debugging-port=9223 --window-size=0,0 --silent-launch --no-first-run --no-default-browser-check --user-data-dir=\"%s\"", temp);

            // Launch the process
            STARTUPINFO si = { 0 };
            PROCESS_INFORMATION pi = { 0 };
            si.cb = sizeof(si);
            si.wShowWindow = SW_MINIMIZE;

            BOOL result = ::CreateProcess(
                chromePath,
                arguments.GetBuffer(),
                nullptr,
                nullptr,
                FALSE,
                0,
                nullptr,
                temp,
                &si,
                &pi);
            arguments.ReleaseBuffer();

            if (result)
            {
                // Store the handles
                CHandle hThread(pi.hThread);
                hChromeProcess.Attach(pi.hProcess);
                DWORD waitResult = ::WaitForInputIdle(hChromeProcess, 30000);
            }
            else
            {
                std::cerr << "Could not open Chrome. Please ensure that Chrome is installed." << std::endl;
                system("pause");
                return -1;
            }
        }
        
        // Get the current path that we are running from
        CString fullPath;
        DWORD count = ::GetModuleFileName(nullptr, fullPath.GetBuffer(MAX_PATH), MAX_PATH);
        fullPath.ReleaseBufferSetLength(count);

        LPWSTR buffer = fullPath.GetBuffer();
        LPWSTR newPath = ::PathFindFileName(buffer);
        if (newPath && newPath != buffer)
        {
            fullPath.ReleaseBufferSetLength((newPath - buffer));
        }
        else
        {
            fullPath.ReleaseBuffer();
        }

        // Load the proxy server
        IEDiagnosticsAdapter proxy(fullPath);

        // Create a message pump
        MSG msg;
        ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

        // Thread message loop
        BOOL getMessageRet;
        while ((getMessageRet = ::GetMessage(&msg, NULL, 0, 0)) != 0)
        {
            if (getMessageRet != -1)
            {
                ::TranslateMessage(&msg);
                ::DispatchMessage(&msg);
            }
        }

        // Leave the window open so we can read the log file
        wcout << endl << L"Press [ENTER] to exit." << endl;
        cin.ignore();
    }

    return 0;
}
int wmain(int argc, wchar_t* argv[])
{
	//::MessageBox(NULL, L"Stop here", L"STOP!", MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON3);

	std:cout << "Edge Diagnostics Adapter" << std::endl;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "Prints this help text.")
		("launch,l", po::value<string>(), "Launches Edge. Optionally at the URL specified in the value")
		("killall,k", "Kills all running Edge processes.")
		("chrome,c", "Launches Crhome in the background to serve the Chrome Developer Tools frontend.")
		("port,p", po::value<string>(), "The port number to listen on. Default is 9222.");

	po::variables_map vm;
	try
	{
		po::store(po::parse_command_line(argc, argv, desc), vm);
	}
	catch (po::error& e)
	{
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		std::cerr << desc << std::endl;
		return E_FAIL;
	}

	if (vm.count("help"))
	{
		std::cout << desc << std::endl;
		return S_OK;
	}


	// Initialize COM and deinitialize when we go out of scope
	HRESULT hrCoInit = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

	shared_ptr<HRESULT> spCoInit(&hrCoInit, [](const HRESULT* hrCom) -> void { if (SUCCEEDED(*hrCom)) { ::CoUninitialize(); } });
	{
		// Set a close handler to shutdown the chrome instance we launch
		::SetConsoleCtrlHandler(OnClose, TRUE);

		// Launch chrome
		if (vm.count("chrome"))
		{
			CString chromePath;

			// Find the chrome install location via the registry
			CString keyPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe";

			CRegKey regKey;

			// First see if we can find where Chrome is installed from the registry. This will only succeed if Chrome is installed for all users
			if (regKey.Open(HKEY_LOCAL_MACHINE, keyPath, KEY_READ) == ERROR_SUCCESS)
			{
				ULONG bufferSize = MAX_PATH;
				CString path;
				LRESULT result = regKey.QueryStringValue(nullptr, path.GetBufferSetLength(bufferSize), &bufferSize);
				path.ReleaseBufferSetLength(bufferSize);
				if (result == ERROR_SUCCESS)
				{
					chromePath = path;
				}
			}

			if (chromePath.GetLength() == 0)
			{
				// If Chrome is only installed for the current user, look in \AppData\Local\Google\Chrome\Application\ for Chrome.exe
				CString appPath;
				::SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appPath.GetBuffer(MAX_PATH + 1));
				appPath.ReleaseBuffer();
				chromePath = appPath + L"\\Google\\Chrome\\Application\\chrome.exe";
			}

			// Get a temp location
			CString temp;
			Helpers::ExpandEnvironmentString(L"%Temp%", temp);

			// Set arguments for the chrome that we launch
			CString arguments;
			arguments.Format(L"about:blank --remote-debugging-port=9223 --window-size=0,0 --silent-launch --no-first-run --no-default-browser-check --user-data-dir=\"%s\"", temp);

			// Launch the process
			STARTUPINFO si = { 0 };
			PROCESS_INFORMATION pi = { 0 };
			si.cb = sizeof(si);
			si.wShowWindow = SW_MINIMIZE;

			BOOL result = ::CreateProcess(
				chromePath,
				arguments.GetBuffer(),
				nullptr,
				nullptr,
				FALSE,
				0,
				nullptr,
				temp,
				&si,
				&pi);
			arguments.ReleaseBuffer();

			if (result)
			{
				// Store the handles
				CHandle hThread(pi.hThread);
				hChromeProcess.Attach(pi.hProcess);
				DWORD waitResult = ::WaitForInputIdle(hChromeProcess, 30000);
			}
			else
			{
				std::cerr << "Could not open Chrome. Please ensure that Chrome is installed." << std::endl;
				system("pause");
				return -1;
			}
		}

		// Kill all Edge instances if their is an aegument /killall
		if (vm.count("killall"))
		{
			//killAllProcessByExe(L"MicrosoftEdgeCP.exe");
			Helpers::KillAllProcessByExe(L"MicrosoftEdge.exe");
		}

		// Launch Edge if their is an argument set /launch:<url>
		if (vm.count("launch"))
		{
			CString url(vm["launch"].as<string>().c_str());
			if (url.GetLength() == 0)
			{
				url = L"https://www.bing.com";
			}

			HRESULT hr = Helpers::OpenUrlInMicrosoftEdge(url);

			if (FAILED(hr))
			{
				std::cout << L"Failed to launch Microsoft Edge";
			}
		}

		string port = EdgeDiagnosticsAdapter::s_Default_Port;
		if (vm.count("port"))
		{
			port = vm["port"].as<string>();
		}

		// We don't care if this fails as the developer can set it manually.
		setSecurityACLs();

		// We don't care if this fails or not as maybe the developer wants to do something that won't hit the PLM. In case errors went to the console.
		setEdgeForDebugging(true);

		// Load the proxy server
		EdgeDiagnosticsAdapter proxy(getPathToCurrentExeContainer(), port);

		if (proxy.IsServerRunning)
		{

			// Create a message pump
			MSG msg;
			::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

			// Thread message loop
			BOOL getMessageRet;
			while ((getMessageRet = ::GetMessage(&msg, NULL, 0, 0)) != 0)
			{
				if (getMessageRet != -1)
				{
					::TranslateMessage(&msg);
					::DispatchMessage(&msg);
				}
			}

			// Leave the window open so we can read the log file
			wcout << endl << L"Press [ENTER] to exit." << endl;
			cin.ignore();
		}
		else
		{
			wcout << L"Error starting. Quiting.";
			return E_FAIL;
		}
	}

	return S_OK;
}