folly: replace old-style header guards with "pragma once"
[folly.git] / folly / Subprocess.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * Subprocess library, modeled after Python's subprocess module
19  * (http://docs.python.org/2/library/subprocess.html)
20  *
21  * This library defines one class (Subprocess) which represents a child
22  * process.  Subprocess has two constructors: one that takes a vector<string>
23  * and executes the given executable without using the shell, and one
24  * that takes a string and executes the given command using the shell.
25  * Subprocess allows you to redirect the child's standard input, standard
26  * output, and standard error to/from child descriptors in the parent,
27  * or to create communication pipes between the child and the parent.
28  *
29  * The simplest example is a thread-safe [1] version of the system() library
30  * function:
31  *    Subprocess(cmd).wait();
32  * which executes the command using the default shell and waits for it
33  * to complete, returning the exit status.
34  *
35  * A thread-safe [1] version of popen() (type="r", to read from the child):
36  *    Subprocess proc(cmd, Subprocess::pipeStdout());
37  *    // read from proc.stdout()
38  *    proc.wait();
39  *
40  * A thread-safe [1] version of popen() (type="w", to write to the child):
41  *    Subprocess proc(cmd, Subprocess::pipeStdin());
42  *    // write to proc.stdin()
43  *    proc.wait();
44  *
45  * If you want to redirect both stdin and stdout to pipes, you can, but note
46  * that you're subject to a variety of deadlocks.  You'll want to use
47  * nonblocking I/O, like the callback version of communicate().
48  *
49  * The string or IOBuf-based variants of communicate() are the simplest way
50  * to communicate with a child via its standard input, standard output, and
51  * standard error.  They buffer everything in memory, so they are not great
52  * for large amounts of data (or long-running processes), but they are much
53  * simpler than the callback version.
54  *
55  * == A note on thread-safety ==
56  *
57  * [1] "thread-safe" refers ONLY to the fact that Subprocess is very careful
58  * to fork in a way that does not cause grief in multithreaded programs.
59  *
60  * Caveat: If your system does not have the atomic pipe2 system call, it is
61  * not safe to concurrently call Subprocess from different threads.
62  * Therefore, it is best to have a single thread be responsible for spawning
63  * subprocesses.
64  *
65  * A particular instances of Subprocess is emphatically **not** thread-safe.
66  * If you need to simultaneously communicate via the pipes, and interact
67  * with the Subprocess state, your best bet is to:
68  *  - takeOwnershipOfPipes() to separate the pipe I/O from the subprocess.
69  *  - Only interact with the Subprocess from one thread at a time.
70  *
71  * The current implementation of communicate() cannot be safely interrupted.
72  * To do so correctly, one would need to use EventFD, or open a dedicated
73  * pipe to be messaged from a different thread -- in particular, kill() will
74  * not do, since a descendant may keep the pipes open indefinitely.
75  *
76  * So, once you call communicate(), you must wait for it to return, and not
77  * touch the pipes from other threads.  closeParentFd() is emphatically
78  * unsafe to call concurrently, and even sendSignal() is not a good idea.
79  * You can perhaps give the Subprocess's PID to a different thread before
80  * starting communicate(), and use that PID to send a signal without
81  * accessing the Subprocess object.  In that case, you will need a mutex
82  * that ensures you don't wait() before you sent said signal.  In a
83  * nutshell, don't do this.
84  *
85  * In fact, signals are inherently concurrency-unsafe on Unix: if you signal
86  * a PID, while another thread is in waitpid(), the signal may fire either
87  * before or after the process is reaped.  This means that your signal can,
88  * in pathological circumstances, be delivered to the wrong process (ouch!).
89  * To avoid this, you should only use non-blocking waits (i.e. poll()), and
90  * make sure to serialize your signals (i.e. kill()) with the waits --
91  * either wait & signal from the same thread, or use a mutex.
92  */
93
94 #pragma once
95
96 #include <sys/types.h>
97 #include <signal.h>
98 #if __APPLE__
99 #include <sys/wait.h>
100 #else
101 #include <wait.h>
102 #endif
103
104 #include <exception>
105 #include <vector>
106 #include <string>
107
108 #include <boost/container/flat_map.hpp>
109 #include <boost/operators.hpp>
110
111 #include <folly/File.h>
112 #include <folly/FileUtil.h>
113 #include <folly/gen/String.h>
114 #include <folly/io/IOBufQueue.h>
115 #include <folly/MapUtil.h>
116 #include <folly/Portability.h>
117 #include <folly/Range.h>
118
119 namespace folly {
120
121 /**
122  * Class to wrap a process return code.
123  */
124 class Subprocess;
125 class ProcessReturnCode {
126   friend class Subprocess;
127  public:
128   enum State {
129     // Subprocess starts in the constructor, so this state designates only
130     // default-initialized or moved-out ProcessReturnCodes.
131     NOT_STARTED,
132     RUNNING,
133     EXITED,
134     KILLED
135   };
136
137   // Default-initialized for convenience. Subprocess::returnCode() will
138   // never produce this value.
139   ProcessReturnCode() : ProcessReturnCode(RV_NOT_STARTED) {}
140
141   // Trivially copyable
142   ProcessReturnCode(const ProcessReturnCode& p) = default;
143   ProcessReturnCode& operator=(const ProcessReturnCode& p) = default;
144   // Non-default move: In order for Subprocess to be movable, the "moved
145   // out" state must not be "running", or ~Subprocess() will abort.
146   ProcessReturnCode(ProcessReturnCode&& p) noexcept;
147   ProcessReturnCode& operator=(ProcessReturnCode&& p) noexcept;
148
149   /**
150    * Process state.  One of:
151    * NOT_STARTED: process hasn't been started successfully
152    * RUNNING: process is currently running
153    * EXITED: process exited (successfully or not)
154    * KILLED: process was killed by a signal.
155    */
156   State state() const;
157
158   /**
159    * Helper wrappers around state().
160    */
161   bool notStarted() const { return state() == NOT_STARTED; }
162   bool running() const { return state() == RUNNING; }
163   bool exited() const { return state() == EXITED; }
164   bool killed() const { return state() == KILLED; }
165
166   /**
167    * Exit status.  Only valid if state() == EXITED; throws otherwise.
168    */
169   int exitStatus() const;
170
171   /**
172    * Signal that caused the process's termination.  Only valid if
173    * state() == KILLED; throws otherwise.
174    */
175   int killSignal() const;
176
177   /**
178    * Was a core file generated?  Only valid if state() == KILLED; throws
179    * otherwise.
180    */
181   bool coreDumped() const;
182
183   /**
184    * String representation; one of
185    * "not started"
186    * "running"
187    * "exited with status <status>"
188    * "killed by signal <signal>"
189    * "killed by signal <signal> (core dumped)"
190    */
191   std::string str() const;
192
193   /**
194    * Helper function to enforce a precondition based on this.
195    * Throws std::logic_error if in an unexpected state.
196    */
197   void enforce(State state) const;
198  private:
199   explicit ProcessReturnCode(int rv) : rawStatus_(rv) { }
200   static constexpr int RV_NOT_STARTED = -2;
201   static constexpr int RV_RUNNING = -1;
202
203   int rawStatus_;
204 };
205
206 /**
207  * Base exception thrown by the Subprocess methods.
208  */
209 class SubprocessError : public std::exception {};
210
211 /**
212  * Exception thrown by *Checked methods of Subprocess.
213  */
214 class CalledProcessError : public SubprocessError {
215  public:
216   explicit CalledProcessError(ProcessReturnCode rc);
217   ~CalledProcessError() throw() = default;
218   const char* what() const throw() override { return what_.c_str(); }
219   ProcessReturnCode returnCode() const { return returnCode_; }
220  private:
221   ProcessReturnCode returnCode_;
222   std::string what_;
223 };
224
225 /**
226  * Exception thrown if the subprocess cannot be started.
227  */
228 class SubprocessSpawnError : public SubprocessError {
229  public:
230   SubprocessSpawnError(const char* executable, int errCode, int errnoValue);
231   ~SubprocessSpawnError() throw() = default;
232   const char* what() const throw() override { return what_.c_str(); }
233   int errnoValue() const { return errnoValue_; }
234
235  private:
236   int errnoValue_;
237   std::string what_;
238 };
239
240 /**
241  * Subprocess.
242  */
243 class Subprocess {
244  public:
245   static const int CLOSE = -1;
246   static const int PIPE = -2;
247   static const int PIPE_IN = -3;
248   static const int PIPE_OUT = -4;
249
250   /**
251    * See Subprocess::Options::dangerousPostForkPreExecCallback() for usage.
252    * Every derived class should include the following warning:
253    *
254    * DANGER: This class runs after fork in a child processes. Be fast, the
255    * parent thread is waiting, but remember that other parent threads are
256    * running and may mutate your state.  Avoid mutating any data belonging to
257    * the parent.  Avoid interacting with non-POD data that originated in the
258    * parent.  Avoid any libraries that may internally reference non-POD data.
259    * Especially beware parent mutexes -- for example, glog's LOG() uses one.
260    */
261   struct DangerousPostForkPreExecCallback {
262     virtual ~DangerousPostForkPreExecCallback() {}
263     // This must return 0 on success, or an `errno` error code.
264     virtual int operator()() = 0;
265   };
266
267   /**
268    * Class representing various options: file descriptor behavior, and
269    * whether to use $PATH for searching for the executable,
270    *
271    * By default, we don't use $PATH, file descriptors are closed if
272    * the close-on-exec flag is set (fcntl FD_CLOEXEC) and inherited
273    * otherwise.
274    */
275   class Options : private boost::orable<Options> {
276     friend class Subprocess;
277    public:
278     Options() {}  // E.g. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58328
279
280     /**
281      * Change action for file descriptor fd.
282      *
283      * "action" may be another file descriptor number (dup2()ed before the
284      * child execs), or one of CLOSE, PIPE_IN, and PIPE_OUT.
285      *
286      * CLOSE: close the file descriptor in the child
287      * PIPE_IN: open a pipe *from* the child
288      * PIPE_OUT: open a pipe *to* the child
289      *
290      * PIPE is a shortcut; same as PIPE_IN for stdin (fd 0), same as
291      * PIPE_OUT for stdout (fd 1) or stderr (fd 2), and an error for
292      * other file descriptors.
293      */
294     Options& fd(int fd, int action);
295
296     /**
297      * Shortcut to change the action for standard input.
298      */
299     Options& stdin(int action) { return fd(STDIN_FILENO, action); }
300
301     /**
302      * Shortcut to change the action for standard output.
303      */
304     Options& stdout(int action) { return fd(STDOUT_FILENO, action); }
305
306     /**
307      * Shortcut to change the action for standard error.
308      * Note that stderr(1) will redirect the standard error to the same
309      * file descriptor as standard output; the equivalent of bash's "2>&1"
310      */
311     Options& stderr(int action) { return fd(STDERR_FILENO, action); }
312
313     Options& pipeStdin() { return fd(STDIN_FILENO, PIPE_IN); }
314     Options& pipeStdout() { return fd(STDOUT_FILENO, PIPE_OUT); }
315     Options& pipeStderr() { return fd(STDERR_FILENO, PIPE_OUT); }
316
317     /**
318      * Close all other fds (other than standard input, output, error,
319      * and file descriptors explicitly specified with fd()).
320      *
321      * This is potentially slow; it's generally a better idea to
322      * set the close-on-exec flag on all file descriptors that shouldn't
323      * be inherited by the child.
324      *
325      * Even with this option set, standard input, output, and error are
326      * not closed; use stdin(CLOSE), stdout(CLOSE), stderr(CLOSE) if you
327      * desire this.
328      */
329     Options& closeOtherFds() { closeOtherFds_ = true; return *this; }
330
331     /**
332      * Use the search path ($PATH) when searching for the executable.
333      */
334     Options& usePath() { usePath_ = true; return *this; }
335
336     /**
337      * Change the child's working directory, after the vfork.
338      */
339     Options& chdir(const std::string& dir) { childDir_ = dir; return *this; }
340
341 #if __linux__
342     /**
343      * Child will receive a signal when the parent exits.
344      */
345     Options& parentDeathSignal(int sig) {
346       parentDeathSignal_ = sig;
347       return *this;
348     }
349 #endif
350
351     /**
352      * Child will be made a process group leader when it starts. Upside: one
353      * can reliably all its kill non-daemonizing descendants.  Downside: the
354      * child will not receive Ctrl-C etc during interactive use.
355      */
356     Options& processGroupLeader() {
357       processGroupLeader_ = true;
358       return *this;
359     }
360
361     /**
362      * *** READ THIS WHOLE DOCBLOCK BEFORE USING ***
363      *
364      * Run this callback in the child after the fork, just before the
365      * exec(), and after the child's state has been completely set up:
366      *  - signal handlers have been reset to default handling and unblocked
367      *  - the working directory was set
368      *  - closed any file descriptors specified via Options()
369      *  - set child process flags (see code)
370      *
371      * This is EXTREMELY DANGEROUS. For example, this innocuous-looking code
372      * can cause a fraction of your Subprocess launches to hang forever:
373      *
374      *   LOG(INFO) << "Hello from the child";
375      *
376      * The reason is that glog has an internal mutex. If your fork() happens
377      * when the parent has the mutex locked, the child will wait forever.
378      *
379      * == GUIDELINES ==
380      *
381      * - Be quick -- the parent thread is blocked until you exit.
382      * - Remember that other parent threads are running, and may mutate your
383      *   state.
384      * - Avoid mutating any data belonging to the parent.
385      * - Avoid interacting with non-POD data that came from the parent.
386      * - Avoid any libraries that may internally reference non-POD state.
387      * - Especially beware parent mutexes, e.g. LOG() uses a global mutex.
388      * - Avoid invoking the parent's destructors (you can accidentally
389      *   delete files, terminate network connections, etc).
390      * - Read http://ewontfix.com/7/
391      */
392     Options& dangerousPostForkPreExecCallback(
393         DangerousPostForkPreExecCallback* cob) {
394       dangerousPostForkPreExecCallback_ = cob;
395       return *this;
396     }
397
398     /**
399      * Helpful way to combine Options.
400      */
401     Options& operator|=(const Options& other);
402
403    private:
404     typedef boost::container::flat_map<int, int> FdMap;
405     FdMap fdActions_;
406     bool closeOtherFds_{false};
407     bool usePath_{false};
408     std::string childDir_;  // "" keeps the parent's working directory
409 #if __linux__
410     int parentDeathSignal_{0};
411 #endif
412     bool processGroupLeader_{false};
413     DangerousPostForkPreExecCallback*
414       dangerousPostForkPreExecCallback_{nullptr};
415   };
416
417   static Options pipeStdin() { return Options().stdin(PIPE); }
418   static Options pipeStdout() { return Options().stdout(PIPE); }
419   static Options pipeStderr() { return Options().stderr(PIPE); }
420
421   // Non-copiable, but movable
422   Subprocess(const Subprocess&) = delete;
423   Subprocess& operator=(const Subprocess&) = delete;
424   Subprocess(Subprocess&&) = default;
425   Subprocess& operator=(Subprocess&&) = default;
426
427   /**
428    * Create a subprocess from the given arguments.  argv[0] must be listed.
429    * If not-null, executable must be the actual executable
430    * being used (otherwise it's the same as argv[0]).
431    *
432    * If env is not-null, it must contain name=value strings to be used
433    * as the child's environment; otherwise, we inherit the environment
434    * from the parent.  env must be null if options.usePath is set.
435    */
436   explicit Subprocess(
437       const std::vector<std::string>& argv,
438       const Options& options = Options(),
439       const char* executable = nullptr,
440       const std::vector<std::string>* env = nullptr);
441   ~Subprocess();
442
443   /**
444    * Create a subprocess run as a shell command (as shell -c 'command')
445    *
446    * The shell to use is taken from the environment variable $SHELL,
447    * or /bin/sh if $SHELL is unset.
448    */
449   explicit Subprocess(
450       const std::string& cmd,
451       const Options& options = Options(),
452       const std::vector<std::string>* env = nullptr);
453
454   ////
455   //// The methods below only manipulate the process state, and do not
456   //// affect its communication pipes.
457   ////
458
459   /**
460    * Return the child's pid, or -1 if the child wasn't successfully spawned
461    * or has already been wait()ed upon.
462    */
463   pid_t pid() const;
464
465   /**
466    * Return the child's status (as per wait()) if the process has already
467    * been waited on, -1 if the process is still running, or -2 if the
468    * process hasn't been successfully started.  NOTE that this does not call
469    * waitpid() or Subprocess::poll(), but simply returns the status stored
470    * in the Subprocess object.
471    */
472   ProcessReturnCode returnCode() const { return returnCode_; }
473
474   /**
475    * Poll the child's status and return it. Return the exit status if the
476    * subprocess had quit, or RUNNING otherwise.  Throws an std::logic_error
477    * if called on a Subprocess whose status is no longer RUNNING.  No other
478    * exceptions are possible.  Aborts on egregious violations of contract,
479    * e.g. if you wait for the underlying process without going through this
480    * Subprocess instance.
481    */
482   ProcessReturnCode poll();
483
484   /**
485    * Poll the child's status.  If the process is still running, return false.
486    * Otherwise, return true if the process exited with status 0 (success),
487    * or throw CalledProcessError if the process exited with a non-zero status.
488    */
489   bool pollChecked();
490
491   /**
492    * Wait for the process to terminate and return its status.  Like poll(),
493    * the only exception this can throw is std::logic_error if you call this
494    * on a Subprocess whose status is RUNNING.  Aborts on egregious
495    * violations of contract, like an out-of-band waitpid(p.pid(), 0, 0).
496    */
497   ProcessReturnCode wait();
498
499   /**
500    * Wait for the process to terminate, throw if unsuccessful.
501    */
502   void waitChecked();
503
504   /**
505    * Send a signal to the child.  Shortcuts for the commonly used Unix
506    * signals are below.
507    */
508   void sendSignal(int signal);
509   void terminate() { sendSignal(SIGTERM); }
510   void kill() { sendSignal(SIGKILL); }
511
512   ////
513   //// The methods below only affect the process's communication pipes, but
514   //// not its return code or state (they do not poll() or wait()).
515   ////
516
517   /**
518    * Communicate with the child until all pipes to/from the child are closed.
519    *
520    * The input buffer is written to the process' stdin pipe, and data is read
521    * from the stdout and stderr pipes.  Non-blocking I/O is performed on all
522    * pipes simultaneously to avoid deadlocks.
523    *
524    * The stdin pipe will be closed after the full input buffer has been written.
525    * An error will be thrown if a non-empty input buffer is supplied but stdin
526    * was not configured as a pipe.
527    *
528    * Returns a pair of buffers containing the data read from stdout and stderr.
529    * If stdout or stderr is not a pipe, an empty IOBuf queue will be returned
530    * for the respective buffer.
531    *
532    * Note that communicate() and communicateIOBuf() both return when all
533    * pipes to/from the child are closed; the child might stay alive after
534    * that, so you must still wait().
535    *
536    * communicateIOBuf() uses IOBufQueue for buffering (which has the
537    * advantage that it won't try to allocate all data at once), but it does
538    * store the subprocess's entire output in memory before returning.
539    *
540    * communicate() uses strings for simplicity.
541    */
542   std::pair<IOBufQueue, IOBufQueue> communicateIOBuf(
543       IOBufQueue input = IOBufQueue());
544
545   std::pair<std::string, std::string> communicate(
546       StringPiece input = StringPiece());
547
548   /**
549    * Communicate with the child until all pipes to/from the child are closed.
550    *
551    * == Semantics ==
552    *
553    * readCallback(pfd, cfd) will be called whenever there's data available
554    * on any pipe *from* the child (PIPE_OUT).  pfd is the file descriptor
555    * in the parent (that you use to read from); cfd is the file descriptor
556    * in the child (used for identifying the stream; 1 = child's standard
557    * output, 2 = child's standard error, etc)
558    *
559    * writeCallback(pfd, cfd) will be called whenever a pipe *to* the child is
560    * writable (PIPE_IN).  pfd is the file descriptor in the parent (that you
561    * use to write to); cfd is the file descriptor in the child (used for
562    * identifying the stream; 0 = child's standard input, etc)
563    *
564    * The read and write callbacks must read from / write to pfd and return
565    * false during normal operation.  Return true to tell communicate() to
566    * close the pipe.  For readCallback, this might send SIGPIPE to the
567    * child, or make its writes fail with EPIPE, so you should generally
568    * avoid returning true unless you've reached end-of-file.
569    *
570    * communicate() returns when all pipes to/from the child are closed; the
571    * child might stay alive after that, so you must still wait().
572    * Conversely, the child may quit long before its pipes are closed, since
573    * its descendants can keep them alive forever.
574    *
575    * Most users won't need to use this callback version; the simpler version
576    * of communicate (which buffers data in memory) will probably work fine.
577    *
578    * == Things you must get correct ==
579    *
580    * 1) You MUST consume all data passed to readCallback (or return true to
581    * close the pipe).  Similarly, you MUST write to a writable pipe (or
582    * return true to close the pipe).  To do otherwise is an error that can
583    * result in a deadlock.  You must do this even for pipes you are not
584    * interested in.
585    *
586    * 2) pfd is nonblocking, so be prepared for read() / write() to return -1
587    * and set errno to EAGAIN (in which case you should return false).  Use
588    * readNoInt() from FileUtil.h to handle interrupted reads for you.
589    *
590    * 3) Your callbacks MUST NOT call any of the Subprocess methods that
591    * manipulate the pipe FDs.  Check the docblocks, but, for example,
592    * neither closeParentFd (return true instead) nor takeOwnershipOfPipes
593    * are safe.  Stick to reading/writing from pfd, as appropriate.
594    *
595    * == Good to know ==
596    *
597    * 1) See ReadLinesCallback for an easy way to consume the child's output
598    * streams line-by-line (or tokenized by another delimiter).
599    *
600    * 2) "Wait until the descendants close the pipes" is usually the behavior
601    * you want, since the descendants may have something to say even if the
602    * immediate child is dead.  If you need to be able to force-close all
603    * parent FDs, communicate() will NOT work for you.  Do it your own way by
604    * using takeOwnershipOfPipes().
605    *
606    * Why not? You can return "true" from your callbacks to sever active
607    * pipes, but inactive ones can remain open indefinitely.  It is
608    * impossible to safely close inactive pipes while another thread is
609    * blocked in communicate().  This is BY DESIGN.  Racing communicate()'s
610    * read/write callbacks can result in wrong I/O and data corruption.  This
611    * class would need internal synchronization and timeouts, a poor and
612    * expensive implementation choice, in order to make closeParentFd()
613    * thread-safe.
614    */
615   typedef std::function<bool(int, int)> FdCallback;
616   void communicate(FdCallback readCallback, FdCallback writeCallback);
617
618   /**
619    * A readCallback for Subprocess::communicate() that helps you consume
620    * lines (or other delimited pieces) from your subprocess's file
621    * descriptors.  Use the readLinesCallback() helper to get template
622    * deduction.  For example:
623    *
624    *   auto read_cb = Subprocess::readLinesCallback(
625    *     [](int fd, folly::StringPiece s) {
626    *       std::cout << fd << " said: " << s;
627    *       return false;  // Keep reading from the child
628    *     }
629    *   );
630    *   subprocess.communicate(
631    *     // ReadLinesCallback contains StreamSplitter contains IOBuf, making
632    *     // it noncopyable, whereas std::function must be copyable.  So, we
633    *     // keep the callback in a local, and instead pass a reference.
634    *     std::ref(read_cb),
635    *     [](int pdf, int cfd){ return true; }  // Don't write to the child
636    *   );
637    *
638    * If a file line exceeds maxLineLength, your callback will get some
639    * initial chunks of maxLineLength with no trailing delimiters.  The final
640    * chunk of a line is delimiter-terminated iff the delimiter was present
641    * in the input.  In particular, the last line in a file always lacks a
642    * delimiter -- so if a file ends on a delimiter, the final line is empty.
643    *
644    * Like a regular communicate() callback, your fdLineCb() normally returns
645    * false.  It may return true to tell Subprocess to close the underlying
646    * file descriptor.  The child process may then receive SIGPIPE or get
647    * EPIPE errors on writes.
648    */
649   template <class Callback>
650   class ReadLinesCallback {
651    private:
652     // Binds an FD to the client-provided FD+line callback
653     struct StreamSplitterCallback {
654       StreamSplitterCallback(Callback& cb, int fd) : cb_(cb), fd_(fd) { }
655       // The return value semantics are inverted vs StreamSplitter
656       bool operator()(StringPiece s) { return !cb_(fd_, s); }
657       Callback& cb_;
658       int fd_;
659     };
660     typedef gen::StreamSplitter<StreamSplitterCallback> LineSplitter;
661    public:
662     explicit ReadLinesCallback(
663       Callback&& fdLineCb,
664       uint64_t maxLineLength = 0,  // No line length limit by default
665       char delimiter = '\n',
666       uint64_t bufSize = 1024
667     ) : fdLineCb_(std::move(fdLineCb)),
668         maxLineLength_(maxLineLength),
669         delimiter_(delimiter),
670         bufSize_(bufSize) {}
671
672     bool operator()(int pfd, int cfd) {
673       // Make a splitter for this cfd if it doesn't already exist
674       auto it = fdToSplitter_.find(cfd);
675       auto& splitter = (it != fdToSplitter_.end()) ? it->second
676         : fdToSplitter_.emplace(cfd, LineSplitter(
677             delimiter_, StreamSplitterCallback(fdLineCb_, cfd), maxLineLength_
678           )).first->second;
679       // Read as much as we can from this FD
680       char buf[bufSize_];
681       while (true) {
682         ssize_t ret = readNoInt(pfd, buf, bufSize_);
683         if (ret == -1 && errno == EAGAIN) {  // No more data for now
684           return false;
685         }
686         if (ret == 0) {  // Reached end-of-file
687           splitter.flush();  // Ignore return since the file is over anyway
688           return true;
689         }
690         if (!splitter(StringPiece(buf, ret))) {
691           return true;  // The callback told us to stop
692         }
693       }
694     }
695
696    private:
697     Callback fdLineCb_;
698     const uint64_t maxLineLength_;
699     const char delimiter_;
700     const uint64_t bufSize_;
701     // We lazily make splitters for all cfds that get used.
702     std::unordered_map<int, LineSplitter> fdToSplitter_;
703   };
704
705   // Helper to enable template deduction
706   template <class Callback>
707   static ReadLinesCallback<Callback> readLinesCallback(
708       Callback&& fdLineCb,
709       uint64_t maxLineLength = 0,  // No line length limit by default
710       char delimiter = '\n',
711       uint64_t bufSize = 1024) {
712     return ReadLinesCallback<Callback>(
713       std::move(fdLineCb), maxLineLength, delimiter, bufSize
714     );
715   }
716
717   /**
718    * communicate() callbacks can use this to temporarily enable/disable
719    * notifications (callbacks) for a pipe to/from the child.  By default,
720    * all are enabled.  Useful for "chatty" communication -- you want to
721    * disable write callbacks until you receive the expected message.
722    *
723    * Disabling a pipe does not free you from the requirement to consume all
724    * incoming data.  Failing to do so will easily create deadlock bugs.
725    *
726    * Throws if the childFd is not known.
727    */
728   void enableNotifications(int childFd, bool enabled);
729
730   /**
731    * Are notifications for one pipe to/from child enabled?  Throws if the
732    * childFd is not known.
733    */
734   bool notificationsEnabled(int childFd) const;
735
736   ////
737   //// The following methods are meant for the cases when communicate() is
738   //// not suitable.  You should not need them when you call communicate(),
739   //// and, in fact, it is INHERENTLY UNSAFE to use closeParentFd() or
740   //// takeOwnershipOfPipes() from a communicate() callback.
741   ////
742
743   /**
744    * Close the parent file descriptor given a file descriptor in the child.
745    * DO NOT USE from communicate() callbacks; make them return true instead.
746    */
747   void closeParentFd(int childFd);
748
749   /**
750    * Set all pipes from / to child to be non-blocking.  communicate() does
751    * this for you.
752    */
753   void setAllNonBlocking();
754
755   /**
756    * Get parent file descriptor corresponding to the given file descriptor
757    * in the child.  Throws if childFd isn't a pipe (PIPE_IN / PIPE_OUT).
758    * Do not close() the returned file descriptor; use closeParentFd, above.
759    */
760   int parentFd(int childFd) const {
761     return pipes_[findByChildFd(childFd)].pipe.fd();
762   }
763   int stdin() const { return parentFd(0); }
764   int stdout() const { return parentFd(1); }
765   int stderr() const { return parentFd(2); }
766
767   /**
768    * The child's pipes are logically separate from the process metadata
769    * (they may even be kept alive by the child's descendants).  This call
770    * lets you manage the pipes' lifetime separetely from the lifetime of the
771    * child process.
772    *
773    * After this call, the Subprocess instance will have no knowledge of
774    * these pipes, and the caller assumes responsibility for managing their
775    * lifetimes.  Pro-tip: prefer to explicitly close() the pipes, since
776    * folly::File would otherwise silently suppress I/O errors.
777    *
778    * No, you may NOT call this from a communicate() callback.
779    */
780   struct ChildPipe {
781     ChildPipe(int fd, folly::File&& ppe) : childFd(fd), pipe(std::move(ppe)) {}
782     int childFd;
783     folly::File pipe;  // Owns the parent FD
784   };
785   std::vector<ChildPipe> takeOwnershipOfPipes();
786
787  private:
788   static const int RV_RUNNING = ProcessReturnCode::RV_RUNNING;
789   static const int RV_NOT_STARTED = ProcessReturnCode::RV_NOT_STARTED;
790
791   // spawn() sets up a pipe to read errors from the child,
792   // then calls spawnInternal() to do the bulk of the work.  Once
793   // spawnInternal() returns it reads the error pipe to see if the child
794   // encountered any errors.
795   void spawn(
796       std::unique_ptr<const char*[]> argv,
797       const char* executable,
798       const Options& options,
799       const std::vector<std::string>* env);
800   void spawnInternal(
801       std::unique_ptr<const char*[]> argv,
802       const char* executable,
803       Options& options,
804       const std::vector<std::string>* env,
805       int errFd);
806
807   // Actions to run in child.
808   // Note that this runs after vfork(), so tread lightly.
809   // Returns 0 on success, or an errno value on failure.
810   int prepareChild(const Options& options,
811                    const sigset_t* sigmask,
812                    const char* childDir) const;
813   int runChild(const char* executable, char** argv, char** env,
814                const Options& options) const;
815
816   /**
817    * Read from the error pipe, and throw SubprocessSpawnError if the child
818    * failed before calling exec().
819    */
820   void readChildErrorPipe(int pfd, const char* executable);
821
822   // Returns an index into pipes_. Throws std::invalid_argument if not found.
823   size_t findByChildFd(const int childFd) const;
824
825
826   pid_t pid_;
827   ProcessReturnCode returnCode_;
828
829   /**
830    * Represents a pipe between this process, and the child process (or its
831    * descendant).  To interact with these pipes, you can use communicate(),
832    * or use parentFd() and related methods, or separate them from the
833    * Subprocess instance entirely via takeOwnershipOfPipes().
834    */
835   struct Pipe : private boost::totally_ordered<Pipe> {
836     folly::File pipe; // Our end of the pipe, wrapped in a File to auto-close.
837     int childFd = -1; // Identifies the pipe: what FD is this in the child?
838     int direction = PIPE_IN; // one of PIPE_IN / PIPE_OUT
839     bool enabled = true; // Are notifications enabled in communicate()?
840
841     bool operator<(const Pipe& other) const {
842       return childFd < other.childFd;
843     }
844     bool operator==(const Pipe& other) const {
845       return childFd == other.childFd;
846     }
847   };
848
849   // Populated at process start according to fdActions, empty after
850   // takeOwnershipOfPipes().  Sorted by childFd.  Can only have elements
851   // erased, but not inserted, after being populated.
852   //
853   // The number of pipes between parent and child is assumed to be small,
854   // so we're happy with a vector here, even if it means linear erase.
855   std::vector<Pipe> pipes_;
856 };
857
858 inline Subprocess::Options& Subprocess::Options::operator|=(
859     const Subprocess::Options& other) {
860   if (this == &other) return *this;
861   // Replace
862   for (auto& p : other.fdActions_) {
863     fdActions_[p.first] = p.second;
864   }
865   closeOtherFds_ |= other.closeOtherFds_;
866   usePath_ |= other.usePath_;
867   processGroupLeader_ |= other.processGroupLeader_;
868   return *this;
869 }
870
871 }  // namespace folly