Line data Source code
1 : #include "ProcessSpawn.h"
2 : #include "macros.h"
3 :
4 : #if !IS_WINDOWS
5 : #include <spawn.h>
6 : #include <sys/wait.h>
7 : #include <fcntl.h>
8 : #include <unistd.h>
9 : #include <cerrno>
10 : #include <filesystem>
11 :
12 : extern char** environ;
13 : #else
14 : #include <windows.h>
15 : #include <filesystem>
16 : #include <string>
17 : #endif
18 :
19 : namespace Utils
20 : {
21 : #if !IS_WINDOWS
22 :
23 6 : std::int64_t run_process(const std::string& program, const std::vector<std::string>& args, bool discardOutput /* = true*/)
24 : {
25 : // Build the child's argv: argv[0] is the program by convention. posix_spawnp
26 : // PATH-searches the program; every argument below is a distinct argv entry,
27 : // so no shell ever re-parses them (audit F001).
28 6 : std::vector<char*> argv;
29 6 : argv.reserve(args.size() + 2);
30 6 : argv.push_back(const_cast<char*>(program.c_str()));
31 19 : for (const auto& arg : args)
32 : {
33 13 : argv.push_back(const_cast<char*>(arg.c_str()));
34 : }
35 6 : argv.push_back(nullptr);
36 :
37 : posix_spawn_file_actions_t actions;
38 6 : posix_spawn_file_actions_init(&actions);
39 6 : if (discardOutput)
40 : {
41 : // connect stdin/stdout/stderr to /dev/null inside the child
42 6 : posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
43 6 : posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null", O_WRONLY, 0);
44 6 : posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null", O_WRONLY, 0);
45 : }
46 :
47 6 : pid_t pid = -1;
48 6 : const int spawnResult = posix_spawnp(&pid, program.c_str(), &actions, nullptr, argv.data(), environ);
49 6 : posix_spawn_file_actions_destroy(&actions);
50 :
51 6 : if (spawnResult != 0)
52 : {
53 1 : return -1;
54 : }
55 :
56 5 : int status = 0;
57 : // EINTR: a signal during the blocking wait is not a child failure -
58 : // retry until waitpid gives a real verdict, else the child zombies
59 : // and we report a bogus "could not start" error
60 : int waitResult;
61 : do
62 : {
63 5 : waitResult = waitpid(pid, &status, 0);
64 5 : } while (waitResult == -1 && errno == EINTR);
65 :
66 5 : if (waitResult == -1)
67 : {
68 0 : return -1;
69 : }
70 5 : if (WIFEXITED(status))
71 : {
72 5 : return WEXITSTATUS(status);
73 : }
74 0 : if (WIFSIGNALED(status))
75 : {
76 : // shell convention: 128+signal, positive and distinct from the
77 : // -1 "could not start" sentinel (a crashed child is a command
78 : // failure, not a spawn failure)
79 0 : return 128 + WTERMSIG(status);
80 : }
81 0 : return -1;
82 6 : }
83 :
84 : #else // IS_WINDOWS
85 :
86 : namespace
87 : {
88 : // CreateProcessW takes one command-line STRING, not an argv array, so the
89 : // arguments must be quoted with the standard Windows rules (MSDN
90 : // "Parsing C++ Command-Line Arguments"): wrap in quotes when the argument
91 : // contains space/tab/quote, and double any embedded backslashes that
92 : // precede a quote. There is still no shell involved - cmd-style
93 : // metacharacters (&, |, >, ;) inside a quoted argument are literal.
94 : std::wstring quote_windows_argument(const std::wstring& argument)
95 : {
96 : if (!argument.empty() && argument.find_first_of(L" \t\"") == std::wstring::npos)
97 : {
98 : return argument;
99 : }
100 :
101 : std::wstring quoted;
102 : quoted.reserve(argument.size() + 2);
103 : quoted.push_back(L'"');
104 : std::size_t backslashRun = 0;
105 : for (const auto c : argument)
106 : {
107 : if (c == L'\\')
108 : {
109 : ++backslashRun;
110 : continue;
111 : }
112 : if (c == L'"')
113 : {
114 : // double the backslashes that end a run before the quote, then
115 : // escape the quote itself
116 : quoted.append(backslashRun * 2, L'\\');
117 : quoted += L"\\\"";
118 : }
119 : else
120 : {
121 : quoted.append(backslashRun, L'\\');
122 : quoted.push_back(c);
123 : }
124 : backslashRun = 0;
125 : }
126 : quoted.append(backslashRun * 2, L'\\');
127 : quoted.push_back(L'"');
128 : return quoted;
129 : }
130 : }
131 :
132 : std::int64_t run_process(const std::string& program, const std::vector<std::string>& args, bool discardOutput /* = true*/)
133 : {
134 : // widen via std::filesystem::path so the conversion matches however
135 : // the system encoded the string in the first place (path::string() on
136 : // Windows uses the active ANSI code page; path(string) inverts it).
137 : // Byte-wise wstring construction would mangle every non-ASCII path.
138 : // the program token must be quoted too: with lpApplicationName NULL,
139 : // CreateProcessW resolves the executable by whitespace-prefix
140 : // progression over the head of the command line, so an unquoted
141 : // "C:\Program Files\...\7z.exe" mis-resolves
142 : std::wstring commandLine = quote_windows_argument(std::filesystem::path(program).wstring());
143 : for (const auto& arg : args)
144 : {
145 : commandLine += L" ";
146 : commandLine += quote_windows_argument(std::filesystem::path(arg).wstring());
147 : }
148 :
149 : // NUL-device handles for the child's streams
150 : STARTUPINFOW startupInfo{};
151 : startupInfo.cb = sizeof(startupInfo);
152 : SECURITY_ATTRIBUTES inheritable{ sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE };
153 : HANDLE nullOutput = INVALID_HANDLE_VALUE;
154 : HANDLE nullInput = INVALID_HANDLE_VALUE;
155 : if (discardOutput)
156 : {
157 : startupInfo.dwFlags = STARTF_USESTDHANDLES;
158 : nullInput = CreateFileW(L"NUL", GENERIC_READ, 0, &inheritable, OPEN_EXISTING, 0, nullptr);
159 : nullOutput = CreateFileW(L"NUL", GENERIC_WRITE, 0, &inheritable, OPEN_EXISTING, 0, nullptr);
160 : startupInfo.hStdInput = nullInput;
161 : startupInfo.hStdOutput = nullOutput;
162 : startupInfo.hStdError = nullOutput;
163 : }
164 :
165 : PROCESS_INFORMATION processInfo{};
166 : const BOOL created = CreateProcessW(
167 : nullptr,
168 : commandLine.data(),
169 : nullptr,
170 : nullptr,
171 : discardOutput ? TRUE : FALSE,
172 : CREATE_NO_WINDOW,
173 : nullptr,
174 : nullptr,
175 : &startupInfo,
176 : &processInfo);
177 :
178 : if (nullInput != INVALID_HANDLE_VALUE) CloseHandle(nullInput);
179 : if (nullOutput != INVALID_HANDLE_VALUE) CloseHandle(nullOutput);
180 :
181 : if (!created)
182 : {
183 : return -1;
184 : }
185 :
186 : DWORD exitCode = 0;
187 : WaitForSingleObject(processInfo.hProcess, INFINITE);
188 : const BOOL gotExitCode = GetExitCodeProcess(processInfo.hProcess, &exitCode);
189 : CloseHandle(processInfo.hThread);
190 : CloseHandle(processInfo.hProcess);
191 :
192 : if (!gotExitCode)
193 : {
194 : // exit status undeterminable - report the spawn-failure class
195 : return -1;
196 : }
197 : // zero-extend the unsigned 32-bit code into int64: crash codes like
198 : // 0xC0000005 stay positive (command failure) instead of colliding
199 : // with the -1 "could not start" sentinel
200 : return static_cast<std::int64_t>(exitCode);
201 : }
202 :
203 : #endif // IS_WINDOWS
204 : }
|