subprocess.h 36 KB

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