Debian Codegraph @

melder/melder_sysenv.cpp

raw symbols SCIP
1 /* melder_sysenv.cpp
2 *
3 * Copyright (C) 1992-2007,2011,2012,2015-2019,2023-2026 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #if defined (_WIN32)
20 #if ! defined (__CYGWIN__) && ! defined (__MINGW32__)
21 #include <crtl.h>
22 #endif
23 #include <fcntl.h>
24 #include <windows.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #else
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #endif
32 #include "melder.h"
33
34 conststring32 Melder_getenv (conststring32 variableName) {
35 #if defined (macintosh) || defined (UNIX) || defined (__MINGW32__) || defined (__CYGWIN__)
36 char *value = getenv (Melder_peek32to8 (variableName));
37 if (! value)
38 return nullptr;
39 return Melder_peek8to32_u (value);
40 #elif defined (_WIN32)
41 static char32 buffer [11] [255];
42 static int ibuffer = 0;
43 if (++ ibuffer == 11)
44 ibuffer = 0;
45 DWORD n = GetEnvironmentVariableW (variableName, buffer [ibuffer], 255); BUG
46 if (n == ERROR_ENVVAR_NOT_FOUND)
47 return nullptr;
48 return & buffer [ibuffer] [0];
49 #else
50 return nullptr;
51 #endif
52 }
53
54 /*
55 Command lines on Windows (mostly from https://learn.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments?view=msvc-170)
56
57 Command-line input argv[1] argv[2] argv[3] remarks
58 "a b c" d e a b c d e normal
59 "ab\"c" "\\" d ab"c \ d escaped "; escaped second \ as it's before "
60 a\\\b d"e f"g h a\\\b de fg h literal backslashes as not followed by "
61 a\\\"b c d a\"b c d escaped second \ as the backslashes are followed by "
62 a\\\\"b c" d e a\\b c d e escaped second and fourth \ as they're followed by ", which is a delimiter
63 a"b"" c d ab" c d unfinished sequence as closing " is missing
64 "back\slash\\" back\slash\
65 */
66
67 static autostring32 runAny_STR (
68 conststring32 procedureMessageName,
69 conststring32 command, // it's either this one...
70 conststring32 executableFileName, integer narg, char32 ** args, // ... or these three
71 bool collectStdout
72 ) {
73 if (! command)
74 command = U"";
75 /*
76 Create a pipe for stdout and a pipe for stderr.
77 */
78 #if defined (macintosh) || defined (UNIX)
79 int stdoutPipe [2], stderrPipe [2];
80 if (! Melder_asynchronous) {
81 if (collectStdout && pipe (stdoutPipe) == -1)
82 Melder_throw (procedureMessageName, U": cannot start system command <<", command, U">> (“pipe error”).");
83 if (pipe (stderrPipe) == -1)
84 Melder_throw (procedureMessageName, U": cannot start system command <<", command, U">> (“pipe error”).");
85 }
86 #elif defined (_WIN32)
87 HANDLE stdoutReadPipe = NULL, stdoutWritePipe = NULL, stderrReadPipe = NULL, stderrWritePipe = NULL;
88 if (! Melder_asynchronous) {
89 SECURITY_ATTRIBUTES securityAttributes;
90 securityAttributes. nLength = sizeof (SECURITY_ATTRIBUTES);
91 securityAttributes. bInheritHandle = TRUE;
92 securityAttributes. lpSecurityDescriptor = NULL;
93 if (collectStdout && ! CreatePipe (& stdoutReadPipe, & stdoutWritePipe, & securityAttributes, 0))
94 Melder_throw (procedureMessageName, U": cannot start system command <<", command, U">> (“pipe error”).");
95 if (! CreatePipe (& stderrReadPipe, & stderrWritePipe, & securityAttributes, 0))
96 Melder_throw (procedureMessageName, U": cannot start system command <<", command, U">> (“pipe error”).");
97 }
98 #endif
99 /*
100 Create a child process that shall run
101 /bin/sh with arguments: (1) argv[0] = "sh", (2) argv[1] = "-c", (3) argv[2..n] = command
102 or
103 cmd.exe /c command
104 attaching the stdout and stderr write pipes to the child process.
105 */
106 #if defined (macintosh) || defined (UNIX)
107 pid_t childProcess = fork ();
108 if (childProcess == -1)
109 Melder_throw (procedureMessageName, U": cannot start system command <<", command, U">> (“fork error”).");
110 if (childProcess == 0) {
111 /*
112 We are in the child process.
113 */
114 if (! Melder_asynchronous) {
115 while (collectStdout && (dup2 (stdoutPipe [1], STDOUT_FILENO) == -1) && (errno == EINTR)) { // attach stdout write pipe to child process
116 }
117 while ((dup2 (stderrPipe [1], STDERR_FILENO) == -1) && (errno == EINTR)) { // attach stderr write pipe to child process
118 }
119 if (collectStdout) {
120 close (stdoutPipe [1]);
121 close (stdoutPipe [0]);
122 }
123 close (stderrPipe [1]);
124 close (stderrPipe [0]);
125 }
126 if (executableFileName) {
127 autostring8vector args8 (narg + 2);
128 args8 [1] = Melder_32to8 (executableFileName);
129 for (integer i = 1; i <= narg; i ++) {
130 trace (U"Argument ", i, U": <<", args [i], U">>");
131 args8 [1 + i] = Melder_32to8 (args [i]);
132 }
133 args8 [narg + 2] = autostring8();
134 execvp (
135 Melder_peek32to8 (executableFileName),
136 & args8.peek2() [1]
137 );
138 } else {
139 //
140 // From the execl man page:
141 // int execl(const char *path, const char *arg0, ..., /*, (char *)0, */);
142 // With more quotes from the execl man page:
143 //
144 autostring8 command8 = Melder_32to8 (command);
145 execl (
146 "/bin/sh", // "The initial argument for these functions is the pathname of a file which is to be executed."
147 // "The const char *arg0 and subsequent ellipses in the execl(), execlp(), and execle() functions"
148 // "can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers"
149 // "to null-terminated strings that represent the argument list available to the executed program."
150 "sh", // "The first argument, by convention, should point to the file name associated with the file being executed."
151 // (that is, this is arg0, which should to sh become argv[0], which should generally be the app name)
152 "-c", // (from the bash man page: "If the -c option is present, then commands are read from `string`."; this is argv[1])
153 command8.get(), // (the `string`, combining the complete space-separated command that sh should execute)
154 nullptr // "The list of arguments *must* be terminated by a NULL pointer."
155 ); // if all goes right, this implicitly closes the child process
156 }
157 /*
158 If we arrive here, then execl or execvp must have returned,
159 which is an error condition.
160 */
161 _exit (EXIT_FAILURE); // close the child process explicitly
162 }
163 /*
164 We are in the parent process.
165 */
166 #elif defined (_WIN32)
167 STARTUPINFO siStartInfo;
168 memset (& siStartInfo, 0, sizeof (siStartInfo));
169 siStartInfo. cb = sizeof (siStartInfo);
170 if (! Melder_asynchronous) {
171 siStartInfo. dwFlags = STARTF_USESTDHANDLES;
172 if (collectStdout)
173 siStartInfo. hStdOutput = stdoutWritePipe; // attach stdout write pipe to child process
174 else
175 siStartInfo. hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE); // TODO: make this work in the Windows console, not just in Cygwin and MSYS
176 siStartInfo. hStdError = stderrWritePipe; // attach stderr write pipe to child process
177 }
178 PROCESS_INFORMATION piProcInfo;
179 memset (& piProcInfo, 0, sizeof (piProcInfo));
180 autoMelderString buffer;
181 if (executableFileName) {
182 MelderString_empty (& buffer);
183 MelderString_append (& buffer, U"\"", executableFileName, U"\"");
184 for (integer iarg = 1; iarg <= narg; iarg ++) {
185 MelderString_append (& buffer, U" \"");
186 for (const char32 *p = & args [iarg] [0]; *p != U'\0'; p ++) {
187 if (*p == U'"') {
188 MelderString_append (& buffer, U"\\\"");
189 } else if (*p == U'\\') {
190 /*
191 Count the backslashes.
192 */
193 const char32 *q = p + 1;
194 while (*q == '\\')
195 q ++;
196 const integer numberOfBackslashesInInput = q - p;
197 const bool backslashSequenceFollowedByDoubleQuote = ( *q == U'"' );
198 const bool backslashSequenceAtEnd = ( *q == U'\0' );
199 if (backslashSequenceFollowedByDoubleQuote || backslashSequenceAtEnd)
200 MelderString_append (& buffer, U"\\\\"); // double pre-quote and final backslashes
201 else
202 MelderString_append (& buffer, U"\\");
203 } else
204 MelderString_appendCharacter (& buffer, *p);
205 }
206 MelderString_appendCharacter (& buffer, U'"');
207 }
208 autostringW bufferW = Melder_32toW_fileSystem (buffer.string);
209 if (! CreateProcess (nullptr, bufferW.get(), nullptr, nullptr, true, CREATE_NO_WINDOW, nullptr, nullptr, & siStartInfo, & piProcInfo))
210 Melder_throw (procedureMessageName, U": cannot start subprocess <<", executableFileName, U">>.");
211 } else {
212 conststring32 comspec = Melder_getenv (U"COMSPEC"); // e.g. "C:\WINDOWS\COMMAND.COM" or "C:\WINNT\windows32\cmd.exe" or "C:\WINDOWS\system32\cmd.exe"
213 if (! comspec)
214 comspec = Melder_getenv (U"ComSpec");
215 if (! comspec)
216 comspec = U"cmd.exe";
217 MelderString_copy (& buffer, comspec);
218 Melder_assert (! str32chr (buffer.string, ' '));
219 MelderString_append (& buffer, U" /c ", command);
220 autostringW bufferW = Melder_32toW_fileSystem (buffer.string);
221 const bool shouldInheritHandles = ! Melder_asynchronous;
222 if (! CreateProcess (nullptr, bufferW.get(), nullptr, nullptr, shouldInheritHandles, CREATE_NO_WINDOW, nullptr, nullptr, & siStartInfo, & piProcInfo))
223 Melder_throw (procedureMessageName, U": cannot start system command <<", command, U">>.");
224 }
225 #endif
226 /*
227 Close the write pipes; no longer should anything be written to them.
228 */
229 if (! Melder_asynchronous) {
230 #if defined (macintosh) || defined (UNIX)
231 if (collectStdout)
232 close (stdoutPipe [1]);
233 close (stderrPipe [1]);
234 #elif defined (_WIN32)
235 if (collectStdout)
236 CloseHandle (stdoutWritePipe);
237 CloseHandle (stderrWritePipe);
238 #endif
239 }
240 /*
241 Collect the output of the child process.
242 */
243 autoMelderString stdout_string, stderr_string;
244 if (! Melder_asynchronous) {
245 char buffer8 [1+4096];
246 if (collectStdout)
247 for (;;) {
248 #if defined (macintosh) || defined (UNIX)
249 ssize_t count = read (stdoutPipe [0], buffer8, 4096);
250 #elif defined (_WIN32)
251 DWORD count;
252 BOOL success = ReadFile (stdoutReadPipe, buffer8, 4096, & count, NULL);
253 Melder_killReturns_inplace (buffer8);
254 #endif
255 if (count == 0) // on Windows, this has to go before the success test
256 break;
257 #if defined (macintosh) || defined (UNIX)
258 if (count == -1) {
259 if (errno == EINTR)
260 continue;
261 Melder_throw (procedureMessageName, U": error while handling child process output.");
262 }
263 #elif defined (_WIN32)
264 if (! success)
265 Melder_throw (procedureMessageName, U": error while handling child process output.");
266 #endif
267 buffer8 [count] = '\0';
268 MelderString_append (& stdout_string, Melder_peek8to32_u (buffer8));
269 }
270 for (;;) {
271 #if defined (macintosh) || defined (UNIX)
272 ssize_t count = read (stderrPipe [0], buffer8, 4096);
273 #elif defined (_WIN32)
274 DWORD count;
275 BOOL success = ReadFile (stderrReadPipe, buffer8, 4096, & count, NULL);
276 #endif
277 if (count == 0) // on Windows, this has to go before the success test
278 break;
279 #if defined (macintosh) || defined (UNIX)
280 if (count == -1) {
281 if (errno == EINTR)
282 continue;
283 Melder_throw (procedureMessageName, U": error while handling child process error output.");
284 }
285 #elif defined (_WIN32)
286 if (! success)
287 Melder_throw (procedureMessageName, U": error while handling child process error output.");
288 #endif
289 buffer8 [count] = '\0';
290 MelderString_append (& stderr_string, Melder_peek8to32_u (buffer8));
291 }
292 trace (U"read");
293 }
294 /*
295 Close the read pipes, which are no longer needed.
296 */
297 #if defined (macintosh) || defined (UNIX)
298 if (collectStdout)
299 close (stdoutPipe [0]);
300 close (stderrPipe [0]);
301 #elif defined (_WIN32)
302 if (collectStdout)
303 CloseHandle (stdoutReadPipe);
304 CloseHandle (stderrReadPipe);
305 #endif
306 /*
307 "Wait" for the child process to finish completely.
308 */
309 if (Melder_asynchronous) {
310 return autostring32 ();
311 } else {
312 #if defined (macintosh) || defined (UNIX)
313 int childProcessStatus;
314 waitpid (childProcess, & childProcessStatus, 0); // unzombie child process
315 if (! WIFEXITED (childProcessStatus))
316 Melder_throw (procedureMessageName, U": subprocess not exited (probably stopped by a signal):\n", stderr_string.string);
317 if (WEXITSTATUS (childProcessStatus) != 0)
318 Melder_throw (stderr_string.string, U".\n", procedureMessageName, U": subprocess exited with error ", WEXITSTATUS (childProcessStatus));
319 if (stderr_string.length > 0)
320 Melder_casual (procedureMessageName, U": casual message:\n", stderr_string.string);
321 #elif defined (_WIN32)
322 if (WaitForSingleObject (piProcInfo. hProcess, INFINITE) != 0)
323 Melder_throw (procedureMessageName, U": cannot finish system command <<", command, U">>.");
324 DWORD exitCode;
325 if (! GetExitCodeProcess (piProcInfo. hProcess, & exitCode))
326 Melder_throw (procedureMessageName, U": cannot evaluate system command <<", command, U">>.");
327 if (exitCode != 0)
328 Melder_throw (stderr_string.string, U".\n", procedureMessageName, U": subprocess exited with error ", (int) exitCode);
329 CloseHandle (piProcInfo. hProcess);
330 CloseHandle (piProcInfo. hThread);
331 #endif
332 return collectStdout ? Melder_dup (stdout_string.string) : autostring32 ();
333 }
334 }
335
336 autostring32 runSystem_STR (conststring32 command) {
337 return runAny_STR (U"runSystem$", command, nullptr, 0, nullptr, true);
338 }
339 void Melder_runSystem (conststring32 command) {
340 (void) runAny_STR (U"runSystem", command, nullptr, 0, nullptr, false);
341 }
342 autostring32 runSubprocess_STR (conststring32 executableFileName, integer narg, char32 ** args) {
343 return runAny_STR (U"runSubprocess$", nullptr, executableFileName, narg, args, true);
344 }
345 void Melder_runSubprocess (conststring32 executableFileName, integer narg, char32 ** args) {
346 (void) runAny_STR (U"runSubprocess", nullptr, executableFileName, narg, args, false);
347 }
348
349 /* End of file melder_sysenv.cpp */