Newer
Older
dub_jkp / source / dub / internal / std / processcompat.d
  1. // Written in the D programming language.
  2.  
  3. /**
  4. Functions for starting and interacting with other processes, and for
  5. working with the current process' execution environment.
  6.  
  7. Process_handling:
  8. $(UL $(LI
  9. $(LREF spawnProcess) spawns a new _process, optionally assigning it an
  10. arbitrary set of standard input, output, and error streams.
  11. The function returns immediately, leaving the child _process to execute
  12. in parallel with its parent. All other functions in this module that
  13. spawn processes are built around $(D spawnProcess).)
  14. $(LI
  15. $(LREF wait) makes the parent _process wait for a child _process to
  16. terminate. In general one should always do this, to avoid
  17. child _processes becoming "zombies" when the parent _process exits.
  18. Scope guards are perfect for this – see the $(LREF spawnProcess)
  19. documentation for examples.)
  20. $(LI
  21. $(LREF pipeProcess) also spawns a child _process which runs
  22. in parallel with its parent. However, instead of taking
  23. arbitrary streams, it automatically creates a set of
  24. pipes that allow the parent to communicate with the child
  25. through the child's standard input, output, and/or error streams.
  26. This function corresponds roughly to C's $(D popen) function.)
  27. $(LI
  28. $(LREF execute) starts a new _process and waits for it
  29. to complete before returning. Additionally, it captures
  30. the _process' standard output and error streams and returns
  31. the output of these as a string.)
  32. $(LI
  33. $(LREF spawnShell), $(LREF pipeShell) and $(LREF shell) work like
  34. $(D spawnProcess), $(D pipeProcess) and $(D execute), respectively,
  35. except that they take a single command string and run it through
  36. the current user's default command interpreter.
  37. $(D shell) corresponds roughly to C's $(D system) function.)
  38. $(LI
  39. $(LREF kill) attempts to terminate a running process.)
  40. )
  41. Unless the directory of the executable file is explicitly specified, all
  42. functions will search for it in the directories specified in the PATH
  43. environment variable.
  44.  
  45. Other_functionality:
  46. $(UL
  47. $(LI
  48. $(LREF pipe) is used to create unidirectional pipes.)
  49. $(LI
  50. $(LREF environment) is an interface through which the current process'
  51. environment variables can be read and manipulated.)
  52. )
  53.  
  54. Authors:
  55. $(LINK2 https://github.com/kyllingstad, Lars Tandle Kyllingstad),
  56. $(LINK2 https://github.com/schveiguy, Steven Schveighoffer),
  57. $(LINK2 https://github.com/cybershadow, Vladimir Panteleev)
  58. Copyright:
  59. Copyright (c) 2013, the authors. All rights reserved.
  60. Source:
  61. $(PHOBOSSRC std/_process.d)
  62. Macros:
  63. WIKI=Phobos/StdProcess
  64. OBJECTREF=$(D $(LINK2 object.html#$0,$0))
  65. */
  66. module dub.internal.std.processcompat;
  67.  
  68. version (Posix)
  69. {
  70. import core.stdc.errno;
  71. import core.stdc.string;
  72. import core.sys.posix.stdio;
  73. import core.sys.posix.unistd;
  74. import core.sys.posix.sys.wait;
  75. }
  76. version (Windows)
  77. {
  78. import core.stdc.stdio;
  79. import core.sys.windows.windows;
  80. import std.utf;
  81. import std.windows.syserror;
  82. }
  83. import std.algorithm;
  84. import std.array;
  85. import std.conv;
  86. import std.exception;
  87. import std.path;
  88. import std.stdio;
  89. import std.string;
  90. import std.typecons;
  91.  
  92.  
  93. // When the DMC runtime is used, we have to use some custom functions
  94. // to convert between Windows file handles and FILE*s.
  95. version (Win32) version (DigitalMars) version = DMC_RUNTIME;
  96.  
  97.  
  98. // Some of the following should be moved to druntime.
  99. private:
  100.  
  101. // Windows API declarations.
  102. version (Windows)
  103. {
  104. extern(Windows) BOOL GetHandleInformation(HANDLE hObject,
  105. LPDWORD lpdwFlags);
  106. extern(Windows) BOOL SetHandleInformation(HANDLE hObject,
  107. DWORD dwMask,
  108. DWORD dwFlags);
  109. extern(Windows) BOOL TerminateProcess(HANDLE hProcess,
  110. UINT uExitCode);
  111. extern(Windows) LPWSTR* CommandLineToArgvW(LPCWSTR lpCmdLine,
  112. int* pNumArgs);
  113. enum
  114. {
  115. HANDLE_FLAG_INHERIT = 0x1,
  116. HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x2,
  117. }
  118. enum CREATE_UNICODE_ENVIRONMENT = 0x400;
  119. }
  120.  
  121. // Microsoft Visual C Runtime (MSVCRT) declarations.
  122. version (Windows)
  123. {
  124. version (DMC_RUNTIME) { } else
  125. {
  126. import core.stdc.stdint;
  127. extern(C)
  128. {
  129. int _fileno(FILE* stream);
  130. HANDLE _get_osfhandle(int fd);
  131. int _open_osfhandle(HANDLE osfhandle, int flags);
  132. FILE* _fdopen(int fd, const (char)* mode);
  133. int _close(int fd);
  134. }
  135. enum
  136. {
  137. STDIN_FILENO = 0,
  138. STDOUT_FILENO = 1,
  139. STDERR_FILENO = 2,
  140. }
  141. enum
  142. {
  143. _O_RDONLY = 0x0000,
  144. _O_APPEND = 0x0004,
  145. _O_TEXT = 0x4000,
  146. }
  147. }
  148. }
  149.  
  150. // POSIX API declarations.
  151. version (Posix)
  152. {
  153. version (OSX)
  154. {
  155. // https://www.gnu.org/software/gnulib/manual/html_node/environ.html
  156. extern(C) char*** _NSGetEnviron();
  157. __gshared const char** environ;
  158. shared static this() { environ = *_NSGetEnviron(); }
  159. }
  160. else
  161. {
  162. // Made available by the C runtime:
  163. extern(C) extern __gshared const char** environ;
  164. }
  165. }
  166.  
  167.  
  168. // Actual module classes/functions start here.
  169. public:
  170.  
  171.  
  172. // =============================================================================
  173. // Functions and classes for process management.
  174. // =============================================================================
  175.  
  176.  
  177. /**
  178. Spawns a new _process, optionally assigning it an
  179. arbitrary set of standard input, output, and error streams.
  180. The function returns immediately, leaving the child _process to execute
  181. in parallel with its parent.
  182.  
  183. Command_line:
  184. There are four overloads of this function. The first two take an array
  185. of strings, $(D args), which should contain the program name as the
  186. zeroth element and any command-line arguments in subsequent elements.
  187. The third and fourth versions are included for convenience, and may be
  188. used when there are no command-line arguments. They take a single string,
  189. $(D program), which specifies the program name.
  190.  
  191. Unless a directory is specified in $(D args[0]) or $(D program),
  192. $(D spawnProcess) will search for the program in the directories listed
  193. in the PATH environment variable. To run an executable in the current
  194. directory, use $(D "./$(I executable_name)").
  195. ---
  196. // Run an executable called "prog" located in the current working
  197. // directory:
  198. auto pid = spawnProcess("./prog");
  199. scope(exit) wait(pid);
  200. // We can do something else while the program runs. The scope guard
  201. // ensures that the process is waited for at the end of the scope.
  202. ...
  203.  
  204. // Run DMD on the file "myprog.d", specifying a few compiler switches:
  205. auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
  206. if (wait(dmdPid) != 0)
  207. writeln("Compilation failed!");
  208. ---
  209.  
  210. Environment_variables:
  211. With the first and third $(D spawnProcess) overloads, one can specify
  212. the environment variables of the child process using the $(D environmentVars)
  213. parameter. With the second and fourth overload, the child process inherits
  214. its parent's environment variables.
  215.  
  216. To make the child inherit the parent's environment $(I plus) one or more
  217. additional variables, first use $(D $(LREF environment).$(LREF toAA)) to
  218. obtain an associative array that contains the parent's environment
  219. variables, and add the new variables to it before passing it to
  220. $(D spawnProcess).
  221. ---
  222. auto envVars = environment.toAA();
  223. envVars["FOO"] = "bar";
  224. wait(spawnProcess("prog", envVars));
  225. ---
  226.  
  227. Standard_streams:
  228. The optional arguments $(D stdin_), $(D stdout_) and $(D stderr_) may
  229. be used to assign arbitrary $(XREF stdio,File) objects as the standard
  230. input, output and error streams, respectively, of the child process. The
  231. former must be opened for reading, while the latter two must be opened for
  232. writing. The default is for the child process to inherit the standard
  233. streams of its parent.
  234. ---
  235. // Run DMD on the file myprog.d, logging any error messages to a
  236. // file named errors.log.
  237. auto logFile = File("errors.log", "w");
  238. auto pid = spawnProcess(["dmd", "myprog.d"],
  239. std.stdio.stdin,
  240. std.stdio.stdout,
  241. logFile);
  242. if (wait(pid) != 0)
  243. writeln("Compilation failed. See errors.log for details.");
  244. ---
  245.  
  246. Note that if you pass a $(D File) object that is $(I not)
  247. one of the standard input/output/error streams of the parent process,
  248. that stream will by default be $(I closed) in the parent process when
  249. this function returns. See the $(LREF Config) documentation below for
  250. information about how to disable this behaviour.
  251.  
  252. Beware of buffering issues when passing $(D File) objects to
  253. $(D spawnProcess). The child process will inherit the low-level raw
  254. read/write offset associated with the underlying file descriptor, but
  255. it will not be aware of any buffered data. In cases where this matters
  256. (e.g. when a file should be aligned before being passed on to the
  257. child process), it may be a good idea to use unbuffered streams, or at
  258. least ensure all relevant buffers are flushed.
  259.  
  260. Params:
  261. args = An array which contains the program name as the first element
  262. and any command-line arguments in the following elements.
  263. program = The program name, $(I without) command-line arguments.
  264. environmentVars = The environment variables for the child process may
  265. be specified using this parameter. By default it is $(D null),
  266. which means that, the child process inherits the environment of
  267. the parent process.
  268. stdin_ = The standard input stream of the child process.
  269. This can be any $(XREF stdio,File) that is opened for reading.
  270. By default the child process inherits the parent's input
  271. stream.
  272. stdout_ = The standard output stream of the child process.
  273. This can be any $(XREF stdio,File) that is opened for writing.
  274. By default the child process inherits the parent's output
  275. stream.
  276. stderr_ = The standard error stream of the child process.
  277. This can be any $(XREF stdio,File) that is opened for writing.
  278. By default the child process inherits the parent's error
  279. stream.
  280. config = Options that control the behaviour of $(D spawnProcess).
  281. See the $(LREF Config) documentation for details.
  282.  
  283. Returns:
  284. A $(LREF Pid) object that corresponds to the spawned process.
  285.  
  286. Throws:
  287. $(LREF ProcessException) on failure to start the process.$(BR)
  288. $(XREF stdio,StdioException) on failure to pass one of the streams
  289. to the child process (Windows only).$(BR)
  290. $(CXREF exception,RangeError) if $(D args) is empty.
  291. */
  292. Pid spawnProcess(in char[][] args,
  293. const string[string] environmentVars,
  294. File stdin_ = std.stdio.stdin,
  295. File stdout_ = std.stdio.stdout,
  296. File stderr_ = std.stdio.stderr,
  297. Config config = Config.none)
  298. @trusted // TODO: Should be @safe
  299. {
  300. version (Windows) auto args2 = escapeShellArguments(args);
  301. else version (Posix) alias args2 = args;
  302. return spawnProcessImpl(args2, toEnvz(environmentVars),
  303. stdin_, stdout_, stderr_, config);
  304. }
  305.  
  306. /// ditto
  307. Pid spawnProcess(in char[][] args,
  308. File stdin_ = std.stdio.stdin,
  309. File stdout_ = std.stdio.stdout,
  310. File stderr_ = std.stdio.stderr,
  311. Config config = Config.none)
  312. @trusted // TODO: Should be @safe
  313. {
  314. version (Windows) auto args2 = escapeShellArguments(args);
  315. else version (Posix) alias args2 = args;
  316. return spawnProcessImpl(args2, null, stdin_, stdout_, stderr_, config);
  317. }
  318.  
  319. /// ditto
  320. Pid spawnProcess(in char[] program,
  321. const string[string] environmentVars,
  322. File stdin_ = std.stdio.stdin,
  323. File stdout_ = std.stdio.stdout,
  324. File stderr_ = std.stdio.stderr,
  325. Config config = Config.none)
  326. @trusted
  327. {
  328. return spawnProcess((&program)[0 .. 1], environmentVars,
  329. stdin_, stdout_, stderr_, config);
  330. }
  331.  
  332. /// ditto
  333. Pid spawnProcess(in char[] program,
  334. File stdin_ = std.stdio.stdin,
  335. File stdout_ = std.stdio.stdout,
  336. File stderr_ = std.stdio.stderr,
  337. Config config = Config.none)
  338. @trusted
  339. {
  340. return spawnProcess((&program)[0 .. 1],
  341. stdin_, stdout_, stderr_, config);
  342. }
  343.  
  344. /*
  345. Implementation of spawnProcess() for POSIX.
  346.  
  347. envz should be a zero-terminated array of zero-terminated strings
  348. on the form "var=value".
  349. */
  350. version (Posix)
  351. private Pid spawnProcessImpl(in char[][] args,
  352. const(char*)* envz,
  353. File stdin_,
  354. File stdout_,
  355. File stderr_,
  356. Config config)
  357. @trusted // TODO: Should be @safe
  358. {
  359. const(char)[] name = args[0];
  360. if (any!isDirSeparator(name))
  361. {
  362. if (!isExecutable(name))
  363. throw new ProcessException(text("Not an executable file: ", name));
  364. }
  365. else
  366. {
  367. name = searchPathFor(name);
  368. if (name is null)
  369. throw new ProcessException(text("Executable file not found: ", name));
  370. }
  371.  
  372. // Convert program name and arguments to C-style strings.
  373. auto argz = new const(char)*[args.length+1];
  374. argz[0] = toStringz(name);
  375. foreach (i; 1 .. args.length) argz[i] = toStringz(args[i]);
  376. argz[$-1] = null;
  377.  
  378. // Use parent's environment variables?
  379. if (envz is null) envz = environ;
  380.  
  381. // Get the file descriptors of the streams.
  382. // These could potentially be invalid, but that is OK. If so, later calls
  383. // to dup2() and close() will just silently fail without causing any harm.
  384. auto stdinFD = core.stdc.stdio.fileno(stdin_.getFP());
  385. auto stdoutFD = core.stdc.stdio.fileno(stdout_.getFP());
  386. auto stderrFD = core.stdc.stdio.fileno(stderr_.getFP());
  387.  
  388. auto id = fork();
  389. if (id < 0)
  390. throw ProcessException.newFromErrno("Failed to spawn new process");
  391. if (id == 0)
  392. {
  393. // Child process
  394.  
  395. // Redirect streams and close the old file descriptors.
  396. // In the case that stderr is redirected to stdout, we need
  397. // to backup the file descriptor since stdout may be redirected
  398. // as well.
  399. if (stderrFD == STDOUT_FILENO) stderrFD = dup(stderrFD);
  400. dup2(stdinFD, STDIN_FILENO);
  401. dup2(stdoutFD, STDOUT_FILENO);
  402. dup2(stderrFD, STDERR_FILENO);
  403.  
  404. // Close the old file descriptors, unless they are
  405. // either of the standard streams.
  406. if (stdinFD > STDERR_FILENO) close(stdinFD);
  407. if (stdoutFD > STDERR_FILENO) close(stdoutFD);
  408. if (stderrFD > STDERR_FILENO) close(stderrFD);
  409.  
  410. // Execute program.
  411. execve(argz[0], argz.ptr, envz);
  412.  
  413. // If execution fails, exit as quickly as possible.
  414. perror("spawnProcess(): Failed to execute program");
  415. _exit(1);
  416. assert (0);
  417. }
  418. else
  419. {
  420. // Parent process: Close streams and return.
  421. if (stdinFD > STDERR_FILENO && !(config & Config.noCloseStdin))
  422. stdin_.close();
  423. if (stdoutFD > STDERR_FILENO && !(config & Config.noCloseStdout))
  424. stdout_.close();
  425. if (stderrFD > STDERR_FILENO && !(config & Config.noCloseStderr))
  426. stderr_.close();
  427. return new Pid(id);
  428. }
  429. }
  430.  
  431. /*
  432. Implementation of spawnProcess() for Windows.
  433.  
  434. commandLine must contain the entire command line, properly
  435. quoted/escaped as required by CreateProcessW().
  436.  
  437. envz must be a pointer to a block of UTF-16 characters on the form
  438. "var1=value1\0var2=value2\0...varN=valueN\0\0".
  439. */
  440. version (Windows)
  441. private Pid spawnProcessImpl(in char[] commandLine,
  442. LPVOID envz,
  443. File stdin_,
  444. File stdout_,
  445. File stderr_,
  446. Config config)
  447. @trusted
  448. {
  449. auto commandz = toUTFz!(wchar*)(commandLine);
  450.  
  451. // Startup info for CreateProcessW().
  452. STARTUPINFO_W startinfo;
  453. startinfo.cb = startinfo.sizeof;
  454. startinfo.dwFlags = STARTF_USESTDHANDLES;
  455.  
  456. // Extract file descriptors and HANDLEs from the streams and make the
  457. // handles inheritable.
  458. static void prepareStream(ref File file, DWORD stdHandle, string which,
  459. out int fileDescriptor, out HANDLE handle)
  460. {
  461. fileDescriptor = _fileno(file.getFP());
  462. if (fileDescriptor < 0) handle = GetStdHandle(stdHandle);
  463. else
  464. {
  465. version (DMC_RUNTIME) handle = _fdToHandle(fileDescriptor);
  466. else /* MSVCRT */ handle = _get_osfhandle(fileDescriptor);
  467. }
  468. DWORD dwFlags;
  469. GetHandleInformation(handle, &dwFlags);
  470. if (!(dwFlags & HANDLE_FLAG_INHERIT))
  471. {
  472. if (!SetHandleInformation(handle,
  473. HANDLE_FLAG_INHERIT,
  474. HANDLE_FLAG_INHERIT))
  475. {
  476. throw new StdioException(
  477. "Failed to make "~which~" stream inheritable by child process ("
  478. ~sysErrorString(GetLastError()) ~ ')',
  479. 0);
  480. }
  481. }
  482. }
  483. int stdinFD = -1, stdoutFD = -1, stderrFD = -1;
  484. prepareStream(stdin_, STD_INPUT_HANDLE, "stdin" , stdinFD, startinfo.hStdInput );
  485. prepareStream(stdout_, STD_OUTPUT_HANDLE, "stdout", stdoutFD, startinfo.hStdOutput);
  486. prepareStream(stderr_, STD_ERROR_HANDLE, "stderr", stderrFD, startinfo.hStdError );
  487.  
  488. // Create process.
  489. PROCESS_INFORMATION pi;
  490. DWORD dwCreationFlags = CREATE_UNICODE_ENVIRONMENT |
  491. ((config & Config.gui) ? CREATE_NO_WINDOW : 0);
  492. if (!CreateProcessW(null, commandz, null, null, true, dwCreationFlags,
  493. envz, null, &startinfo, &pi))
  494. throw ProcessException.newFromLastError("Failed to spawn new process");
  495.  
  496. // figure out if we should close any of the streams
  497. if (stdinFD > STDERR_FILENO && !(config & Config.noCloseStdin))
  498. stdin_.close();
  499. if (stdoutFD > STDERR_FILENO && !(config & Config.noCloseStdout))
  500. stdout_.close();
  501. if (stderrFD > STDERR_FILENO && !(config & Config.noCloseStderr))
  502. stderr_.close();
  503.  
  504. // close the thread handle in the process info structure
  505. CloseHandle(pi.hThread);
  506.  
  507. return new Pid(pi.dwProcessId, pi.hProcess);
  508. }
  509.  
  510. // Searches the PATH variable for the given executable file,
  511. // (checking that it is in fact executable).
  512. version (Posix)
  513. private string searchPathFor(in char[] executable)
  514. @trusted //TODO: @safe nothrow
  515. {
  516. auto pathz = core.stdc.stdlib.getenv("PATH");
  517. if (pathz == null) return null;
  518.  
  519. foreach (dir; splitter(to!string(pathz), ':'))
  520. {
  521. auto execPath = buildPath(dir, executable);
  522. if (isExecutable(execPath)) return execPath;
  523. }
  524.  
  525. return null;
  526. }
  527.  
  528. // Converts a string[string] array to a C array of C strings
  529. // on the form "key=value".
  530. version (Posix)
  531. private const(char)** toEnvz(const string[string] env)
  532. @trusted //TODO: @safe pure nothrow
  533. {
  534. alias const(char)* stringz_t;
  535. auto envz = new stringz_t[](env.length+1);
  536. int i = 0;
  537. foreach (k, v; env) envz[i++] = (k~'='~v~'\0').ptr;
  538. envz[i] = null;
  539. return envz.ptr;
  540. }
  541.  
  542. // Converts a string[string] array to a block of 16-bit
  543. // characters on the form "key=value\0key=value\0...\0\0"
  544. version (Windows)
  545. private LPVOID toEnvz(const string[string] env)
  546. @trusted //TODO: @safe pure nothrow
  547. {
  548. auto envz = appender!(wchar[])();
  549. foreach(k, v; env)
  550. {
  551. envz.put(k);
  552. envz.put('=');
  553. envz.put(v);
  554. envz.put('\0');
  555. }
  556. envz.put('\0');
  557. return envz.data.ptr;
  558. }
  559.  
  560. // Checks whether the file exists and can be executed by the
  561. // current user.
  562. version (Posix)
  563. private bool isExecutable(in char[] path) @trusted //TODO: @safe nothrow
  564. {
  565. return (access(toStringz(path), X_OK) == 0);
  566. }
  567.  
  568.  
  569. /**
  570. A variation on $(LREF spawnProcess) that runs the given _command through
  571. the current user's preferred _command interpreter (aka. shell).
  572.  
  573. The string $(D command) is passed verbatim to the shell, and is therefore
  574. subject to its rules about _command structure, argument/filename quoting
  575. and escaping of special characters.
  576. The path to the shell executable is determined by the $(LREF userShell)
  577. function.
  578.  
  579. In all other respects this function works just like $(D spawnProcess).
  580. Please refer to the $(LREF spawnProcess) documentation for descriptions
  581. of the other function parameters, the return value and any exceptions
  582. that may be thrown.
  583. ---
  584. // Run the command/program "foo" on the file named "my file.txt", and
  585. // redirect its output into foo.log.
  586. auto pid = spawnShell(`foo "my file.txt" > foo.log`);
  587. wait(pid);
  588. ---
  589.  
  590. See_also:
  591. $(LREF escapeShellCommand), which may be helpful in constructing a
  592. properly quoted and escaped shell command line for the current plattform,
  593. from an array of separate arguments.
  594. */
  595. Pid spawnShell(in char[] command,
  596. const string[string] environmentVars,
  597. File stdin_ = std.stdio.stdin,
  598. File stdout_ = std.stdio.stdout,
  599. File stderr_ = std.stdio.stderr,
  600. Config config = Config.none)
  601. @trusted // TODO: Should be @safe
  602. {
  603. return spawnShellImpl(command, toEnvz(environmentVars),
  604. stdin_, stdout_, stderr_, config);
  605. }
  606.  
  607. /// ditto
  608. Pid spawnShell(in char[] command,
  609. File stdin_ = std.stdio.stdin,
  610. File stdout_ = std.stdio.stdout,
  611. File stderr_ = std.stdio.stderr,
  612. Config config = Config.none)
  613. @trusted // TODO: Should be @safe
  614. {
  615. return spawnShellImpl(command, null, stdin_, stdout_, stderr_, config);
  616. }
  617.  
  618. // Implementation of spawnShell() for Windows.
  619. version(Windows)
  620. private Pid spawnShellImpl(in char[] command,
  621. LPVOID envz,
  622. File stdin_ = std.stdio.stdin,
  623. File stdout_ = std.stdio.stdout,
  624. File stderr_ = std.stdio.stderr,
  625. Config config = Config.none)
  626. @trusted // TODO: Should be @safe
  627. {
  628. auto scmd = escapeShellArguments(userShell, shellSwitch) ~ " " ~ command;
  629. return spawnProcessImpl(scmd, envz, stdin_, stdout_, stderr_, config);
  630. }
  631.  
  632. // Implementation of spawnShell() for POSIX.
  633. version(Posix)
  634. private Pid spawnShellImpl(in char[] command,
  635. const char** envz,
  636. File stdin_ = std.stdio.stdin,
  637. File stdout_ = std.stdio.stdout,
  638. File stderr_ = std.stdio.stderr,
  639. Config config = Config.none)
  640. @trusted // TODO: Should be @safe
  641. {
  642. const(char)[][3] args;
  643. args[0] = userShell;
  644. args[1] = shellSwitch;
  645. args[2] = command;
  646. return spawnProcessImpl(args, envz, stdin_, stdout_, stderr_, config);
  647. }
  648.  
  649.  
  650.  
  651. /**
  652. Flags that control the behaviour of $(LREF spawnProcess) and
  653. $(LREF spawnShell).
  654.  
  655. Use bitwise OR to combine flags.
  656.  
  657. Example:
  658. ---
  659. auto logFile = File("myapp_error.log", "w");
  660.  
  661. // Start program in a console window (Windows only), redirect
  662. // its error stream to logFile, and leave logFile open in the
  663. // parent process as well.
  664. auto pid = spawnProcess("myapp", stdin, stdout, logFile,
  665. Config.noCloseStderr | Config.gui);
  666. scope(exit)
  667. {
  668. auto exitCode = wait(pid);
  669. logFile.writeln("myapp exited with code ", exitCode);
  670. logFile.close();
  671. }
  672. ---
  673. */
  674. enum Config
  675. {
  676. none = 0,
  677.  
  678. /**
  679. Unless the child process inherits the standard
  680. input/output/error streams of its parent, one almost
  681. always wants the streams closed in the parent when
  682. $(LREF spawnProcess) returns. Therefore, by default, this
  683. is done. If this is not desirable, pass any of these
  684. options to spawnProcess.
  685. */
  686. noCloseStdin = 1,
  687. noCloseStdout = 2, /// ditto
  688. noCloseStderr = 4, /// ditto
  689.  
  690. /**
  691. On Windows, the child process will by default be run in
  692. a console window. This option wil cause it to run in "GUI mode"
  693. instead, i.e., without a console. On POSIX, it has no effect.
  694. */
  695. gui = 8,
  696. }
  697.  
  698.  
  699. /// A handle that corresponds to a spawned process.
  700. final class Pid
  701. {
  702. /**
  703. The process ID number.
  704.  
  705. This is a number that uniquely identifies the process on the operating
  706. system, for at least as long as the process is running. Once $(LREF wait)
  707. has been called on the $(LREF Pid), this method will return an
  708. invalid process ID.
  709. */
  710. @property int processID() const @safe pure nothrow
  711. {
  712. return _processID;
  713. }
  714.  
  715. /**
  716. An operating system handle to the process.
  717.  
  718. This handle is used to specify the process in OS-specific APIs.
  719. On POSIX, this function returns a $(D core.sys.posix.sys.types.pid_t)
  720. with the same value as $(LREF processID), while on Windows it returns
  721. a $(D core.sys.windows.windows.HANDLE).
  722.  
  723. Once $(LREF wait) has been called on the $(LREF Pid), this method
  724. will return an invalid handle.
  725. */
  726. // Note: Since HANDLE is a reference, this function cannot be const.
  727. version (Windows)
  728. @property HANDLE osHandle() @safe pure nothrow
  729. {
  730. return _handle;
  731. }
  732. else version (Posix)
  733. @property pid_t osHandle() @safe pure nothrow
  734. {
  735. return _processID;
  736. }
  737.  
  738. private:
  739. /*
  740. Pid.performWait() does the dirty work for wait() and nonBlockingWait().
  741.  
  742. If block == true, this function blocks until the process terminates,
  743. sets _processID to terminated, and returns the exit code or terminating
  744. signal as described in the wait() documentation.
  745.  
  746. If block == false, this function returns immediately, regardless
  747. of the status of the process. If the process has terminated, the
  748. function has the exact same effect as the blocking version. If not,
  749. it returns 0 and does not modify _processID.
  750. */
  751. version (Posix)
  752. int performWait(bool block) @trusted
  753. {
  754. if (_processID == terminated) return _exitCode;
  755. int exitCode;
  756. while(true)
  757. {
  758. int status;
  759. auto check = waitpid(_processID, &status, block ? 0 : WNOHANG);
  760. if (check == -1)
  761. {
  762. if (errno == ECHILD)
  763. {
  764. throw new ProcessException(
  765. "Process does not exist or is not a child process.");
  766. }
  767. else
  768. {
  769. // waitpid() was interrupted by a signal. We simply
  770. // restart it.
  771. assert (errno == EINTR);
  772. continue;
  773. }
  774. }
  775. if (!block && check == 0) return 0;
  776. if (WIFEXITED(status))
  777. {
  778. exitCode = WEXITSTATUS(status);
  779. break;
  780. }
  781. else if (WIFSIGNALED(status))
  782. {
  783. exitCode = -WTERMSIG(status);
  784. break;
  785. }
  786. // We check again whether the call should be blocking,
  787. // since we don't care about other status changes besides
  788. // "exited" and "terminated by signal".
  789. if (!block) return 0;
  790.  
  791. // Process has stopped, but not terminated, so we continue waiting.
  792. }
  793. // Mark Pid as terminated, and cache and return exit code.
  794. _processID = terminated;
  795. _exitCode = exitCode;
  796. return exitCode;
  797. }
  798. else version (Windows)
  799. {
  800. int performWait(bool block) @trusted
  801. {
  802. if (_processID == terminated) return _exitCode;
  803. assert (_handle != INVALID_HANDLE_VALUE);
  804. if (block)
  805. {
  806. auto result = WaitForSingleObject(_handle, INFINITE);
  807. if (result != WAIT_OBJECT_0)
  808. throw ProcessException.newFromLastError("Wait failed.");
  809. }
  810. if (!GetExitCodeProcess(_handle, cast(LPDWORD)&_exitCode))
  811. throw ProcessException.newFromLastError();
  812. if (!block && _exitCode == STILL_ACTIVE) return 0;
  813. CloseHandle(_handle);
  814. _handle = INVALID_HANDLE_VALUE;
  815. _processID = terminated;
  816. return _exitCode;
  817. }
  818.  
  819. ~this()
  820. {
  821. if(_handle != INVALID_HANDLE_VALUE)
  822. {
  823. CloseHandle(_handle);
  824. _handle = INVALID_HANDLE_VALUE;
  825. }
  826. }
  827. }
  828.  
  829. // Special values for _processID.
  830. enum invalid = -1, terminated = -2;
  831.  
  832. // OS process ID number. Only nonnegative IDs correspond to
  833. // running processes.
  834. int _processID = invalid;
  835.  
  836. // Exit code cached by wait(). This is only expected to hold a
  837. // sensible value if _processID == terminated.
  838. int _exitCode;
  839.  
  840. // Pids are only meant to be constructed inside this module, so
  841. // we make the constructor private.
  842. version (Windows)
  843. {
  844. HANDLE _handle;
  845. this(int pid, HANDLE handle) @safe pure nothrow
  846. {
  847. _processID = pid;
  848. _handle = handle;
  849. }
  850. }
  851. else
  852. {
  853. this(int id) @safe pure nothrow
  854. {
  855. _processID = id;
  856. }
  857. }
  858. }
  859.  
  860.  
  861. /**
  862. Waits for the process associated with $(D pid) to terminate, and returns
  863. its exit status.
  864.  
  865. In general one should always _wait for child processes to terminate
  866. before exiting the parent process. Otherwise, they may become
  867. "$(WEB en.wikipedia.org/wiki/Zombie_process,zombies)" – processes
  868. that are defunct, yet still occupy a slot in the OS process table.
  869.  
  870. If the process has already terminated, this function returns directly.
  871. The exit code is cached, so that if wait() is called multiple times on
  872. the same $(LREF Pid) it will always return the same value.
  873.  
  874. POSIX_specific:
  875. If the process is terminated by a signal, this function returns a
  876. negative number whose absolute value is the signal number.
  877. Since POSIX restricts normal exit codes to the range 0-255, a
  878. negative return value will always indicate termination by signal.
  879. Signal codes are defined in the $(D core.sys.posix.signal) module
  880. (which corresponds to the $(D signal.h) POSIX header).
  881.  
  882. Throws:
  883. $(LREF ProcessException) on failure.
  884.  
  885. Examples:
  886. See the $(LREF spawnProcess) documentation.
  887.  
  888. See_also:
  889. $(LREF tryWait), for a non-blocking function.
  890. */
  891. int wait(Pid pid) @safe
  892. {
  893. assert(pid !is null, "Called wait on a null Pid.");
  894. return pid.performWait(true);
  895. }
  896.  
  897.  
  898. /**
  899. A non-blocking version of $(LREF wait).
  900.  
  901. If the process associated with $(D pid) has already terminated,
  902. $(D tryWait) has the exact same effect as $(D wait).
  903. In this case, it returns a tuple where the $(D terminated) field
  904. is set to $(D true) and the $(D status) field has the same
  905. interpretation as the return value of $(D wait).
  906.  
  907. If the process has $(I not) yet terminated, this function differs
  908. from $(D wait) in that does not wait for this to happen, but instead
  909. returns immediately. The $(D terminated) field of the returned
  910. tuple will then be set to $(D false), while the $(D status) field
  911. will always be 0 (zero). $(D wait) or $(D tryWait) should then be
  912. called again on the same $(D Pid) at some later time; not only to
  913. get the exit code, but also to avoid the process becoming a "zombie"
  914. when it finally terminates. (See $(LREF wait) for details).
  915.  
  916. Throws:
  917. $(LREF ProcessException) on failure.
  918.  
  919. Example:
  920. ---
  921. auto pid = spawnProcess("dmd myapp.d");
  922. scope(exit) wait(pid);
  923. ...
  924. auto dmd = tryWait(pid);
  925. if (dmd.terminated)
  926. {
  927. if (dmd.status == 0) writeln("Compilation succeeded!");
  928. else writeln("Compilation failed");
  929. }
  930. else writeln("Still compiling...");
  931. ...
  932. ---
  933. Note that in this example, the first $(D wait) call will have no
  934. effect if the process has already terminated by the time $(D tryWait)
  935. is called. In the opposite case, however, the $(D scope) statement
  936. ensures that we always wait for the process if it hasn't terminated
  937. by the time we reach the end of the scope.
  938. */
  939. Tuple!(bool, "terminated", int, "status") tryWait(Pid pid) @safe
  940. {
  941. assert(pid !is null, "Called tryWait on a null Pid.");
  942. auto code = pid.performWait(false);
  943. return typeof(return)(pid._processID == Pid.terminated, code);
  944. }
  945.  
  946.  
  947. /**
  948. Attempts to terminate the process associated with $(D pid).
  949.  
  950. The effect of this function, as well as the meaning of $(D codeOrSignal),
  951. is highly platform dependent. Details are given below. Common to all
  952. platforms is that this function only $(I initiates) termination of the process,
  953. and returns immediately. It does not wait for the process to end,
  954. nor does it guarantee that the process does in fact get terminated.
  955.  
  956. Always call $(LREF wait) to wait for a process to complete, even if $(D kill)
  957. has been called on it.
  958.  
  959. Windows_specific:
  960. The process will be
  961. $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/ms686714%28v=vs.100%29.aspx,
  962. forcefully and abruptly terminated). If $(D codeOrSignal) is specified, it
  963. will be used as the exit code of the process. If not, the process wil exit
  964. with code 1. Do not use $(D codeOrSignal = 259), as this is a special value
  965. (aka. $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/ms683189.aspx,
  966. STILL_ACTIVE)) used by Windows to signal that a process has in fact $(I not)
  967. terminated yet.
  968. ---
  969. auto pid = spawnProcess("some_app");
  970. kill(pid, 10);
  971. assert (wait(pid) == 10);
  972. ---
  973.  
  974. POSIX_specific:
  975. A $(LINK2 http://en.wikipedia.org/wiki/Unix_signal,signal) will be sent to
  976. the process, whose value is given by $(D codeOrSignal). Depending on the
  977. signal sent, this may or may not terminate the process. Symbolic constants
  978. for various $(LINK2 http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals,
  979. POSIX signals) are defined in $(D core.sys.posix.signal), which corresponds to the
  980. $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html,
  981. $(D signal.h) POSIX header). If $(D codeOrSignal) is omitted, the
  982. $(D SIGTERM) signal will be sent. (This matches the behaviour of the
  983. $(LINK2 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/kill.html,
  984. $(D _kill)) shell command.)
  985. ---
  986. import core.sys.posix.signal: SIGKILL;
  987. auto pid = spawnProcess("some_app");
  988. kill(pid, SIGKILL);
  989. assert (wait(pid) == -SIGKILL); // Negative return value on POSIX!
  990. ---
  991.  
  992. Throws:
  993. $(LREF ProcessException) if the operating system reports an error.
  994. (Note that this does not include failure to terminate the process,
  995. which is considered a "normal" outcome.)$(BR)
  996. $(OBJECTREF Error) if $(D codeOrSignal) is negative.
  997. */
  998. void kill(Pid pid)
  999. {
  1000. version (Windows) kill(pid, 1);
  1001. else version (Posix)
  1002. {
  1003. import core.sys.posix.signal: SIGTERM;
  1004. kill(pid, SIGTERM);
  1005. }
  1006. }
  1007.  
  1008. /// ditto
  1009. void kill(Pid pid, int codeOrSignal)
  1010. {
  1011. version (Windows) enum errMsg = "Invalid exit code";
  1012. else version (Posix) enum errMsg = "Invalid signal";
  1013. if (codeOrSignal < 0) throw new Error(errMsg);
  1014.  
  1015. version (Windows)
  1016. {
  1017. if (!TerminateProcess(pid.osHandle, codeOrSignal))
  1018. throw ProcessException.newFromLastError();
  1019. }
  1020. else version (Posix)
  1021. {
  1022. import core.sys.posix.signal;
  1023. if (kill(pid.osHandle, codeOrSignal) == -1)
  1024. throw ProcessException.newFromErrno();
  1025. }
  1026. }
  1027.  
  1028.  
  1029. private File encapPipeAsFile(FILE* fil)
  1030. {
  1031. static struct Impl
  1032. {
  1033. FILE * handle = null; // Is null iff this Impl is closed by another File
  1034. uint refs = uint.max / 2;
  1035. bool isPipe;
  1036. }
  1037. auto f = File.wrapFile(fil);
  1038. auto imp = *cast(Impl**)&f;
  1039. imp.refs = 1;
  1040. imp.isPipe = false;
  1041. return f;
  1042. }
  1043.  
  1044. /**
  1045. Creates a unidirectional _pipe.
  1046.  
  1047. Data is written to one end of the _pipe and read from the other.
  1048. ---
  1049. auto p = pipe();
  1050. p.writeEnd.writeln("Hello World");
  1051. assert (p.readEnd.readln().chomp() == "Hello World");
  1052. ---
  1053. Pipes can, for example, be used for interprocess communication
  1054. by spawning a new process and passing one end of the _pipe to
  1055. the child, while the parent uses the other end.
  1056. (See also $(LREF pipeProcess) and $(LREF pipeShell) for an easier
  1057. way of doing this.)
  1058. ---
  1059. // Use cURL to download the dlang.org front page, pipe its
  1060. // output to grep to extract a list of links to ZIP files,
  1061. // and write the list to the file "D downloads.txt":
  1062. auto p = pipe();
  1063. auto outFile = File("D downloads.txt", "w");
  1064. auto cpid = spawnProcess(["curl", "http://dlang.org/download.html"],
  1065. std.stdio.stdin, p.writeEnd);
  1066. scope(exit) wait(cpid);
  1067. auto gpid = spawnProcess(["grep", "-o", `http://\S*\.zip`],
  1068. p.readEnd, outFile);
  1069. scope(exit) wait(gpid);
  1070. ---
  1071.  
  1072. Returns:
  1073. A $(LREF Pipe) object that corresponds to the created _pipe.
  1074.  
  1075. Throws:
  1076. $(XREF stdio,StdioException) on failure.
  1077. */
  1078. version (Posix)
  1079. Pipe pipe() @trusted //TODO: @safe
  1080. {
  1081. int[2] fds;
  1082. errnoEnforce(core.sys.posix.unistd.pipe(fds) == 0,
  1083. "Unable to create pipe");
  1084. Pipe p;
  1085. auto readFP = fdopen(fds[0], "r");
  1086. if (readFP == null)
  1087. throw new StdioException("Cannot open read end of pipe");
  1088. p._read = encapPipeAsFile(readFP);
  1089. auto writeFP = fdopen(fds[1], "w");
  1090. if (writeFP == null)
  1091. throw new StdioException("Cannot open write end of pipe");
  1092. p._write = encapPipeAsFile(writeFP);
  1093. return p;
  1094. }
  1095. else version (Windows)
  1096. Pipe pipe() @trusted //TODO: @safe
  1097. {
  1098. // use CreatePipe to create an anonymous pipe
  1099. HANDLE readHandle;
  1100. HANDLE writeHandle;
  1101. if (!CreatePipe(&readHandle, &writeHandle, null, 0))
  1102. {
  1103. throw new StdioException(
  1104. "Error creating pipe (" ~ sysErrorString(GetLastError()) ~ ')',
  1105. 0);
  1106. }
  1107.  
  1108. // Create file descriptors from the handles
  1109. version (DMC_RUNTIME)
  1110. {
  1111. auto readFD = _handleToFD(readHandle, FHND_DEVICE);
  1112. auto writeFD = _handleToFD(writeHandle, FHND_DEVICE);
  1113. }
  1114. else // MSVCRT
  1115. {
  1116. auto readFD = _open_osfhandle(readHandle, _O_RDONLY);
  1117. auto writeFD = _open_osfhandle(writeHandle, _O_APPEND);
  1118. }
  1119. version (DMC_RUNTIME) alias .close _close;
  1120. if (readFD == -1 || writeFD == -1)
  1121. {
  1122. // Close file descriptors, then throw.
  1123. if (readFD >= 0) _close(readFD);
  1124. else CloseHandle(readHandle);
  1125. if (writeFD >= 0) _close(writeFD);
  1126. else CloseHandle(writeHandle);
  1127. throw new StdioException("Error creating pipe");
  1128. }
  1129.  
  1130. // Create FILE pointers from the file descriptors
  1131. Pipe p;
  1132. version (DMC_RUNTIME)
  1133. {
  1134. // This is a re-implementation of DMC's fdopen, but without the
  1135. // mucking with the file descriptor. POSIX standard requires the
  1136. // new fdopen'd file to retain the given file descriptor's
  1137. // position.
  1138. FILE * local_fdopen(int fd, const(char)* mode)
  1139. {
  1140. auto fp = core.stdc.stdio.fopen("NUL", mode);
  1141. if(!fp) return null;
  1142. FLOCK(fp);
  1143. auto iob = cast(_iobuf*)fp;
  1144. .close(iob._file);
  1145. iob._file = fd;
  1146. iob._flag &= ~_IOTRAN;
  1147. FUNLOCK(fp);
  1148. return fp;
  1149. }
  1150.  
  1151. auto readFP = local_fdopen(readFD, "r");
  1152. auto writeFP = local_fdopen(writeFD, "a");
  1153. }
  1154. else // MSVCRT
  1155. {
  1156. auto readFP = _fdopen(readFD, "r");
  1157. auto writeFP = _fdopen(writeFD, "a");
  1158. }
  1159. if (readFP == null || writeFP == null)
  1160. {
  1161. // Close streams, then throw.
  1162. if (readFP != null) fclose(readFP);
  1163. else _close(readFD);
  1164. if (writeFP != null) fclose(writeFP);
  1165. else _close(writeFD);
  1166. throw new StdioException("Cannot open pipe");
  1167. }
  1168. p._read = encapPipeAsFile(readFP);
  1169. p._write = encapPipeAsFile(writeFP);
  1170. return p;
  1171. }
  1172.  
  1173.  
  1174. /// An interface to a pipe created by the $(LREF pipe) function.
  1175. struct Pipe
  1176. {
  1177. /// The read end of the pipe.
  1178. @property File readEnd() @trusted /*TODO: @safe nothrow*/ { return _read; }
  1179.  
  1180.  
  1181. /// The write end of the pipe.
  1182. @property File writeEnd() @trusted /*TODO: @safe nothrow*/ { return _write; }
  1183.  
  1184.  
  1185. /**
  1186. Closes both ends of the pipe.
  1187.  
  1188. Normally it is not necessary to do this manually, as $(XREF stdio,File)
  1189. objects are automatically closed when there are no more references
  1190. to them.
  1191.  
  1192. Note that if either end of the pipe has been passed to a child process,
  1193. it will only be closed in the parent process. (What happens in the
  1194. child process is platform dependent.)
  1195. */
  1196. void close() @trusted //TODO: @safe nothrow
  1197. {
  1198. _read.close();
  1199. _write.close();
  1200. }
  1201.  
  1202. private:
  1203. File _read, _write;
  1204. }
  1205.  
  1206.  
  1207. /**
  1208. Starts a new process, creating pipes to redirect its standard
  1209. input, output and/or error streams.
  1210.  
  1211. These functions return immediately, leaving the child process to
  1212. execute in parallel with the parent.
  1213. $(LREF pipeShell) invokes the user's _command interpreter, as
  1214. determined by $(LREF userShell), to execute the given program or
  1215. _command.
  1216.  
  1217. Returns:
  1218. A $(LREF ProcessPipes) object which contains $(XREF stdio,File)
  1219. handles that communicate with the redirected streams of the child
  1220. process, along with the $(LREF Pid) of the process.
  1221.  
  1222. Throws:
  1223. $(LREF ProcessException) on failure to start the process.$(BR)
  1224. $(XREF stdio,StdioException) on failure to create pipes.$(BR)
  1225. $(OBJECTREF Error) if $(D redirectFlags) is an invalid combination of flags.
  1226.  
  1227. Example:
  1228. ---
  1229. auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr);
  1230. scope(exit) wait(pipes.pid);
  1231.  
  1232. // Store lines of output.
  1233. string[] output;
  1234. foreach (line; pipes.stdout.byLine) output ~= line.idup;
  1235.  
  1236. // Store lines of errors.
  1237. string[] errors;
  1238. foreach (line; pipes.stderr.byLine) errors ~= line.idup;
  1239. ---
  1240. */
  1241. ProcessPipes pipeProcess(string program,
  1242. Redirect redirectFlags = Redirect.all)
  1243. @trusted
  1244. {
  1245. return pipeProcessImpl!spawnProcess(program, redirectFlags);
  1246. }
  1247.  
  1248. /// ditto
  1249. ProcessPipes pipeProcess(string[] args,
  1250. Redirect redirectFlags = Redirect.all)
  1251. @trusted //TODO: @safe
  1252. {
  1253. return pipeProcessImpl!spawnProcess(args, redirectFlags);
  1254. }
  1255.  
  1256. /// ditto
  1257. ProcessPipes pipeShell(string command, Redirect redirectFlags = Redirect.all)
  1258. @safe
  1259. {
  1260. return pipeProcessImpl!spawnShell(command, redirectFlags);
  1261. }
  1262.  
  1263. // Implementation of the pipeProcess() family of functions.
  1264. private ProcessPipes pipeProcessImpl(alias spawnFunc, Cmd)
  1265. (Cmd command, Redirect redirectFlags)
  1266. @trusted //TODO: @safe
  1267. {
  1268. File childStdin, childStdout, childStderr;
  1269. ProcessPipes pipes;
  1270. pipes._redirectFlags = redirectFlags;
  1271.  
  1272. if (redirectFlags & Redirect.stdin)
  1273. {
  1274. auto p = pipe();
  1275. childStdin = p.readEnd;
  1276. pipes._stdin = p.writeEnd;
  1277. }
  1278. else
  1279. {
  1280. childStdin = std.stdio.stdin;
  1281. }
  1282.  
  1283. if (redirectFlags & Redirect.stdout)
  1284. {
  1285. if ((redirectFlags & Redirect.stdoutToStderr) != 0)
  1286. throw new Error("Invalid combination of options: Redirect.stdout | "
  1287. ~"Redirect.stdoutToStderr");
  1288. auto p = pipe();
  1289. childStdout = p.writeEnd;
  1290. pipes._stdout = p.readEnd;
  1291. }
  1292. else
  1293. {
  1294. childStdout = std.stdio.stdout;
  1295. }
  1296.  
  1297. if (redirectFlags & Redirect.stderr)
  1298. {
  1299. if ((redirectFlags & Redirect.stderrToStdout) != 0)
  1300. throw new Error("Invalid combination of options: Redirect.stderr | "
  1301. ~"Redirect.stderrToStdout");
  1302. auto p = pipe();
  1303. childStderr = p.writeEnd;
  1304. pipes._stderr = p.readEnd;
  1305. }
  1306. else
  1307. {
  1308. childStderr = std.stdio.stderr;
  1309. }
  1310.  
  1311. if (redirectFlags & Redirect.stdoutToStderr)
  1312. {
  1313. if (redirectFlags & Redirect.stderrToStdout)
  1314. {
  1315. // We know that neither of the other options have been
  1316. // set, so we assign the std.stdio.std* streams directly.
  1317. childStdout = std.stdio.stderr;
  1318. childStderr = std.stdio.stdout;
  1319. }
  1320. else
  1321. {
  1322. childStdout = childStderr;
  1323. }
  1324. }
  1325. else if (redirectFlags & Redirect.stderrToStdout)
  1326. {
  1327. childStderr = childStdout;
  1328. }
  1329.  
  1330. pipes._pid = spawnFunc(command, null, childStdin, childStdout, childStderr);
  1331. return pipes;
  1332. }
  1333.  
  1334.  
  1335. /**
  1336. Flags that can be passed to $(LREF pipeProcess) and $(LREF pipeShell)
  1337. to specify which of the child process' standard streams are redirected.
  1338. Use bitwise OR to combine flags.
  1339. */
  1340. enum Redirect
  1341. {
  1342. /// Redirect the standard input, output or error streams, respectively.
  1343. stdin = 1,
  1344. stdout = 2, /// ditto
  1345. stderr = 4, /// ditto
  1346.  
  1347. /**
  1348. Redirect _all three streams. This is equivalent to
  1349. $(D Redirect.stdin | Redirect.stdout | Redirect.stderr).
  1350. */
  1351. all = stdin | stdout | stderr,
  1352.  
  1353. /**
  1354. Redirect the standard error stream into the standard output stream.
  1355. This can not be combined with $(D Redirect.stderr).
  1356. */
  1357. stderrToStdout = 8,
  1358.  
  1359. /**
  1360. Redirect the standard output stream into the standard error stream.
  1361. This can not be combined with $(D Redirect.stdout).
  1362. */
  1363. stdoutToStderr = 16,
  1364. }
  1365.  
  1366.  
  1367. /**
  1368. Object which contains $(XREF stdio,File) handles that allow communication
  1369. with a child process through its standard streams.
  1370. */
  1371. struct ProcessPipes
  1372. {
  1373. /// The $(LREF Pid) of the child process.
  1374. @property Pid pid() @safe nothrow
  1375. {
  1376. assert(_pid !is null);
  1377. return _pid;
  1378. }
  1379.  
  1380. /**
  1381. An $(XREF stdio,File) that allows writing to the child process'
  1382. standard input stream.
  1383.  
  1384. Throws:
  1385. $(OBJECTREF Error) if the child process' standard input stream hasn't
  1386. been redirected.
  1387. */
  1388. @property File stdin() @trusted //TODO: @safe nothrow
  1389. {
  1390. if ((_redirectFlags & Redirect.stdin) == 0)
  1391. throw new Error("Child process' standard input stream hasn't "
  1392. ~"been redirected.");
  1393. return _stdin;
  1394. }
  1395.  
  1396. /**
  1397. An $(XREF stdio,File) that allows reading from the child process'
  1398. standard output stream.
  1399.  
  1400. Throws:
  1401. $(OBJECTREF Error) if the child process' standard output stream hasn't
  1402. been redirected.
  1403. */
  1404. @property File stdout() @trusted //TODO: @safe nothrow
  1405. {
  1406. if ((_redirectFlags & Redirect.stdout) == 0)
  1407. throw new Error("Child process' standard output stream hasn't "
  1408. ~"been redirected.");
  1409. return _stdout;
  1410. }
  1411.  
  1412. /**
  1413. An $(XREF stdio,File) that allows reading from the child process'
  1414. standard error stream.
  1415.  
  1416. Throws:
  1417. $(OBJECTREF Error) if the child process' standard error stream hasn't
  1418. been redirected.
  1419. */
  1420. @property File stderr() @trusted //TODO: @safe nothrow
  1421. {
  1422. if ((_redirectFlags & Redirect.stderr) == 0)
  1423. throw new Error("Child process' standard error stream hasn't "
  1424. ~"been redirected.");
  1425. return _stderr;
  1426. }
  1427.  
  1428. private:
  1429. Redirect _redirectFlags;
  1430. Pid _pid;
  1431. File _stdin, _stdout, _stderr;
  1432. }
  1433.  
  1434.  
  1435. /**
  1436. Executes the given program and returns its exit code and output.
  1437.  
  1438. This function blocks until the program terminates.
  1439. The $(D output) string includes what the program writes to its
  1440. standard error stream as well as its standard output stream.
  1441. ---
  1442. auto dmd = execute("dmd", "myapp.d");
  1443. if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
  1444. ---
  1445.  
  1446. POSIX_specific:
  1447. If the process is terminated by a signal, the $(D status) field of
  1448. the return value will contain a negative number whose absolute
  1449. value is the signal number. (See $(LREF wait) for details.)
  1450.  
  1451. Throws:
  1452. $(LREF ProcessException) on failure to start the process.$(BR)
  1453. $(XREF stdio,StdioException) on failure to capture output.
  1454. */
  1455. Tuple!(int, "status", string, "output") execute(string[] args...)
  1456. @trusted //TODO: @safe
  1457. {
  1458. auto p = pipeProcess(args, Redirect.stdout | Redirect.stderrToStdout);
  1459. return processOutput(p, size_t.max);
  1460. }
  1461.  
  1462.  
  1463. /**
  1464. Executes $(D _command) in the user's default _shell and returns its
  1465. exit code and output.
  1466.  
  1467. This function blocks until the command terminates.
  1468. The $(D output) string includes what the command writes to its
  1469. standard error stream as well as its standard output stream.
  1470. The path to the _command interpreter is given by $(LREF userShell).
  1471. ---
  1472. auto ls = shell("ls -l");
  1473. writefln("ls exited with code %s and said: %s", ls.status, ls.output);
  1474. ---
  1475.  
  1476. POSIX_specific:
  1477. If the process is terminated by a signal, the $(D status) field of
  1478. the return value will contain a negative number whose absolute
  1479. value is the signal number. (See $(LREF wait) for details.)
  1480.  
  1481. Throws:
  1482. $(LREF ProcessException) on failure to start the process.$(BR)
  1483. $(XREF stdio,StdioException) on failure to capture output.
  1484. */
  1485. Tuple!(int, "status", string, "output") shell(string command)
  1486. @trusted //TODO: @safe
  1487. {
  1488. auto p = pipeShell(command, Redirect.stdout | Redirect.stderrToStdout);
  1489. return processOutput(p, size_t.max);
  1490. }
  1491.  
  1492.  
  1493. // Collects the output and exit code for execute() and shell().
  1494. private Tuple!(int, "status", string, "output") processOutput(
  1495. ref ProcessPipes pp,
  1496. size_t maxData)
  1497. {
  1498. Appender!(ubyte[]) a;
  1499. enum chunkSize = 4096;
  1500. foreach (ubyte[] chunk; pp.stdout.byChunk(chunkSize))
  1501. {
  1502. a.put(chunk);
  1503. if (a.data().length + chunkSize > maxData) break;
  1504. }
  1505.  
  1506. typeof(return) r;
  1507. r.output = cast(string) a.data;
  1508. r.status = wait(pp.pid);
  1509. return r;
  1510. }
  1511.  
  1512.  
  1513.  
  1514. /// An exception that signals a problem with starting or waiting for a process.
  1515. class ProcessException : Exception
  1516. {
  1517. // Standard constructor.
  1518. this(string msg, string file = __FILE__, size_t line = __LINE__)
  1519. {
  1520. super(msg, file, line);
  1521. }
  1522.  
  1523. // Creates a new ProcessException based on errno.
  1524. static ProcessException newFromErrno(string customMsg = null,
  1525. string file = __FILE__,
  1526. size_t line = __LINE__)
  1527. {
  1528. import core.stdc.errno;
  1529. import std.c.string;
  1530. version (linux)
  1531. {
  1532. char[1024] buf;
  1533. auto errnoMsg = to!string(
  1534. std.c.string.strerror_r(errno, buf.ptr, buf.length));
  1535. }
  1536. else
  1537. {
  1538. auto errnoMsg = to!string(std.c.string.strerror(errno));
  1539. }
  1540. auto msg = customMsg.empty() ? errnoMsg
  1541. : customMsg ~ " (" ~ errnoMsg ~ ')';
  1542. return new ProcessException(msg, file, line);
  1543. }
  1544.  
  1545. // Creates a new ProcessException based on GetLastError() (Windows only).
  1546. version (Windows)
  1547. static ProcessException newFromLastError(string customMsg = null,
  1548. string file = __FILE__,
  1549. size_t line = __LINE__)
  1550. {
  1551. auto lastMsg = sysErrorString(GetLastError());
  1552. auto msg = customMsg.empty() ? lastMsg
  1553. : customMsg ~ " (" ~ lastMsg ~ ')';
  1554. return new ProcessException(msg, file, line);
  1555. }
  1556. }
  1557.  
  1558.  
  1559. /**
  1560. Determines the path to the current user's default command interpreter.
  1561.  
  1562. On Windows, this function returns the contents of the COMSPEC environment
  1563. variable, if it exists. Otherwise, it returns the string $(D "cmd.exe").
  1564.  
  1565. On POSIX, $(D userShell) returns the contents of the SHELL environment
  1566. variable, if it exists and is non-empty. Otherwise, it returns
  1567. $(D "/bin/sh").
  1568. */
  1569. @property string userShell() @safe //TODO: nothrow
  1570. {
  1571. version (Windows) return environment.get("COMSPEC", "cmd.exe");
  1572. else version (Posix) return environment.get("SHELL", "/bin/sh");
  1573. }
  1574.  
  1575.  
  1576. // A command-line switch that indicates to the shell that it should
  1577. // interpret the following argument as a command to be executed.
  1578. version (Posix) private immutable string shellSwitch = "-c";
  1579. version (Windows) private immutable string shellSwitch = "/C";
  1580.  
  1581.  
  1582. /// Returns the process ID number of the current process.
  1583. @property int thisProcessID() @trusted //TODO: @safe nothrow
  1584. {
  1585. version (Windows) return GetCurrentProcessId();
  1586. else version (Posix) return getpid();
  1587. }
  1588.  
  1589.  
  1590. // Unittest support code: TestScript takes a string that contains a
  1591. // shell script for the current platform, and writes it to a temporary
  1592. // file. On Windows the file name gets a .cmd extension, while on
  1593. // POSIX its executable permission bit is set. The file is
  1594. // automatically deleted when the object goes out of scope.
  1595.  
  1596.  
  1597. // =============================================================================
  1598. // Functions for shell command quoting/escaping.
  1599. // =============================================================================
  1600.  
  1601.  
  1602. /*
  1603. Command line arguments exist in three forms:
  1604. 1) string or char* array, as received by main.
  1605. Also used internally on POSIX systems.
  1606. 2) Command line string, as used in Windows'
  1607. CreateProcess and CommandLineToArgvW functions.
  1608. A specific quoting and escaping algorithm is used
  1609. to distinguish individual arguments.
  1610. 3) Shell command string, as written at a shell prompt
  1611. or passed to cmd /C - this one may contain shell
  1612. control characters, e.g. > or | for redirection /
  1613. piping - thus, yet another layer of escaping is
  1614. used to distinguish them from program arguments.
  1615.  
  1616. Except for escapeWindowsArgument, the intermediary
  1617. format (2) is hidden away from the user in this module.
  1618. */
  1619.  
  1620. /**
  1621. Escapes an argv-style argument array to be used with $(LREF spawnShell),
  1622. $(LREF pipeShell) or $(LREF shell).
  1623. ---
  1624. string url = "http://dlang.org/";
  1625. shell(escapeShellCommand("wget", url, "-O", "dlang-index.html"));
  1626. ---
  1627.  
  1628. Concatenate multiple $(D escapeShellCommand) and
  1629. $(LREF escapeShellFileName) results to use shell redirection or
  1630. piping operators.
  1631. ---
  1632. shell(
  1633. escapeShellCommand("curl", "http://dlang.org/download.html") ~
  1634. "|" ~
  1635. escapeShellCommand("grep", "-o", `http://\S*\.zip`) ~
  1636. ">" ~
  1637. escapeShellFileName("D download links.txt"));
  1638. ---
  1639. */
  1640. string escapeShellCommand(in char[][] args...)
  1641. //TODO: @safe pure nothrow
  1642. {
  1643. return escapeShellCommandString(escapeShellArguments(args));
  1644. }
  1645.  
  1646.  
  1647. private string escapeShellCommandString(string command)
  1648. //TODO: @safe pure nothrow
  1649. {
  1650. version (Windows)
  1651. return escapeWindowsShellCommand(command);
  1652. else
  1653. return command;
  1654. }
  1655.  
  1656. string escapeWindowsShellCommand(in char[] command)
  1657. //TODO: @safe pure nothrow (prevented by Appender)
  1658. {
  1659. auto result = appender!string();
  1660. result.reserve(command.length);
  1661.  
  1662. foreach (c; command)
  1663. switch (c)
  1664. {
  1665. case '\0':
  1666. assert(0, "Cannot put NUL in command line");
  1667. case '\r':
  1668. case '\n':
  1669. assert(0, "CR/LF are not escapable");
  1670. case '\x01': .. case '\x09':
  1671. case '\x0B': .. case '\x0C':
  1672. case '\x0E': .. case '\x1F':
  1673. case '"':
  1674. case '^':
  1675. case '&':
  1676. case '<':
  1677. case '>':
  1678. case '|':
  1679. result.put('^');
  1680. goto default;
  1681. default:
  1682. result.put(c);
  1683. }
  1684. return result.data;
  1685. }
  1686.  
  1687. private string escapeShellArguments(in char[][] args...)
  1688. @trusted pure nothrow
  1689. {
  1690. char[] buf;
  1691.  
  1692. @safe nothrow
  1693. char[] allocator(size_t size)
  1694. {
  1695. if (buf.length == 0)
  1696. return buf = new char[size];
  1697. else
  1698. {
  1699. auto p = buf.length;
  1700. buf.length = buf.length + 1 + size;
  1701. buf[p++] = ' ';
  1702. return buf[p..p+size];
  1703. }
  1704. }
  1705.  
  1706. foreach (arg; args)
  1707. escapeShellArgument!allocator(arg);
  1708. return assumeUnique(buf);
  1709. }
  1710.  
  1711. private auto escapeShellArgument(alias allocator)(in char[] arg) @safe nothrow
  1712. {
  1713. // The unittest for this function requires special
  1714. // preparation - see below.
  1715.  
  1716. version (Windows)
  1717. return escapeWindowsArgumentImpl!allocator(arg);
  1718. else
  1719. return escapePosixArgumentImpl!allocator(arg);
  1720. }
  1721.  
  1722. /**
  1723. Quotes a command-line argument in a manner conforming to the behavior of
  1724. $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx,
  1725. CommandLineToArgvW).
  1726. */
  1727. string escapeWindowsArgument(in char[] arg) @trusted pure nothrow
  1728. {
  1729. // Rationale for leaving this function as public:
  1730. // this algorithm of escaping paths is also used in other software,
  1731. // e.g. DMD's response files.
  1732.  
  1733. auto buf = escapeWindowsArgumentImpl!charAllocator(arg);
  1734. return assumeUnique(buf);
  1735. }
  1736.  
  1737.  
  1738. private char[] charAllocator(size_t size) @safe pure nothrow
  1739. {
  1740. return new char[size];
  1741. }
  1742.  
  1743.  
  1744. private char[] escapeWindowsArgumentImpl(alias allocator)(in char[] arg)
  1745. @safe nothrow
  1746. if (is(typeof(allocator(size_t.init)[0] = char.init)))
  1747. {
  1748. // References:
  1749. // * http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
  1750. // * http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
  1751.  
  1752. // Calculate the total string size.
  1753.  
  1754. // Trailing backslashes must be escaped
  1755. bool escaping = true;
  1756. // Result size = input size + 2 for surrounding quotes + 1 for the
  1757. // backslash for each escaped character.
  1758. size_t size = 1 + arg.length + 1;
  1759.  
  1760. foreach_reverse (c; arg)
  1761. {
  1762. if (c == '"')
  1763. {
  1764. escaping = true;
  1765. size++;
  1766. }
  1767. else
  1768. if (c == '\\')
  1769. {
  1770. if (escaping)
  1771. size++;
  1772. }
  1773. else
  1774. escaping = false;
  1775. }
  1776.  
  1777. // Construct result string.
  1778.  
  1779. auto buf = allocator(size);
  1780. size_t p = size;
  1781. buf[--p] = '"';
  1782. escaping = true;
  1783. foreach_reverse (c; arg)
  1784. {
  1785. if (c == '"')
  1786. escaping = true;
  1787. else
  1788. if (c != '\\')
  1789. escaping = false;
  1790.  
  1791. buf[--p] = c;
  1792. if (escaping)
  1793. buf[--p] = '\\';
  1794. }
  1795. buf[--p] = '"';
  1796. assert(p == 0);
  1797.  
  1798. return buf;
  1799. }
  1800.  
  1801.  
  1802. private string escapePosixArgument(in char[] arg) @trusted pure nothrow
  1803. {
  1804. auto buf = escapePosixArgumentImpl!charAllocator(arg);
  1805. return assumeUnique(buf);
  1806. }
  1807.  
  1808. private char[] escapePosixArgumentImpl(alias allocator)(in char[] arg)
  1809. @safe nothrow
  1810. if (is(typeof(allocator(size_t.init)[0] = char.init)))
  1811. {
  1812. // '\'' means: close quoted part of argument, append an escaped
  1813. // single quote, and reopen quotes
  1814.  
  1815. // Below code is equivalent to:
  1816. // return `'` ~ std.array.replace(arg, `'`, `'\''`) ~ `'`;
  1817.  
  1818. size_t size = 1 + arg.length + 1;
  1819. foreach (c; arg)
  1820. if (c == '\'')
  1821. size += 3;
  1822.  
  1823. auto buf = allocator(size);
  1824. size_t p = 0;
  1825. buf[p++] = '\'';
  1826. foreach (c; arg)
  1827. if (c == '\'')
  1828. {
  1829. buf[p..p+4] = `'\''`;
  1830. p += 4;
  1831. }
  1832. else
  1833. buf[p++] = c;
  1834. buf[p++] = '\'';
  1835. assert(p == size);
  1836.  
  1837. return buf;
  1838. }
  1839.  
  1840. /**
  1841. Escapes a filename to be used for shell redirection with $(LREF spawnShell),
  1842. $(LREF pipeShell) or $(LREF shell).
  1843. */
  1844. string escapeShellFileName(in char[] fileName) @trusted pure nothrow
  1845. {
  1846. // The unittest for this function requires special
  1847. // preparation - see below.
  1848.  
  1849. version (Windows)
  1850. return cast(string)('"' ~ fileName ~ '"');
  1851. else
  1852. return escapePosixArgument(fileName);
  1853. }
  1854.  
  1855. // Loop generating strings with random characters
  1856. //version = unittest_burnin;
  1857.  
  1858.  
  1859.  
  1860. // =============================================================================
  1861. // Environment variable manipulation.
  1862. // =============================================================================
  1863.  
  1864.  
  1865. /**
  1866. Manipulates _environment variables using an associative-array-like
  1867. interface.
  1868.  
  1869. This class contains only static methods, and cannot be instantiated.
  1870. See below for examples of use.
  1871. */
  1872. abstract final class environment
  1873. {
  1874. static:
  1875. /**
  1876. Retrieves the value of the environment variable with the given $(D name).
  1877.  
  1878. If no such variable exists, this function throws an $(D Exception).
  1879. See also $(LREF get), which doesn't throw on failure.
  1880. ---
  1881. auto path = environment["PATH"];
  1882. ---
  1883. */
  1884. string opIndex(string name) @safe
  1885. {
  1886. string value;
  1887. enforce(getImpl(name, value), "Environment variable not found: "~name);
  1888. return value;
  1889. }
  1890.  
  1891. /**
  1892. Retrieves the value of the environment variable with the given $(D name),
  1893. or a default value if the variable doesn't exist.
  1894.  
  1895. Unlike $(LREF opIndex), this function never throws.
  1896. ---
  1897. auto sh = environment.get("SHELL", "/bin/sh");
  1898. ---
  1899. This function is also useful in checking for the existence of an
  1900. environment variable.
  1901. ---
  1902. auto myVar = environment.get("MYVAR");
  1903. if (myVar is null)
  1904. {
  1905. // Environment variable doesn't exist.
  1906. // Note that we have to use 'is' for the comparison, since
  1907. // myVar == null is also true if the variable exists but is
  1908. // empty.
  1909. }
  1910. ---
  1911. */
  1912. string get(string name, string defaultValue = null) @safe //TODO: nothrow
  1913. {
  1914. string value;
  1915. auto found = getImpl(name, value);
  1916. return found ? value : defaultValue;
  1917. }
  1918.  
  1919. /**
  1920. Assigns the given $(D value) to the environment variable with the given
  1921. $(D name).
  1922.  
  1923. If the variable does not exist, it will be created. If it already exists,
  1924. it will be overwritten.
  1925. ---
  1926. environment["foo"] = "bar";
  1927. ---
  1928. */
  1929. string opIndexAssign(string value, string name) @trusted
  1930. {
  1931. version (Posix)
  1932. {
  1933. if (core.sys.posix.stdlib.setenv(toStringz(name), toStringz(value), 1) != -1)
  1934. {
  1935. return value;
  1936. }
  1937. // The default errno error message is very uninformative
  1938. // in the most common case, so we handle it manually.
  1939. enforce(errno != EINVAL,
  1940. "Invalid environment variable name: '"~name~"'");
  1941. errnoEnforce(false,
  1942. "Failed to add environment variable");
  1943. assert(0);
  1944. }
  1945. else version (Windows)
  1946. {
  1947. enforce(
  1948. SetEnvironmentVariableW(toUTF16z(name), toUTF16z(value)),
  1949. sysErrorString(GetLastError())
  1950. );
  1951. return value;
  1952. }
  1953. else static assert(0);
  1954. }
  1955.  
  1956. /**
  1957. Removes the environment variable with the given $(D name).
  1958.  
  1959. If the variable isn't in the environment, this function returns
  1960. successfully without doing anything.
  1961. */
  1962. void remove(string name) @trusted // TODO: @safe nothrow
  1963. {
  1964. version (Windows) SetEnvironmentVariableW(toUTF16z(name), null);
  1965. else version (Posix) core.sys.posix.stdlib.unsetenv(toStringz(name));
  1966. else static assert(0);
  1967. }
  1968.  
  1969. /**
  1970. Copies all environment variables into an associative array.
  1971.  
  1972. Windows_specific:
  1973. While Windows environment variable names are case insensitive, D's
  1974. built-in associative arrays are not. This function will store all
  1975. variable names in uppercase (e.g. $(D PATH)).
  1976. */
  1977. string[string] toAA() @trusted
  1978. {
  1979. string[string] aa;
  1980. version (Posix)
  1981. {
  1982. for (int i=0; environ[i] != null; ++i)
  1983. {
  1984. immutable varDef = to!string(environ[i]);
  1985. immutable eq = std.string.indexOf(varDef, '=');
  1986. assert (eq >= 0);
  1987.  
  1988. immutable name = varDef[0 .. eq];
  1989. immutable value = varDef[eq+1 .. $];
  1990.  
  1991. // In POSIX, environment variables may be defined more
  1992. // than once. This is a security issue, which we avoid
  1993. // by checking whether the key already exists in the array.
  1994. // For more info:
  1995. // http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/environment-variables.html
  1996. if (name !in aa) aa[name] = value;
  1997. }
  1998. }
  1999. else version (Windows)
  2000. {
  2001. auto envBlock = GetEnvironmentStringsW();
  2002. enforce(envBlock, "Failed to retrieve environment variables.");
  2003. scope(exit) FreeEnvironmentStringsW(envBlock);
  2004.  
  2005. for (int i=0; envBlock[i] != '\0'; ++i)
  2006. {
  2007. auto start = i;
  2008. while (envBlock[i] != '=') ++i;
  2009. immutable name = toUTF8(toUpper(envBlock[start .. i]));
  2010.  
  2011. start = i+1;
  2012. while (envBlock[i] != '\0') ++i;
  2013. // Just like in POSIX systems, environment variables may be
  2014. // defined more than once in an environment block on Windows,
  2015. // and it is just as much of a security issue there. Moreso,
  2016. // in fact, due to the case insensensitivity of variable names,
  2017. // which is not handled correctly by all programs.
  2018. if (name !in aa) aa[name] = toUTF8(envBlock[start .. i]);
  2019. }
  2020. }
  2021. else static assert(0);
  2022. return aa;
  2023. }
  2024.  
  2025. private:
  2026. // Returns the length of an environment variable (in number of
  2027. // wchars, including the null terminator), or 0 if it doesn't exist.
  2028. version (Windows)
  2029. int varLength(LPCWSTR namez) @trusted nothrow
  2030. {
  2031. return GetEnvironmentVariableW(namez, null, 0);
  2032. }
  2033.  
  2034. // Retrieves the environment variable, returns false on failure.
  2035. bool getImpl(string name, out string value) @trusted //TODO: nothrow
  2036. {
  2037. version (Windows)
  2038. {
  2039. const namez = toUTF16z(name);
  2040. immutable len = varLength(namez);
  2041. if (len == 0) return false;
  2042. if (len == 1)
  2043. {
  2044. value = "";
  2045. return true;
  2046. }
  2047.  
  2048. auto buf = new WCHAR[len];
  2049. GetEnvironmentVariableW(namez, buf.ptr, to!DWORD(buf.length));
  2050. value = toUTF8(buf[0 .. $-1]);
  2051. return true;
  2052. }
  2053. else version (Posix)
  2054. {
  2055. const vz = core.sys.posix.stdlib.getenv(toStringz(name));
  2056. if (vz == null) return false;
  2057. auto v = vz[0 .. strlen(vz)];
  2058.  
  2059. // Cache the last call's result.
  2060. static string lastResult;
  2061. if (v != lastResult) lastResult = v.idup;
  2062. value = lastResult;
  2063. return true;
  2064. }
  2065. else static assert(0);
  2066. }
  2067. }