forked from kiennq/scoop-better-shimexe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shim.cpp
294 lines (243 loc) · 7.9 KB
/
shim.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#include <corecrt_wstdio.h>
#pragma comment(lib, "SHELL32.LIB")
#pragma comment(lib, "SHLWAPI.LIB")
#include <windows.h>
#include <shlwapi.h>
#include <stdio.h>
#include <string>
#include <string_view>
#include <tuple>
#include <optional>
#include <memory>
#include <vector>
#ifndef ERROR_ELEVATION_REQUIRED
#define ERROR_ELEVATION_REQUIRED 740
#endif
using namespace std::string_view_literals;
BOOL WINAPI CtrlHandler(DWORD ctrlType)
{
switch (ctrlType)
{
// Ignore all events, and let the child process
// handle them.
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_SHUTDOWN_EVENT:
return TRUE;
default:
return FALSE;
}
}
struct HandleDeleter
{
typedef HANDLE pointer;
void operator() (HANDLE handle)
{
if (handle)
{
CloseHandle(handle);
}
}
};
namespace std
{
typedef unique_ptr<HANDLE, HandleDeleter> unique_handle;
typedef optional<wstring> wstring_p;
}
struct ShimInfo
{
std::wstring_p path;
std::wstring_p args;
};
std::wstring_view GetDirectory(std::wstring_view exe)
{
auto pos = exe.find_last_of(L"\\/");
return exe.substr(0, pos);
}
std::wstring_p NormalizeArgs(std::wstring_p& args, std::wstring_view curDir)
{
static constexpr auto s_dirPlaceHolder = L"%~dp0"sv;
if (!args)
{
return args;
}
auto pos = args->find(s_dirPlaceHolder);
if (pos != std::wstring::npos)
{
args->replace(pos, s_dirPlaceHolder.size(), curDir.data(), curDir.size());
}
return args;
}
ShimInfo GetShimInfo()
{
// Find filename of current executable.
wchar_t filename[MAX_PATH + 2];
const auto filenameSize = GetModuleFileNameW(nullptr, filename, MAX_PATH);
if (filenameSize >= MAX_PATH)
{
fprintf(stderr, "Shim: The filename of the program is too long to handle.\n");
return {std::nullopt, std::nullopt};
}
// Use filename of current executable to find .shim
wmemcpy(filename + filenameSize - 3, L"shim", 4U);
filename[filenameSize + 1] = L'\0';
FILE* fp = nullptr;
if (_wfopen_s(&fp, filename, L"r,ccs=UTF-8") != 0)
{
fprintf(stderr, "Cannot open shim file for read.\n");
return {std::nullopt, std::nullopt};
}
std::unique_ptr<FILE, decltype(&fclose)> shimFile(fp, &fclose);
// Read shim
wchar_t linebuf[1<<14];
std::wstring_p path;
std::wstring_p args;
while (true)
{
if (!fgetws(linebuf, ARRAYSIZE(linebuf), shimFile.get()))
{
break;
}
std::wstring_view line(linebuf);
if ((line.size() < 7) || (line.substr(4, 3) != L" = "))
{
continue;
}
if (line.substr(0, 4) == L"path")
{
std::wstring_view line_substr = line.substr(7);
if (line_substr.find(L" ") != std::wstring_view::npos && line_substr.front() != L'"')
{
path.emplace(L"\"");
auto& path_value = path.value();
path_value.append(line_substr.data(), line_substr.size() - (line.back() == L'\n' ? 1 : 0));
path_value.push_back(L'"');
}
else
{
path.emplace(line_substr.data(), line_substr.size() - (line.back() == L'\n' ? 1 : 0));
}
continue;
}
if (line.substr(0, 4) == L"args")
{
args.emplace(line.data() + 7, line.size() - 7 - (line.back() == L'\n' ? 1 : 0));
continue;
}
}
return {path, NormalizeArgs(args, GetDirectory(filename))};
}
std::tuple<std::unique_handle, std::unique_handle> MakeProcess(ShimInfo const& info)
{
// Start subprocess
STARTUPINFOW si = {};
PROCESS_INFORMATION pi = {};
auto&& [path, args] = info;
std::vector<wchar_t> cmd(path->size() + args->size() + 2);
wmemcpy(cmd.data(), path->c_str(), path->size());
cmd[path->size()] = L' ';
wmemcpy(cmd.data() + path->size() + 1, args->c_str(), args->size());
cmd[path->size() + 1 + args->size()] = L'\0';
std::unique_handle threadHandle;
std::unique_handle processHandle;
GetStartupInfoW(&si);
if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, TRUE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi))
{
threadHandle.reset(pi.hThread);
processHandle.reset(pi.hProcess);
ResumeThread(threadHandle.get());
}
else
{
if (GetLastError() == ERROR_ELEVATION_REQUIRED)
{
// We must elevate the process, which is (basically) impossible with
// CreateProcess, and therefore we fallback to ShellExecuteEx,
// which CAN create elevated processes, at the cost of opening a new separate
// window.
// Theorically, this could be fixed (or rather, worked around) using pipes
// and IPC, but... this is a question for another day.
SHELLEXECUTEINFOW sei = {};
sei.cbSize = sizeof(SHELLEXECUTEINFOW);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpFile = path->c_str();
sei.lpParameters = args->c_str();
sei.nShow = SW_SHOW;
if (!ShellExecuteExW(&sei))
{
fprintf(stderr, "Shim: Unable to create elevated process: error %li.", GetLastError());
return {std::move(processHandle), std::move(threadHandle)};
}
processHandle.reset(sei.hProcess);
}
else
{
fprintf(stderr, "Shim: Could not create process with command '%ls'.\n", cmd.data());
return {std::move(processHandle), std::move(threadHandle)};
}
}
// Ignore Ctrl-C and other signals
if (!SetConsoleCtrlHandler(CtrlHandler, TRUE))
{
fprintf(stderr, "Shim: Could not set control handler; Ctrl-C behavior may be invalid.\n");
}
return {std::move(processHandle), std::move(threadHandle)};
}
int wmain(int argc, wchar_t* argv[])
{
auto [path, args] = GetShimInfo();
if (!path)
{
fprintf(stderr, "Could not read shim file.\n");
return 1;
}
if (!args)
{
args.emplace();
}
auto cmd = GetCommandLineW();
if (cmd[0] == L'\"')
{
args->append(cmd + wcslen(argv[0]) + 2);
}
else
{
args->append(cmd + wcslen(argv[0]));
}
// Find out if the target program is a console app
wchar_t unquotedPath[MAX_PATH] = {};
wmemcpy(unquotedPath, path->c_str(), path->length());
PathUnquoteSpacesW(unquotedPath);
SHFILEINFOW sfi = {};
const auto ret = SHGetFileInfoW(unquotedPath, -1, &sfi, sizeof(sfi), SHGFI_EXETYPE);
if (ret == 0)
{
fprintf(stderr, "Shim: Could not determine if target is a GUI app. Assuming console.\n");
}
const auto isWindowsApp = HIWORD(ret) != 0;
if (isWindowsApp)
{
// Unfortunately, this technique will still show a window for a fraction of time,
// but there's just no workaround.
FreeConsole();
}
// Create job object, which can be attached to child processes
// to make sure they terminate when the parent terminates as well.
std::unique_handle jobHandle(CreateJobObject(nullptr, nullptr));
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = {};
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
SetInformationJobObject(jobHandle.get(), JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
auto [processHandle, threadHandle] = MakeProcess({path, args});
if (processHandle && !isWindowsApp)
{
AssignProcessToJobObject(jobHandle.get(), processHandle.get());
// Wait till end of process
WaitForSingleObject(processHandle.get(), INFINITE);
DWORD exitCode = 0;
GetExitCodeProcess(processHandle.get(), &exitCode);
return exitCode;
}
return processHandle ? 0 : 1;
}