1 // Copyright (c) 2011-2016 Ryan Prichard
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to
5 // deal in the Software without restriction, including without limitation the
6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 // sell copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 #include "AgentLocation.h"
27 #include "../shared/WinptyAssert.h"
29 #include "LibWinptyException.h"
31 #define AGENT_EXE L"winpty-agent.exe"
33 static HMODULE getCurrentModule() {
35 if (!GetModuleHandleExW(
36 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
37 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
38 reinterpret_cast<LPCWSTR>(getCurrentModule),
40 ASSERT(false && "GetModuleHandleEx failed");
45 static std::wstring getModuleFileName(HMODULE module) {
46 const int bufsize = 4096;
47 wchar_t path[bufsize];
48 int size = GetModuleFileNameW(module, path, bufsize);
49 ASSERT(size != 0 && size != bufsize);
50 return std::wstring(path);
53 static std::wstring dirname(const std::wstring &path) {
54 std::wstring::size_type pos = path.find_last_of(L"\\/");
55 if (pos == std::wstring::npos) {
58 return path.substr(0, pos);
62 static bool pathExists(const std::wstring &path) {
63 return GetFileAttributesW(path.c_str()) != 0xFFFFFFFF;
66 std::wstring findAgentProgram() {
67 std::wstring progDir = dirname(getModuleFileName(getCurrentModule()));
68 std::wstring ret = progDir + (L"\\" AGENT_EXE);
69 if (!pathExists(ret)) {
70 throw LibWinptyException(
71 WINPTY_ERROR_AGENT_EXE_MISSING,
72 (L"agent executable does not exist: '" + ret + L"'").c_str());