spawn-pipe.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /* Creation of subprocesses, communicating via pipes.
  2. Copyright (C) 2001-2004, 2006-2020 Free Software Foundation, Inc.
  3. Written by Bruno Haible <haible@clisp.cons.org>, 2001.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. /* Tell clang not to warn about the 'child' variable, below. */
  15. #if defined __clang__
  16. # pragma clang diagnostic ignored "-Wconditional-uninitialized"
  17. #endif
  18. #include <config.h>
  19. /* Specification. */
  20. #include "spawn-pipe.h"
  21. #include <errno.h>
  22. #include <fcntl.h>
  23. #include <stdlib.h>
  24. #include <signal.h>
  25. #include <unistd.h>
  26. #include "error.h"
  27. #include "fatal-signal.h"
  28. #include "unistd-safer.h"
  29. #include "wait-process.h"
  30. #include "gettext.h"
  31. #define _(str) gettext (str)
  32. #if (defined _WIN32 && ! defined __CYGWIN__) || defined __KLIBC__
  33. /* Native Windows API. */
  34. # include <process.h>
  35. # include "w32spawn.h"
  36. #else
  37. /* Unix API. */
  38. # include <spawn.h>
  39. #endif
  40. #if defined(__FreeBSD__) || defined(__MACH__)
  41. extern char** environ;
  42. #endif
  43. #ifdef EINTR
  44. /* EINTR handling for close().
  45. These functions can return -1/EINTR even though we don't have any
  46. signal handlers set up, namely when we get interrupted via SIGSTOP. */
  47. static int
  48. nonintr_close (int fd)
  49. {
  50. int retval;
  51. do
  52. retval = close (fd);
  53. while (retval < 0 && errno == EINTR);
  54. return retval;
  55. }
  56. #undef close /* avoid warning related to gnulib module unistd */
  57. #define close nonintr_close
  58. #if defined _WIN32 && ! defined __CYGWIN__
  59. static int
  60. nonintr_open (const char *pathname, int oflag, mode_t mode)
  61. {
  62. int retval;
  63. do
  64. retval = open (pathname, oflag, mode);
  65. while (retval < 0 && errno == EINTR);
  66. return retval;
  67. }
  68. # undef open /* avoid warning on VMS */
  69. # define open nonintr_open
  70. #endif
  71. #endif
  72. /* Open a pipe connected to a child process.
  73. *
  74. * write system read
  75. * parent -> fd[1] -> STDIN_FILENO -> child if pipe_stdin
  76. * parent <- fd[0] <- STDOUT_FILENO <- child if pipe_stdout
  77. * read system write
  78. *
  79. * At least one of pipe_stdin, pipe_stdout must be true.
  80. * pipe_stdin and prog_stdin together determine the child's standard input.
  81. * pipe_stdout and prog_stdout together determine the child's standard output.
  82. * If pipe_stdin is true, prog_stdin is ignored.
  83. * If pipe_stdout is true, prog_stdout is ignored.
  84. */
  85. static pid_t
  86. create_pipe (const char *progname,
  87. const char *prog_path, char **prog_argv,
  88. bool pipe_stdin, bool pipe_stdout,
  89. const char *prog_stdin, const char *prog_stdout,
  90. bool null_stderr,
  91. bool slave_process, bool exit_on_error,
  92. int fd[2])
  93. {
  94. #if (defined _WIN32 && ! defined __CYGWIN__) || defined __KLIBC__
  95. /* Native Windows API.
  96. This uses _pipe(), dup2(), and _spawnv(). It could also be implemented
  97. using the low-level functions CreatePipe(), DuplicateHandle(),
  98. CreateProcess() and _open_osfhandle(); see the GNU make and GNU clisp
  99. and cvs source code. */
  100. int ifd[2];
  101. int ofd[2];
  102. int orig_stdin;
  103. int orig_stdout;
  104. int orig_stderr;
  105. int child;
  106. int nulloutfd;
  107. int stdinfd;
  108. int stdoutfd;
  109. int saved_errno;
  110. /* FIXME: Need to free memory allocated by prepare_spawn. */
  111. prog_argv = prepare_spawn (prog_argv);
  112. if (pipe_stdout)
  113. if (pipe2_safer (ifd, O_BINARY | O_CLOEXEC) < 0)
  114. error (EXIT_FAILURE, errno, _("cannot create pipe"));
  115. if (pipe_stdin)
  116. if (pipe2_safer (ofd, O_BINARY | O_CLOEXEC) < 0)
  117. error (EXIT_FAILURE, errno, _("cannot create pipe"));
  118. /* Data flow diagram:
  119. *
  120. * write system read
  121. * parent -> ofd[1] -> ofd[0] -> child if pipe_stdin
  122. * parent <- ifd[0] <- ifd[1] <- child if pipe_stdout
  123. * read system write
  124. *
  125. */
  126. /* Save standard file handles of parent process. */
  127. if (pipe_stdin || prog_stdin != NULL)
  128. orig_stdin = dup_safer_noinherit (STDIN_FILENO);
  129. if (pipe_stdout || prog_stdout != NULL)
  130. orig_stdout = dup_safer_noinherit (STDOUT_FILENO);
  131. if (null_stderr)
  132. orig_stderr = dup_safer_noinherit (STDERR_FILENO);
  133. child = -1;
  134. /* Create standard file handles of child process. */
  135. nulloutfd = -1;
  136. stdinfd = -1;
  137. stdoutfd = -1;
  138. if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
  139. && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
  140. && (!null_stderr
  141. || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
  142. && (nulloutfd == STDERR_FILENO
  143. || (dup2 (nulloutfd, STDERR_FILENO) >= 0
  144. && close (nulloutfd) >= 0))))
  145. && (pipe_stdin
  146. || prog_stdin == NULL
  147. || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
  148. && (stdinfd == STDIN_FILENO
  149. || (dup2 (stdinfd, STDIN_FILENO) >= 0
  150. && close (stdinfd) >= 0))))
  151. && (pipe_stdout
  152. || prog_stdout == NULL
  153. || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
  154. && (stdoutfd == STDOUT_FILENO
  155. || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
  156. && close (stdoutfd) >= 0)))))
  157. /* The child process doesn't inherit ifd[0], ifd[1], ofd[0], ofd[1],
  158. but it inherits all open()ed or dup2()ed file handles (which is what
  159. we want in the case of STD*_FILENO). */
  160. /* Use _spawnvpe and pass the environment explicitly. This is needed if
  161. the program has modified the environment using putenv() or [un]setenv().
  162. On Windows, programs have two environments, one in the "environment
  163. block" of the process and managed through SetEnvironmentVariable(), and
  164. one inside the process, in the location retrieved by the 'environ'
  165. macro. When using _spawnvp() without 'e', the child process inherits a
  166. copy of the environment block - ignoring the effects of putenv() and
  167. [un]setenv(). */
  168. {
  169. child = _spawnvpe (P_NOWAIT, prog_path, (const char **) prog_argv,
  170. (const char **) environ);
  171. if (child < 0 && errno == ENOEXEC)
  172. {
  173. /* prog is not a native executable. Try to execute it as a
  174. shell script. Note that prepare_spawn() has already prepended
  175. a hidden element "sh.exe" to prog_argv. */
  176. --prog_argv;
  177. child = _spawnvpe (P_NOWAIT, prog_argv[0], (const char **) prog_argv,
  178. (const char **) environ);
  179. }
  180. }
  181. if (child == -1)
  182. saved_errno = errno;
  183. if (stdinfd >= 0)
  184. close (stdinfd);
  185. if (stdoutfd >= 0)
  186. close (stdoutfd);
  187. if (nulloutfd >= 0)
  188. close (nulloutfd);
  189. /* Restore standard file handles of parent process. */
  190. if (null_stderr)
  191. undup_safer_noinherit (orig_stderr, STDERR_FILENO);
  192. if (pipe_stdout || prog_stdout != NULL)
  193. undup_safer_noinherit (orig_stdout, STDOUT_FILENO);
  194. if (pipe_stdin || prog_stdin != NULL)
  195. undup_safer_noinherit (orig_stdin, STDIN_FILENO);
  196. if (pipe_stdin)
  197. close (ofd[0]);
  198. if (pipe_stdout)
  199. close (ifd[1]);
  200. if (child == -1)
  201. {
  202. if (exit_on_error || !null_stderr)
  203. error (exit_on_error ? EXIT_FAILURE : 0, saved_errno,
  204. _("%s subprocess failed"), progname);
  205. if (pipe_stdout)
  206. close (ifd[0]);
  207. if (pipe_stdin)
  208. close (ofd[1]);
  209. errno = saved_errno;
  210. return -1;
  211. }
  212. if (pipe_stdout)
  213. fd[0] = ifd[0];
  214. if (pipe_stdin)
  215. fd[1] = ofd[1];
  216. return child;
  217. #else
  218. /* Unix API. */
  219. int ifd[2];
  220. int ofd[2];
  221. sigset_t blocked_signals;
  222. posix_spawn_file_actions_t actions;
  223. bool actions_allocated;
  224. posix_spawnattr_t attrs;
  225. bool attrs_allocated;
  226. int err;
  227. pid_t child;
  228. if (pipe_stdout)
  229. if (pipe_safer (ifd) < 0)
  230. error (EXIT_FAILURE, errno, _("cannot create pipe"));
  231. if (pipe_stdin)
  232. if (pipe_safer (ofd) < 0)
  233. error (EXIT_FAILURE, errno, _("cannot create pipe"));
  234. /* Data flow diagram:
  235. *
  236. * write system read
  237. * parent -> ofd[1] -> ofd[0] -> child if pipe_stdin
  238. * parent <- ifd[0] <- ifd[1] <- child if pipe_stdout
  239. * read system write
  240. *
  241. */
  242. if (slave_process)
  243. {
  244. sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
  245. block_fatal_signals ();
  246. }
  247. actions_allocated = false;
  248. attrs_allocated = false;
  249. if ((err = posix_spawn_file_actions_init (&actions)) != 0
  250. || (actions_allocated = true,
  251. (pipe_stdin
  252. && (err = posix_spawn_file_actions_adddup2 (&actions,
  253. ofd[0], STDIN_FILENO))
  254. != 0)
  255. || (pipe_stdout
  256. && (err = posix_spawn_file_actions_adddup2 (&actions,
  257. ifd[1], STDOUT_FILENO))
  258. != 0)
  259. || (pipe_stdin
  260. && (err = posix_spawn_file_actions_addclose (&actions, ofd[0]))
  261. != 0)
  262. || (pipe_stdout
  263. && (err = posix_spawn_file_actions_addclose (&actions, ifd[1]))
  264. != 0)
  265. || (pipe_stdin
  266. && (err = posix_spawn_file_actions_addclose (&actions, ofd[1]))
  267. != 0)
  268. || (pipe_stdout
  269. && (err = posix_spawn_file_actions_addclose (&actions, ifd[0]))
  270. != 0)
  271. || (null_stderr
  272. && (err = posix_spawn_file_actions_addopen (&actions,
  273. STDERR_FILENO,
  274. "/dev/null", O_RDWR,
  275. 0))
  276. != 0)
  277. || (!pipe_stdin
  278. && prog_stdin != NULL
  279. && (err = posix_spawn_file_actions_addopen (&actions,
  280. STDIN_FILENO,
  281. prog_stdin, O_RDONLY,
  282. 0))
  283. != 0)
  284. || (!pipe_stdout
  285. && prog_stdout != NULL
  286. && (err = posix_spawn_file_actions_addopen (&actions,
  287. STDOUT_FILENO,
  288. prog_stdout, O_WRONLY,
  289. 0))
  290. != 0)
  291. || (slave_process
  292. && ((err = posix_spawnattr_init (&attrs)) != 0
  293. || (attrs_allocated = true,
  294. (err = posix_spawnattr_setsigmask (&attrs,
  295. &blocked_signals))
  296. != 0
  297. || (err = posix_spawnattr_setflags (&attrs,
  298. POSIX_SPAWN_SETSIGMASK))
  299. != 0)))
  300. || (err = posix_spawnp (&child, prog_path, &actions,
  301. attrs_allocated ? &attrs : NULL, prog_argv,
  302. environ))
  303. != 0))
  304. {
  305. if (actions_allocated)
  306. posix_spawn_file_actions_destroy (&actions);
  307. if (attrs_allocated)
  308. posix_spawnattr_destroy (&attrs);
  309. if (slave_process)
  310. unblock_fatal_signals ();
  311. if (exit_on_error || !null_stderr)
  312. error (exit_on_error ? EXIT_FAILURE : 0, err,
  313. _("%s subprocess failed"), progname);
  314. if (pipe_stdout)
  315. {
  316. close (ifd[0]);
  317. close (ifd[1]);
  318. }
  319. if (pipe_stdin)
  320. {
  321. close (ofd[0]);
  322. close (ofd[1]);
  323. }
  324. errno = err;
  325. return -1;
  326. }
  327. posix_spawn_file_actions_destroy (&actions);
  328. if (attrs_allocated)
  329. posix_spawnattr_destroy (&attrs);
  330. if (slave_process)
  331. {
  332. register_slave_subprocess (child);
  333. unblock_fatal_signals ();
  334. }
  335. if (pipe_stdin)
  336. close (ofd[0]);
  337. if (pipe_stdout)
  338. close (ifd[1]);
  339. if (pipe_stdout)
  340. fd[0] = ifd[0];
  341. if (pipe_stdin)
  342. fd[1] = ofd[1];
  343. return child;
  344. #endif
  345. }
  346. /* Open a bidirectional pipe.
  347. *
  348. * write system read
  349. * parent -> fd[1] -> STDIN_FILENO -> child
  350. * parent <- fd[0] <- STDOUT_FILENO <- child
  351. * read system write
  352. *
  353. */
  354. pid_t
  355. create_pipe_bidi (const char *progname,
  356. const char *prog_path, char **prog_argv,
  357. bool null_stderr,
  358. bool slave_process, bool exit_on_error,
  359. int fd[2])
  360. {
  361. pid_t result = create_pipe (progname, prog_path, prog_argv,
  362. true, true, NULL, NULL,
  363. null_stderr, slave_process, exit_on_error,
  364. fd);
  365. return result;
  366. }
  367. /* Open a pipe for input from a child process.
  368. * The child's stdin comes from a file.
  369. *
  370. * read system write
  371. * parent <- fd[0] <- STDOUT_FILENO <- child
  372. *
  373. */
  374. pid_t
  375. create_pipe_in (const char *progname,
  376. const char *prog_path, char **prog_argv,
  377. const char *prog_stdin, bool null_stderr,
  378. bool slave_process, bool exit_on_error,
  379. int fd[1])
  380. {
  381. int iofd[2];
  382. pid_t result = create_pipe (progname, prog_path, prog_argv,
  383. false, true, prog_stdin, NULL,
  384. null_stderr, slave_process, exit_on_error,
  385. iofd);
  386. if (result != -1)
  387. fd[0] = iofd[0];
  388. return result;
  389. }
  390. /* Open a pipe for output to a child process.
  391. * The child's stdout goes to a file.
  392. *
  393. * write system read
  394. * parent -> fd[0] -> STDIN_FILENO -> child
  395. *
  396. */
  397. pid_t
  398. create_pipe_out (const char *progname,
  399. const char *prog_path, char **prog_argv,
  400. const char *prog_stdout, bool null_stderr,
  401. bool slave_process, bool exit_on_error,
  402. int fd[1])
  403. {
  404. int iofd[2];
  405. pid_t result = create_pipe (progname, prog_path, prog_argv,
  406. true, false, NULL, prog_stdout,
  407. null_stderr, slave_process, exit_on_error,
  408. iofd);
  409. if (result != -1)
  410. fd[0] = iofd[1];
  411. return result;
  412. }