subprocess.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. /*
  2. The latest version of this library is available on GitHub;
  3. https://github.com/sheredom/subprocess.h
  4. */
  5. /*
  6. This is free and unencumbered software released into the public domain.
  7. Anyone is free to copy, modify, publish, use, compile, sell, or
  8. distribute this software, either in source code form or as a compiled
  9. binary, for any purpose, commercial or non-commercial, and by any
  10. means.
  11. In jurisdictions that recognize copyright laws, the author or authors
  12. of this software dedicate any and all copyright interest in the
  13. software to the public domain. We make this dedication for the benefit
  14. of the public at large and to the detriment of our heirs and
  15. successors. We intend this dedication to be an overt act of
  16. relinquishment in perpetuity of all present and future rights to this
  17. software under copyright law.
  18. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  21. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  22. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  23. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  24. OTHER DEALINGS IN THE SOFTWARE.
  25. For more information, please refer to <http://unlicense.org/>
  26. */
  27. #ifndef SHEREDOM_SUBPROCESS_H_INCLUDED
  28. #define SHEREDOM_SUBPROCESS_H_INCLUDED
  29. #if defined(_MSC_VER)
  30. #pragma warning(push, 1)
  31. /* disable warning: '__cplusplus' is not defined as a preprocessor macro,
  32. * replacing with '0' for '#if/#elif' */
  33. #pragma warning(disable : 4668)
  34. #endif
  35. #include <stdio.h>
  36. #include <string.h>
  37. #if defined(_MSC_VER)
  38. #pragma warning(pop)
  39. #endif
  40. #if defined(_MSC_VER)
  41. #define subprocess_pure
  42. #define subprocess_weak __inline
  43. #elif defined(__clang__) || defined(__GNUC__)
  44. #define subprocess_pure __attribute__((pure))
  45. #define subprocess_weak __attribute__((weak))
  46. #else
  47. #error Non clang, non gcc, non MSVC compiler found!
  48. #endif
  49. struct subprocess_s;
  50. enum subprocess_option_e {
  51. // stdout and stderr are the same FILE.
  52. subprocess_option_combined_stdout_stderr = 0x1,
  53. // The child process should inherit the environment variables of the parent.
  54. subprocess_option_inherit_environment = 0x2,
  55. // Enable asynchronous reading of stdout/stderr before it has completed.
  56. subprocess_option_enable_async = 0x4,
  57. // Enable the child process to be spawned with no window visible if supported
  58. // by the platform.
  59. subprocess_option_no_window = 0x8,
  60. // Search for program names in the PATH variable. Always enabled on Windows.
  61. // Note: this will **not** search for paths in any provided custom environment
  62. // and instead uses the PATH of the spawning process.
  63. subprocess_option_search_user_path = 0x10
  64. };
  65. #if defined(__cplusplus)
  66. extern "C" {
  67. #endif
  68. /// @brief Create a process.
  69. /// @param command_line An array of strings for the command line to execute for
  70. /// this process. The last element must be NULL to signify the end of the array.
  71. /// The memory backing this parameter only needs to persist until this function
  72. /// returns.
  73. /// @param options A bit field of subprocess_option_e's to pass.
  74. /// @param out_process The newly created process.
  75. /// @return On success zero is returned.
  76. subprocess_weak int subprocess_create(const char *const command_line[],
  77. int options,
  78. struct subprocess_s *const out_process);
  79. /// @brief Create a process (extended create).
  80. /// @param command_line An array of strings for the command line to execute for
  81. /// this process. The last element must be NULL to signify the end of the array.
  82. /// The memory backing this parameter only needs to persist until this function
  83. /// returns.
  84. /// @param options A bit field of subprocess_option_e's to pass.
  85. /// @param environment An optional array of strings for the environment to use
  86. /// for a child process (each element of the form FOO=BAR). The last element
  87. /// must be NULL to signify the end of the array.
  88. /// @param out_process The newly created process.
  89. /// @return On success zero is returned.
  90. ///
  91. /// If `options` contains `subprocess_option_inherit_environment`, then
  92. /// `environment` must be NULL.
  93. subprocess_weak int
  94. subprocess_create_ex(const char *const command_line[], int options,
  95. const char *const environment[],
  96. struct subprocess_s *const out_process);
  97. /// @brief Get the standard input file for a process.
  98. /// @param process The process to query.
  99. /// @return The file for standard input of the process.
  100. ///
  101. /// The file returned can be written to by the parent process to feed data to
  102. /// the standard input of the process.
  103. subprocess_pure subprocess_weak FILE *
  104. subprocess_stdin(const struct subprocess_s *const process);
  105. /// @brief Get the standard output file for a process.
  106. /// @param process The process to query.
  107. /// @return The file for standard output of the process.
  108. ///
  109. /// The file returned can be read from by the parent process to read data from
  110. /// the standard output of the child process.
  111. subprocess_pure subprocess_weak FILE *
  112. subprocess_stdout(const struct subprocess_s *const process);
  113. /// @brief Get the standard error file for a process.
  114. /// @param process The process to query.
  115. /// @return The file for standard error of the process.
  116. ///
  117. /// The file returned can be read from by the parent process to read data from
  118. /// the standard error of the child process.
  119. ///
  120. /// If the process was created with the subprocess_option_combined_stdout_stderr
  121. /// option bit set, this function will return NULL, and the subprocess_stdout
  122. /// function should be used for both the standard output and error combined.
  123. subprocess_pure subprocess_weak FILE *
  124. subprocess_stderr(const struct subprocess_s *const process);
  125. /// @brief Wait for a process to finish execution.
  126. /// @param process The process to wait for.
  127. /// @param out_return_code The return code of the returned process (can be
  128. /// NULL).
  129. /// @return On success zero is returned.
  130. ///
  131. /// Joining a process will close the stdin pipe to the process.
  132. subprocess_weak int subprocess_join(struct subprocess_s *const process,
  133. int *const out_return_code);
  134. /// @brief Destroy a previously created process.
  135. /// @param process The process to destroy.
  136. /// @return On success zero is returned.
  137. ///
  138. /// If the process to be destroyed had not finished execution, it may out live
  139. /// the parent process.
  140. subprocess_weak int subprocess_destroy(struct subprocess_s *const process);
  141. /// @brief Terminate a previously created process.
  142. /// @param process The process to terminate.
  143. /// @return On success zero is returned.
  144. ///
  145. /// If the process to be destroyed had not finished execution, it will be
  146. /// terminated (i.e killed).
  147. subprocess_weak int subprocess_terminate(struct subprocess_s *const process);
  148. /// @brief Read the standard output from the child process.
  149. /// @param process The process to read from.
  150. /// @param buffer The buffer to read into.
  151. /// @param size The maximum number of bytes to read.
  152. /// @return The number of bytes actually read into buffer. Can only be 0 if the
  153. /// process has complete.
  154. ///
  155. /// The only safe way to read from the standard output of a process during it's
  156. /// execution is to use the `subprocess_option_enable_async` option in
  157. /// conjuction with this method.
  158. subprocess_weak unsigned
  159. subprocess_read_stdout(struct subprocess_s *const process, char *const buffer,
  160. unsigned size);
  161. /// @brief Read the standard error from the child process.
  162. /// @param process The process to read from.
  163. /// @param buffer The buffer to read into.
  164. /// @param size The maximum number of bytes to read.
  165. /// @return The number of bytes actually read into buffer. Can only be 0 if the
  166. /// process has complete.
  167. ///
  168. /// The only safe way to read from the standard error of a process during it's
  169. /// execution is to use the `subprocess_option_enable_async` option in
  170. /// conjuction with this method.
  171. subprocess_weak unsigned
  172. subprocess_read_stderr(struct subprocess_s *const process, char *const buffer,
  173. unsigned size);
  174. /// @brief Returns if the subprocess is currently still alive and executing.
  175. /// @param process The process to check.
  176. /// @return If the process is still alive non-zero is returned.
  177. subprocess_weak int subprocess_alive(struct subprocess_s *const process);
  178. #if defined(__cplusplus)
  179. #define SUBPROCESS_CAST(type, x) static_cast<type>(x)
  180. #define SUBPROCESS_PTR_CAST(type, x) reinterpret_cast<type>(x)
  181. #define SUBPROCESS_CONST_CAST(type, x) const_cast<type>(x)
  182. #define SUBPROCESS_NULL NULL
  183. #else
  184. #define SUBPROCESS_CAST(type, x) ((type)(x))
  185. #define SUBPROCESS_PTR_CAST(type, x) ((type)(x))
  186. #define SUBPROCESS_CONST_CAST(type, x) ((type)(x))
  187. #define SUBPROCESS_NULL 0
  188. #endif
  189. #if !defined(_MSC_VER)
  190. #include <signal.h>
  191. #include <spawn.h>
  192. #include <stdlib.h>
  193. #include <sys/types.h>
  194. #include <sys/wait.h>
  195. #include <unistd.h>
  196. #endif
  197. #if defined(_MSC_VER)
  198. #if (_MSC_VER < 1920)
  199. #ifdef _WIN64
  200. typedef __int64 subprocess_intptr_t;
  201. typedef unsigned __int64 subprocess_size_t;
  202. #else
  203. typedef int subprocess_intptr_t;
  204. typedef unsigned int subprocess_size_t;
  205. #endif
  206. #else
  207. #include <inttypes.h>
  208. typedef intptr_t subprocess_intptr_t;
  209. typedef size_t subprocess_size_t;
  210. #endif
  211. #ifdef __clang__
  212. #pragma clang diagnostic push
  213. #pragma clang diagnostic ignored "-Wreserved-identifier"
  214. #endif
  215. typedef struct _PROCESS_INFORMATION *LPPROCESS_INFORMATION;
  216. typedef struct _SECURITY_ATTRIBUTES *LPSECURITY_ATTRIBUTES;
  217. typedef struct _STARTUPINFOA *LPSTARTUPINFOA;
  218. typedef struct _OVERLAPPED *LPOVERLAPPED;
  219. #ifdef __clang__
  220. #pragma clang diagnostic pop
  221. #endif
  222. #pragma warning(push, 1)
  223. struct subprocess_subprocess_information_s {
  224. void *hProcess;
  225. void *hThread;
  226. unsigned long dwProcessId;
  227. unsigned long dwThreadId;
  228. };
  229. struct subprocess_security_attributes_s {
  230. unsigned long nLength;
  231. void *lpSecurityDescriptor;
  232. int bInheritHandle;
  233. };
  234. struct subprocess_startup_info_s {
  235. unsigned long cb;
  236. char *lpReserved;
  237. char *lpDesktop;
  238. char *lpTitle;
  239. unsigned long dwX;
  240. unsigned long dwY;
  241. unsigned long dwXSize;
  242. unsigned long dwYSize;
  243. unsigned long dwXCountChars;
  244. unsigned long dwYCountChars;
  245. unsigned long dwFillAttribute;
  246. unsigned long dwFlags;
  247. unsigned short wShowWindow;
  248. unsigned short cbReserved2;
  249. unsigned char *lpReserved2;
  250. void *hStdInput;
  251. void *hStdOutput;
  252. void *hStdError;
  253. };
  254. struct subprocess_overlapped_s {
  255. uintptr_t Internal;
  256. uintptr_t InternalHigh;
  257. union {
  258. struct {
  259. unsigned long Offset;
  260. unsigned long OffsetHigh;
  261. } DUMMYSTRUCTNAME;
  262. void *Pointer;
  263. } DUMMYUNIONNAME;
  264. void *hEvent;
  265. };
  266. #pragma warning(pop)
  267. __declspec(dllimport) unsigned long __stdcall GetLastError(void);
  268. __declspec(dllimport) int __stdcall SetHandleInformation(void *, unsigned long,
  269. unsigned long);
  270. __declspec(dllimport) int __stdcall CreatePipe(void **, void **,
  271. LPSECURITY_ATTRIBUTES,
  272. unsigned long);
  273. __declspec(dllimport) void *__stdcall CreateNamedPipeA(
  274. const char *, unsigned long, unsigned long, unsigned long, unsigned long,
  275. unsigned long, unsigned long, LPSECURITY_ATTRIBUTES);
  276. __declspec(dllimport) int __stdcall ReadFile(void *, void *, unsigned long,
  277. unsigned long *, LPOVERLAPPED);
  278. __declspec(dllimport) unsigned long __stdcall GetCurrentProcessId(void);
  279. __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(void);
  280. __declspec(dllimport) void *__stdcall CreateFileA(const char *, unsigned long,
  281. unsigned long,
  282. LPSECURITY_ATTRIBUTES,
  283. unsigned long, unsigned long,
  284. void *);
  285. __declspec(dllimport) void *__stdcall CreateEventA(LPSECURITY_ATTRIBUTES, int,
  286. int, const char *);
  287. __declspec(dllimport) int __stdcall CreateProcessA(
  288. const char *, char *, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, int,
  289. unsigned long, void *, const char *, LPSTARTUPINFOA, LPPROCESS_INFORMATION);
  290. __declspec(dllimport) int __stdcall CloseHandle(void *);
  291. __declspec(dllimport) unsigned long __stdcall WaitForSingleObject(
  292. void *, unsigned long);
  293. __declspec(dllimport) int __stdcall GetExitCodeProcess(
  294. void *, unsigned long *lpExitCode);
  295. __declspec(dllimport) int __stdcall TerminateProcess(void *, unsigned int);
  296. __declspec(dllimport) unsigned long __stdcall WaitForMultipleObjects(
  297. unsigned long, void *const *, int, unsigned long);
  298. __declspec(dllimport) int __stdcall GetOverlappedResult(void *, LPOVERLAPPED,
  299. unsigned long *, int);
  300. #if defined(_DLL) && (_DLL == 1)
  301. #define SUBPROCESS_DLLIMPORT __declspec(dllimport)
  302. #else
  303. #define SUBPROCESS_DLLIMPORT
  304. #endif
  305. #ifdef __clang__
  306. #pragma clang diagnostic push
  307. #pragma clang diagnostic ignored "-Wreserved-identifier"
  308. #endif
  309. SUBPROCESS_DLLIMPORT int __cdecl _fileno(FILE *);
  310. SUBPROCESS_DLLIMPORT int __cdecl _open_osfhandle(subprocess_intptr_t, int);
  311. SUBPROCESS_DLLIMPORT subprocess_intptr_t __cdecl _get_osfhandle(int);
  312. void *__cdecl _alloca(subprocess_size_t);
  313. #ifdef __clang__
  314. #pragma clang diagnostic pop
  315. #endif
  316. #else
  317. typedef size_t subprocess_size_t;
  318. #endif
  319. #ifdef __clang__
  320. #pragma clang diagnostic push
  321. #pragma clang diagnostic ignored "-Wpadded"
  322. #endif
  323. struct subprocess_s {
  324. FILE *stdin_file;
  325. FILE *stdout_file;
  326. FILE *stderr_file;
  327. #if defined(_MSC_VER)
  328. void *hProcess;
  329. void *hStdInput;
  330. void *hEventOutput;
  331. void *hEventError;
  332. #else
  333. pid_t child;
  334. int return_status;
  335. #endif
  336. subprocess_size_t alive;
  337. };
  338. #ifdef __clang__
  339. #pragma clang diagnostic pop
  340. #endif
  341. #if defined(_MSC_VER)
  342. subprocess_weak int subprocess_create_named_pipe_helper(void **rd, void **wr);
  343. int subprocess_create_named_pipe_helper(void **rd, void **wr) {
  344. const unsigned long pipeAccessInbound = 0x00000001;
  345. const unsigned long fileFlagOverlapped = 0x40000000;
  346. const unsigned long pipeTypeByte = 0x00000000;
  347. const unsigned long pipeWait = 0x00000000;
  348. const unsigned long genericWrite = 0x40000000;
  349. const unsigned long openExisting = 3;
  350. const unsigned long fileAttributeNormal = 0x00000080;
  351. const void *const invalidHandleValue =
  352. SUBPROCESS_PTR_CAST(void *, ~(SUBPROCESS_CAST(subprocess_intptr_t, 0)));
  353. struct subprocess_security_attributes_s saAttr = {sizeof(saAttr),
  354. SUBPROCESS_NULL, 1};
  355. char name[256] = {0};
  356. __declspec(thread) static long index = 0;
  357. const long unique = index++;
  358. #if _MSC_VER < 1900
  359. #pragma warning(push, 1)
  360. #pragma warning(disable : 4996)
  361. _snprintf(name, sizeof(name) - 1,
  362. "\\\\.\\pipe\\sheredom_subprocess_h.%08lx.%08lx.%ld",
  363. GetCurrentProcessId(), GetCurrentThreadId(), unique);
  364. #pragma warning(pop)
  365. #else
  366. snprintf(name, sizeof(name) - 1,
  367. "\\\\.\\pipe\\sheredom_subprocess_h.%08lx.%08lx.%ld",
  368. GetCurrentProcessId(), GetCurrentThreadId(), unique);
  369. #endif
  370. *rd =
  371. CreateNamedPipeA(name, pipeAccessInbound | fileFlagOverlapped,
  372. pipeTypeByte | pipeWait, 1, 4096, 4096, SUBPROCESS_NULL,
  373. SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr));
  374. if (invalidHandleValue == *rd) {
  375. return -1;
  376. }
  377. *wr = CreateFileA(name, genericWrite, SUBPROCESS_NULL,
  378. SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr),
  379. openExisting, fileAttributeNormal, SUBPROCESS_NULL);
  380. if (invalidHandleValue == *wr) {
  381. return -1;
  382. }
  383. return 0;
  384. }
  385. #endif
  386. int subprocess_create(const char *const commandLine[], int options,
  387. struct subprocess_s *const out_process) {
  388. return subprocess_create_ex(commandLine, options, SUBPROCESS_NULL,
  389. out_process);
  390. }
  391. int subprocess_create_ex(const char *const commandLine[], int options,
  392. const char *const environment[],
  393. struct subprocess_s *const out_process) {
  394. #if defined(_MSC_VER)
  395. int fd;
  396. void *rd, *wr;
  397. char *commandLineCombined;
  398. subprocess_size_t len;
  399. int i, j;
  400. int need_quoting;
  401. unsigned long flags = 0;
  402. const unsigned long startFUseStdHandles = 0x00000100;
  403. const unsigned long handleFlagInherit = 0x00000001;
  404. const unsigned long createNoWindow = 0x08000000;
  405. struct subprocess_subprocess_information_s processInfo;
  406. struct subprocess_security_attributes_s saAttr = {sizeof(saAttr),
  407. SUBPROCESS_NULL, 1};
  408. char *used_environment = SUBPROCESS_NULL;
  409. struct subprocess_startup_info_s startInfo = {0,
  410. SUBPROCESS_NULL,
  411. SUBPROCESS_NULL,
  412. SUBPROCESS_NULL,
  413. 0,
  414. 0,
  415. 0,
  416. 0,
  417. 0,
  418. 0,
  419. 0,
  420. 0,
  421. 0,
  422. 0,
  423. SUBPROCESS_NULL,
  424. SUBPROCESS_NULL,
  425. SUBPROCESS_NULL,
  426. SUBPROCESS_NULL};
  427. startInfo.cb = sizeof(startInfo);
  428. startInfo.dwFlags = startFUseStdHandles;
  429. if (subprocess_option_no_window == (options & subprocess_option_no_window)) {
  430. flags |= createNoWindow;
  431. }
  432. if (subprocess_option_inherit_environment !=
  433. (options & subprocess_option_inherit_environment)) {
  434. if (SUBPROCESS_NULL == environment) {
  435. used_environment = SUBPROCESS_CONST_CAST(char *, "\0\0");
  436. } else {
  437. // We always end with two null terminators.
  438. len = 2;
  439. for (i = 0; environment[i]; i++) {
  440. for (j = 0; '\0' != environment[i][j]; j++) {
  441. len++;
  442. }
  443. // For the null terminator too.
  444. len++;
  445. }
  446. used_environment = SUBPROCESS_CAST(char *, _alloca(len));
  447. // Re-use len for the insertion position
  448. len = 0;
  449. for (i = 0; environment[i]; i++) {
  450. for (j = 0; '\0' != environment[i][j]; j++) {
  451. used_environment[len++] = environment[i][j];
  452. }
  453. used_environment[len++] = '\0';
  454. }
  455. // End with the two null terminators.
  456. used_environment[len++] = '\0';
  457. used_environment[len++] = '\0';
  458. }
  459. } else {
  460. if (SUBPROCESS_NULL != environment) {
  461. return -1;
  462. }
  463. }
  464. if (!CreatePipe(&rd, &wr, SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr),
  465. 0)) {
  466. return -1;
  467. }
  468. if (!SetHandleInformation(wr, handleFlagInherit, 0)) {
  469. return -1;
  470. }
  471. fd = _open_osfhandle(SUBPROCESS_PTR_CAST(subprocess_intptr_t, wr), 0);
  472. if (-1 != fd) {
  473. out_process->stdin_file = _fdopen(fd, "wb");
  474. if (SUBPROCESS_NULL == out_process->stdin_file) {
  475. return -1;
  476. }
  477. }
  478. startInfo.hStdInput = rd;
  479. if (options & subprocess_option_enable_async) {
  480. if (subprocess_create_named_pipe_helper(&rd, &wr)) {
  481. return -1;
  482. }
  483. } else {
  484. if (!CreatePipe(&rd, &wr,
  485. SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr), 0)) {
  486. return -1;
  487. }
  488. }
  489. if (!SetHandleInformation(rd, handleFlagInherit, 0)) {
  490. return -1;
  491. }
  492. fd = _open_osfhandle(SUBPROCESS_PTR_CAST(subprocess_intptr_t, rd), 0);
  493. if (-1 != fd) {
  494. out_process->stdout_file = _fdopen(fd, "rb");
  495. if (SUBPROCESS_NULL == out_process->stdout_file) {
  496. return -1;
  497. }
  498. }
  499. startInfo.hStdOutput = wr;
  500. if (subprocess_option_combined_stdout_stderr ==
  501. (options & subprocess_option_combined_stdout_stderr)) {
  502. out_process->stderr_file = out_process->stdout_file;
  503. startInfo.hStdError = startInfo.hStdOutput;
  504. } else {
  505. if (options & subprocess_option_enable_async) {
  506. if (subprocess_create_named_pipe_helper(&rd, &wr)) {
  507. return -1;
  508. }
  509. } else {
  510. if (!CreatePipe(&rd, &wr,
  511. SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr), 0)) {
  512. return -1;
  513. }
  514. }
  515. if (!SetHandleInformation(rd, handleFlagInherit, 0)) {
  516. return -1;
  517. }
  518. fd = _open_osfhandle(SUBPROCESS_PTR_CAST(subprocess_intptr_t, rd), 0);
  519. if (-1 != fd) {
  520. out_process->stderr_file = _fdopen(fd, "rb");
  521. if (SUBPROCESS_NULL == out_process->stderr_file) {
  522. return -1;
  523. }
  524. }
  525. startInfo.hStdError = wr;
  526. }
  527. if (options & subprocess_option_enable_async) {
  528. out_process->hEventOutput =
  529. CreateEventA(SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr), 1, 1,
  530. SUBPROCESS_NULL);
  531. out_process->hEventError =
  532. CreateEventA(SUBPROCESS_PTR_CAST(LPSECURITY_ATTRIBUTES, &saAttr), 1, 1,
  533. SUBPROCESS_NULL);
  534. } else {
  535. out_process->hEventOutput = SUBPROCESS_NULL;
  536. out_process->hEventError = SUBPROCESS_NULL;
  537. }
  538. // Combine commandLine together into a single string
  539. len = 0;
  540. for (i = 0; commandLine[i]; i++) {
  541. // for the trailing \0
  542. len++;
  543. // Quote the argument if it has a space in it
  544. if (strpbrk(commandLine[i], "\t\v ") != SUBPROCESS_NULL)
  545. len += 2;
  546. for (j = 0; '\0' != commandLine[i][j]; j++) {
  547. switch (commandLine[i][j]) {
  548. default:
  549. break;
  550. case '\\':
  551. if (commandLine[i][j + 1] == '"') {
  552. len++;
  553. }
  554. break;
  555. case '"':
  556. len++;
  557. break;
  558. }
  559. len++;
  560. }
  561. }
  562. commandLineCombined = SUBPROCESS_CAST(char *, _alloca(len));
  563. if (!commandLineCombined) {
  564. return -1;
  565. }
  566. // Gonna re-use len to store the write index into commandLineCombined
  567. len = 0;
  568. for (i = 0; commandLine[i]; i++) {
  569. if (0 != i) {
  570. commandLineCombined[len++] = ' ';
  571. }
  572. need_quoting = strpbrk(commandLine[i], "\t\v ") != SUBPROCESS_NULL;
  573. if (need_quoting) {
  574. commandLineCombined[len++] = '"';
  575. }
  576. for (j = 0; '\0' != commandLine[i][j]; j++) {
  577. switch (commandLine[i][j]) {
  578. default:
  579. break;
  580. case '\\':
  581. if (commandLine[i][j + 1] == '"') {
  582. commandLineCombined[len++] = '\\';
  583. }
  584. break;
  585. case '"':
  586. commandLineCombined[len++] = '\\';
  587. break;
  588. }
  589. commandLineCombined[len++] = commandLine[i][j];
  590. }
  591. if (need_quoting) {
  592. commandLineCombined[len++] = '"';
  593. }
  594. }
  595. commandLineCombined[len] = '\0';
  596. if (!CreateProcessA(
  597. SUBPROCESS_NULL,
  598. commandLineCombined, // command line
  599. SUBPROCESS_NULL, // process security attributes
  600. SUBPROCESS_NULL, // primary thread security attributes
  601. 1, // handles are inherited
  602. flags, // creation flags
  603. used_environment, // used environment
  604. SUBPROCESS_NULL, // use parent's current directory
  605. SUBPROCESS_PTR_CAST(LPSTARTUPINFOA,
  606. &startInfo), // STARTUPINFO pointer
  607. SUBPROCESS_PTR_CAST(LPPROCESS_INFORMATION, &processInfo))) {
  608. return -1;
  609. }
  610. out_process->hProcess = processInfo.hProcess;
  611. out_process->hStdInput = startInfo.hStdInput;
  612. // We don't need the handle of the primary thread in the called process.
  613. CloseHandle(processInfo.hThread);
  614. if (SUBPROCESS_NULL != startInfo.hStdOutput) {
  615. CloseHandle(startInfo.hStdOutput);
  616. if (startInfo.hStdError != startInfo.hStdOutput) {
  617. CloseHandle(startInfo.hStdError);
  618. }
  619. }
  620. out_process->alive = 1;
  621. return 0;
  622. #else
  623. int stdinfd[2];
  624. int stdoutfd[2];
  625. int stderrfd[2];
  626. pid_t child;
  627. extern char **environ;
  628. char *const empty_environment[1] = {SUBPROCESS_NULL};
  629. posix_spawn_file_actions_t actions;
  630. char *const *used_environment;
  631. if (subprocess_option_inherit_environment ==
  632. (options & subprocess_option_inherit_environment)) {
  633. if (SUBPROCESS_NULL != environment) {
  634. return -1;
  635. }
  636. }
  637. if (0 != pipe(stdinfd)) {
  638. return -1;
  639. }
  640. if (0 != pipe(stdoutfd)) {
  641. return -1;
  642. }
  643. if (subprocess_option_combined_stdout_stderr !=
  644. (options & subprocess_option_combined_stdout_stderr)) {
  645. if (0 != pipe(stderrfd)) {
  646. return -1;
  647. }
  648. }
  649. if (environment) {
  650. #ifdef __clang__
  651. #pragma clang diagnostic push
  652. #pragma clang diagnostic ignored "-Wcast-qual"
  653. #pragma clang diagnostic ignored "-Wold-style-cast"
  654. #endif
  655. used_environment = (char *const *)environment;
  656. #ifdef __clang__
  657. #pragma clang diagnostic pop
  658. #endif
  659. } else if (subprocess_option_inherit_environment ==
  660. (options & subprocess_option_inherit_environment)) {
  661. used_environment = environ;
  662. } else {
  663. used_environment = empty_environment;
  664. }
  665. if (0 != posix_spawn_file_actions_init(&actions)) {
  666. return -1;
  667. }
  668. // Close the stdin write end
  669. if (0 != posix_spawn_file_actions_addclose(&actions, stdinfd[1])) {
  670. posix_spawn_file_actions_destroy(&actions);
  671. return -1;
  672. }
  673. // Map the read end to stdin
  674. if (0 !=
  675. posix_spawn_file_actions_adddup2(&actions, stdinfd[0], STDIN_FILENO)) {
  676. posix_spawn_file_actions_destroy(&actions);
  677. return -1;
  678. }
  679. // Close the stdout read end
  680. if (0 != posix_spawn_file_actions_addclose(&actions, stdoutfd[0])) {
  681. posix_spawn_file_actions_destroy(&actions);
  682. return -1;
  683. }
  684. // Map the write end to stdout
  685. if (0 !=
  686. posix_spawn_file_actions_adddup2(&actions, stdoutfd[1], STDOUT_FILENO)) {
  687. posix_spawn_file_actions_destroy(&actions);
  688. return -1;
  689. }
  690. if (subprocess_option_combined_stdout_stderr ==
  691. (options & subprocess_option_combined_stdout_stderr)) {
  692. if (0 != posix_spawn_file_actions_adddup2(&actions, STDOUT_FILENO,
  693. STDERR_FILENO)) {
  694. posix_spawn_file_actions_destroy(&actions);
  695. return -1;
  696. }
  697. } else {
  698. // Close the stderr read end
  699. if (0 != posix_spawn_file_actions_addclose(&actions, stderrfd[0])) {
  700. posix_spawn_file_actions_destroy(&actions);
  701. return -1;
  702. }
  703. // Map the write end to stdout
  704. if (0 != posix_spawn_file_actions_adddup2(&actions, stderrfd[1],
  705. STDERR_FILENO)) {
  706. posix_spawn_file_actions_destroy(&actions);
  707. return -1;
  708. }
  709. }
  710. #ifdef __clang__
  711. #pragma clang diagnostic push
  712. #pragma clang diagnostic ignored "-Wcast-qual"
  713. #pragma clang diagnostic ignored "-Wold-style-cast"
  714. #endif
  715. if (subprocess_option_search_user_path ==
  716. (options & subprocess_option_search_user_path)) {
  717. if (0 != posix_spawnp(&child, commandLine[0], &actions, SUBPROCESS_NULL,
  718. (char *const *)commandLine, used_environment)) {
  719. posix_spawn_file_actions_destroy(&actions);
  720. return -1;
  721. }
  722. } else {
  723. if (0 != posix_spawn(&child, commandLine[0], &actions, SUBPROCESS_NULL,
  724. (char *const *)commandLine, used_environment)) {
  725. posix_spawn_file_actions_destroy(&actions);
  726. return -1;
  727. }
  728. }
  729. #ifdef __clang__
  730. #pragma clang diagnostic pop
  731. #endif
  732. // Close the stdin read end
  733. close(stdinfd[0]);
  734. // Store the stdin write end
  735. out_process->stdin_file = fdopen(stdinfd[1], "wb");
  736. // Close the stdout write end
  737. close(stdoutfd[1]);
  738. // Store the stdout read end
  739. out_process->stdout_file = fdopen(stdoutfd[0], "rb");
  740. if (subprocess_option_combined_stdout_stderr ==
  741. (options & subprocess_option_combined_stdout_stderr)) {
  742. out_process->stderr_file = out_process->stdout_file;
  743. } else {
  744. // Close the stderr write end
  745. close(stderrfd[1]);
  746. // Store the stderr read end
  747. out_process->stderr_file = fdopen(stderrfd[0], "rb");
  748. }
  749. // Store the child's pid
  750. out_process->child = child;
  751. out_process->alive = 1;
  752. posix_spawn_file_actions_destroy(&actions);
  753. return 0;
  754. #endif
  755. }
  756. FILE *subprocess_stdin(const struct subprocess_s *const process) {
  757. return process->stdin_file;
  758. }
  759. FILE *subprocess_stdout(const struct subprocess_s *const process) {
  760. return process->stdout_file;
  761. }
  762. FILE *subprocess_stderr(const struct subprocess_s *const process) {
  763. if (process->stdout_file != process->stderr_file) {
  764. return process->stderr_file;
  765. } else {
  766. return SUBPROCESS_NULL;
  767. }
  768. }
  769. int subprocess_join(struct subprocess_s *const process,
  770. int *const out_return_code) {
  771. #if defined(_MSC_VER)
  772. const unsigned long infinite = 0xFFFFFFFF;
  773. if (process->stdin_file) {
  774. fclose(process->stdin_file);
  775. process->stdin_file = SUBPROCESS_NULL;
  776. }
  777. if (process->hStdInput) {
  778. CloseHandle(process->hStdInput);
  779. process->hStdInput = SUBPROCESS_NULL;
  780. }
  781. WaitForSingleObject(process->hProcess, infinite);
  782. if (out_return_code) {
  783. if (!GetExitCodeProcess(
  784. process->hProcess,
  785. SUBPROCESS_PTR_CAST(unsigned long *, out_return_code))) {
  786. return -1;
  787. }
  788. }
  789. process->alive = 0;
  790. return 0;
  791. #else
  792. int status;
  793. if (process->stdin_file) {
  794. fclose(process->stdin_file);
  795. process->stdin_file = SUBPROCESS_NULL;
  796. }
  797. if (process->child) {
  798. if (process->child != waitpid(process->child, &status, 0)) {
  799. return -1;
  800. }
  801. process->child = 0;
  802. if (WIFEXITED(status)) {
  803. process->return_status = WEXITSTATUS(status);
  804. } else {
  805. process->return_status = EXIT_FAILURE;
  806. }
  807. process->alive = 0;
  808. }
  809. if (out_return_code) {
  810. *out_return_code = process->return_status;
  811. }
  812. return 0;
  813. #endif
  814. }
  815. int subprocess_destroy(struct subprocess_s *const process) {
  816. if (process->stdin_file) {
  817. fclose(process->stdin_file);
  818. process->stdin_file = SUBPROCESS_NULL;
  819. }
  820. if (process->stdout_file) {
  821. fclose(process->stdout_file);
  822. if (process->stdout_file != process->stderr_file) {
  823. fclose(process->stderr_file);
  824. }
  825. process->stdout_file = SUBPROCESS_NULL;
  826. process->stderr_file = SUBPROCESS_NULL;
  827. }
  828. #if defined(_MSC_VER)
  829. if (process->hProcess) {
  830. CloseHandle(process->hProcess);
  831. process->hProcess = SUBPROCESS_NULL;
  832. if (process->hStdInput) {
  833. CloseHandle(process->hStdInput);
  834. }
  835. if (process->hEventOutput) {
  836. CloseHandle(process->hEventOutput);
  837. }
  838. if (process->hEventError) {
  839. CloseHandle(process->hEventError);
  840. }
  841. }
  842. #endif
  843. return 0;
  844. }
  845. int subprocess_terminate(struct subprocess_s *const process) {
  846. #if defined(_MSC_VER)
  847. unsigned int killed_process_exit_code;
  848. int success_terminate;
  849. int windows_call_result;
  850. killed_process_exit_code = 99;
  851. windows_call_result =
  852. TerminateProcess(process->hProcess, killed_process_exit_code);
  853. success_terminate = (windows_call_result == 0) ? 1 : 0;
  854. return success_terminate;
  855. #else
  856. int result;
  857. result = kill(process->child, 9);
  858. return result;
  859. #endif
  860. }
  861. unsigned subprocess_read_stdout(struct subprocess_s *const process,
  862. char *const buffer, unsigned size) {
  863. #if defined(_MSC_VER)
  864. void *handle;
  865. unsigned long bytes_read = 0;
  866. struct subprocess_overlapped_s overlapped = {0, 0, {{0, 0}}, SUBPROCESS_NULL};
  867. overlapped.hEvent = process->hEventOutput;
  868. handle = SUBPROCESS_PTR_CAST(void *,
  869. _get_osfhandle(_fileno(process->stdout_file)));
  870. if (!ReadFile(handle, buffer, size, &bytes_read,
  871. SUBPROCESS_PTR_CAST(LPOVERLAPPED, &overlapped))) {
  872. const unsigned long errorIoPending = 997;
  873. unsigned long error = GetLastError();
  874. // Means we've got an async read!
  875. if (error == errorIoPending) {
  876. if (!GetOverlappedResult(handle,
  877. SUBPROCESS_PTR_CAST(LPOVERLAPPED, &overlapped),
  878. &bytes_read, 1)) {
  879. const unsigned long errorIoIncomplete = 996;
  880. const unsigned long errorHandleEOF = 38;
  881. error = GetLastError();
  882. if ((error != errorIoIncomplete) && (error != errorHandleEOF)) {
  883. return 0;
  884. }
  885. }
  886. }
  887. }
  888. return SUBPROCESS_CAST(unsigned, bytes_read);
  889. #else
  890. const int fd = fileno(process->stdout_file);
  891. const ssize_t bytes_read = read(fd, buffer, size);
  892. if (bytes_read < 0) {
  893. return 0;
  894. }
  895. return SUBPROCESS_CAST(unsigned, bytes_read);
  896. #endif
  897. }
  898. unsigned subprocess_read_stderr(struct subprocess_s *const process,
  899. char *const buffer, unsigned size) {
  900. #if defined(_MSC_VER)
  901. void *handle;
  902. unsigned long bytes_read = 0;
  903. struct subprocess_overlapped_s overlapped = {0, 0, {{0, 0}}, SUBPROCESS_NULL};
  904. overlapped.hEvent = process->hEventError;
  905. handle = SUBPROCESS_PTR_CAST(void *,
  906. _get_osfhandle(_fileno(process->stderr_file)));
  907. if (!ReadFile(handle, buffer, size, &bytes_read,
  908. SUBPROCESS_PTR_CAST(LPOVERLAPPED, &overlapped))) {
  909. const unsigned long errorIoPending = 997;
  910. unsigned long error = GetLastError();
  911. // Means we've got an async read!
  912. if (error == errorIoPending) {
  913. if (!GetOverlappedResult(handle,
  914. SUBPROCESS_PTR_CAST(LPOVERLAPPED, &overlapped),
  915. &bytes_read, 1)) {
  916. const unsigned long errorIoIncomplete = 996;
  917. const unsigned long errorHandleEOF = 38;
  918. error = GetLastError();
  919. if ((error != errorIoIncomplete) && (error != errorHandleEOF)) {
  920. return 0;
  921. }
  922. }
  923. }
  924. }
  925. return SUBPROCESS_CAST(unsigned, bytes_read);
  926. #else
  927. const int fd = fileno(process->stderr_file);
  928. const ssize_t bytes_read = read(fd, buffer, size);
  929. if (bytes_read < 0) {
  930. return 0;
  931. }
  932. return SUBPROCESS_CAST(unsigned, bytes_read);
  933. #endif
  934. }
  935. int subprocess_alive(struct subprocess_s *const process) {
  936. int is_alive = SUBPROCESS_CAST(int, process->alive);
  937. if (!is_alive) {
  938. return 0;
  939. }
  940. #if defined(_MSC_VER)
  941. {
  942. const unsigned long zero = 0x0;
  943. const unsigned long wait_object_0 = 0x00000000L;
  944. is_alive = wait_object_0 != WaitForSingleObject(process->hProcess, zero);
  945. }
  946. #else
  947. {
  948. int status;
  949. is_alive = 0 == waitpid(process->child, &status, WNOHANG);
  950. // If the process was successfully waited on we need to cleanup now.
  951. if (!is_alive) {
  952. if (WIFEXITED(status)) {
  953. process->return_status = WEXITSTATUS(status);
  954. } else {
  955. process->return_status = EXIT_FAILURE;
  956. }
  957. // Since we've already successfully waited on the process, we need to wipe
  958. // the child now.
  959. process->child = 0;
  960. if (subprocess_join(process, SUBPROCESS_NULL)) {
  961. return -1;
  962. }
  963. }
  964. }
  965. #endif
  966. if (!is_alive) {
  967. process->alive = 0;
  968. }
  969. return is_alive;
  970. }
  971. #if defined(__cplusplus)
  972. } // extern "C"
  973. #endif
  974. #endif /* SHEREDOM_SUBPROCESS_H_INCLUDED */