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"cxx . . $ `<file>/melder/melder.h`/
33
34 conststring32cxx . . $ conststring32# Melder_getenvcxx . . $ Melder_getenv(5553299aa8c4fee9). (conststring32cxx . . $ conststring32# variableName) {
35 #if defined (macintosh) || defined (UNIXcxx . . $ `<built-in>:479:9`!) || defined (__MINGW32__) || defined (__CYGWIN__)
36 char *value = getenvcxx . . $ getenv(c63359b659779399). (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 autostring32cxx . . $ autostring32# runAny_STRcxx . . $ runAny_STR(5c2a62d3743e2946). (
68 conststring32cxx . . $ conststring32# procedureMessageName,
69 conststring32cxx . . $ conststring32# command, // it's either this one...
70 conststring32cxx . . $ conststring32# executableFileName, integercxx . . $ integer# narg, char32cxx . . $ 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 (UNIXcxx . . $ `<built-in>:479:9`!)
79 int stdoutPipe [2], stderrPipe [2];
80 if (! Melder_asynchronouscxx . . $ Melder_asynchronous.) {
81 if (collectStdout && pipe (stdoutPipe) == -1)
82 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (procedureMessageName, U": cannot start system command <<", command, U">> (“pipe error”).");
83 if (pipe (stderrPipe) == -1)
84 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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 (UNIXcxx . . $ `<built-in>:479:9`!)
107 pid_t childProcess = fork ();
108 if (childProcess == -1)
109 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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_asynchronouscxx . . $ Melder_asynchronous.) {
115 while (collectStdout && (dup2 (stdoutPipe [1], STDOUT_FILENOcxx . . $ `<external>/12628407106812493757/unistd.h:211:9`!) == -1) && (errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`! == EINTRcxx . . $ `<external>/8987895939074593727/errno-base.h:8:9`!)) { // attach stdout write pipe to child process
116 }
117 while ((dup2 (stderrPipe [1], STDERR_FILENOcxx . . $ `<external>/12628407106812493757/unistd.h:212:9`!) == -1) && (errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`! == EINTRcxx . . $ `<external>/8987895939074593727/errno-base.h:8:9`!)) { // 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 autostring8vectorcxx . . $ autostring8vector# args8cxx . . $ _autostringautovector#_autostringautovector(1624ee8275b10bda). (narg + 2);
128 args8 [cxx . . $ _autostringautovector#`operator[]`(f191be2b65019068).1] =cxx . . $ _autostring#`operator=`(f562943cbc4bcf37). Melder_32to8cxx . . $ Melder_32to8(d0484fb546b1094e). (executableFileName);
129 for (integercxx . . $ integer# i = 1; i <= narg; i ++) {
130 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"Argument ", i, U": <<", args [i], U">>");
131 args8 [cxx . . $ _autostringautovector#`operator[]`(f191be2b65019068).1 + i] =cxx . . $ _autostring#`operator=`(f562943cbc4bcf37). Melder_32to8cxx . . $ Melder_32to8(d0484fb546b1094e). (args [i]);
132 }
133 args8 [cxx . . $ _autostringautovector#`operator[]`(f191be2b65019068).narg + 2] =cxx . . $ _autostring#`operator=`(f562943cbc4bcf37). autostring8cxx . . $ _autostring#_autostring(49f6e7a06ebc5aa8).();
134 execvp (
135 Melder_peek32to8 (executableFileName),
136 & args8.peek2cxx . . $ _autostringautovector#peek2(3871cfe815cb200).() [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 autostring8cxx . . $ autostring8# command8 = Melder_32to8cxx . . $ Melder_32to8(d0484fb546b1094e). (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.getcxx . . $ _autostring#get(5a2a78a048fb49a8).(), // (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_FAILUREcxx . . $ `<external>/10696550936717951914/stdlib.h:92:9`!); // 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_asynchronouscxx . . $ Melder_asynchronous.) {
230 #if defined (macintosh) || defined (UNIXcxx . . $ `<built-in>:479:9`!)
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 autoMelderStringcxx . . $ autoMelderString# stdout_stringcxx . . $ autoMelderString#autoMelderString(49f6e7a06ebc5aa8)., stderr_stringcxx . . $ autoMelderString#autoMelderString(49f6e7a06ebc5aa8).;
244 if (! Melder_asynchronouscxx . . $ Melder_asynchronous.) {
245 char buffer8 [1+4096];
246 if (collectStdout)
247 for (;;) {
248 #if defined (macintosh) || defined (UNIXcxx . . $ `<built-in>:479:9`!)
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 (UNIXcxx . . $ `<built-in>:479:9`!)
258 if (count == -1) {
259 if (errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`! == EINTRcxx . . $ `<external>/8987895939074593727/errno-base.h:8:9`!)
260 continue;
261 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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_appendcxx . . $ MelderString_append(65be51a793e0ff96). (& stdout_string, Melder_peek8to32_u (buffer8));
269 }
270 for (;;) {
271 #if defined (macintosh) || defined (UNIXcxx . . $ `<built-in>:479:9`!)
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 (UNIXcxx . . $ `<built-in>:479:9`!)
280 if (count == -1) {
281 if (errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`! == EINTRcxx . . $ `<external>/8987895939074593727/errno-base.h:8:9`!)
282 continue;
283 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (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_appendcxx . . $ MelderString_append(65be51a793e0ff96). (& stderr_string, Melder_peek8to32_u (buffer8));
291 }
292 tracecxx . . $ `melder/melder_debug.h:60:10`! (U"read");
293 }
294 /*
295 Close the read pipes, which are no longer needed.
296 */
297 #if defined (macintosh) || defined (UNIXcxx . . $ `<built-in>:479:9`!)
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_asynchronouscxx . . $ Melder_asynchronous.) {
310 return autostring32cxx . . $ _autostring#_autostring(49f6e7a06ebc5aa8). ();
311 } else {
312 #if defined (macintosh) || defined (UNIXcxx . . $ `<built-in>:479:9`!)
313 int childProcessStatus;
314 waitpid (childProcess, & childProcessStatus, 0); // unzombie child process
315 if (! WIFEXITEDcxx . . $ `<external>/3791503621068212355/wait.h:57:10`! (childProcessStatus))
316 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (procedureMessageName, U": subprocess not exited (probably stopped by a signal):\n", stderr_string.string);
317 if (WEXITSTATUScxx . . $ `<external>/3791503621068212355/wait.h:54:10`! (childProcessStatus) != 0)
318 Melder_throwcxx . . $ `melder/melder_error.h:77:9`! (stderr_string.string, U".\n", procedureMessageName, U": subprocess exited with error ", WEXITSTATUScxx . . $ `<external>/3791503621068212355/wait.h:54:10`! (childProcessStatus));
319 if (stderr_string.lengthcxx . . $ MelderString#length. > 0)
320 Melder_casualcxx . . $ Melder_casual(6298c93241566110). (procedureMessageName, U": casual message:\n", stderr_string.stringcxx . . $ MelderString#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_dupcxx . . $ Melder_dup(87bf156b1f548402). (stdout_string.stringcxx . . $ MelderString#string.) : autostring32cxx . . $ _autostring#_autostring(49f6e7a06ebc5aa8). ();
333 }
334 }
335
336 autostring32cxx . . $ autostring32# runSystem_STRcxx . . $ runSystem_STR(87bf156b1f548402). (conststring32cxx . . $ conststring32# command) {
337 return runAny_STRcxx . . $ runAny_STR(5c2a62d3743e2946). (U"runSystem$", command, nullptr, 0, nullptr, true);
338 }
339 void Melder_runSystemcxx . . $ Melder_runSystem(ff00d524ab0355ec). (conststring32cxx . . $ conststring32# command) {
340 (void) runAny_STRcxx . . $ runAny_STR(5c2a62d3743e2946). (U"runSystem", command, nullptr, 0, nullptr, false);
341 }
342 autostring32cxx . . $ autostring32# runSubprocess_STRcxx . . $ runSubprocess_STR(8979b6aada8ea3b7). (conststring32cxx . . $ conststring32# executableFileName, integercxx . . $ integer# narg, char32cxx . . $ char32# ** args) {
343 return runAny_STRcxx . . $ runAny_STR(5c2a62d3743e2946). (U"runSubprocess$", nullptr, executableFileName, narg, args, true);
344 }
345 void Melder_runSubprocesscxx . . $ Melder_runSubprocess(daddfa367acd8092). (conststring32cxx . . $ conststring32# executableFileName, integercxx . . $ integer# narg, char32cxx . . $ char32# ** args) {
346 (void) runAny_STRcxx . . $ runAny_STR(5c2a62d3743e2946). (U"runSubprocess", nullptr, executableFileName, narg, args, false);
347 }
348
349 /* End of file melder_sysenv.cpp */