aboutsummaryrefslogtreecommitdiff
path: root/src/util/subprocess.h
blob: e76ced687cec8ecf52a999b1b6db99a1f01df9d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
// Based on the https://github.com/arun11299/cpp-subprocess project.

/*!

Documentation for C++ subprocessing library.

@copyright The code is licensed under the [MIT
  License](http://opensource.org/licenses/MIT):
  <br>
  Copyright &copy; 2016-2018 Arun Muralidharan.
  <br>
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  <br>
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  <br>
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.

@author [Arun Muralidharan]
@see https://github.com/arun11299/cpp-subprocess to download the source code

@version 1.0.0
*/

#ifndef BITCOIN_UTIL_SUBPROCESS_H
#define BITCOIN_UTIL_SUBPROCESS_H

#include <util/syserror.h>

#include <algorithm>
#include <cassert>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <future>
#include <initializer_list>
#include <iostream>
#include <locale>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

#if (defined _MSC_VER) || (defined __MINGW32__)
  #define __USING_WINDOWS__
#endif

#ifdef __USING_WINDOWS__
  #include <codecvt>
#endif

extern "C" {
#ifdef __USING_WINDOWS__
  #include <Windows.h>
  #include <io.h>
  #include <cwchar>

  #define close _close
  #define open _open
  #define fileno _fileno
#else
  #include <sys/wait.h>
  #include <unistd.h>
#endif
  #include <csignal>
  #include <fcntl.h>
  #include <sys/types.h>
}

/*!
 * Getting started with reading this source code.
 * The source is mainly divided into four parts:
 * 1. Exception Classes:
 *    These are very basic exception classes derived from
 *    runtime_error exception.
 *    There are two types of exception thrown from subprocess
 *    library: OSError and CalledProcessError
 *
 * 2. Popen Class
 *    This is the main class the users will deal with. It
 *    provides with all the API's to deal with processes.
 *
 * 3. Util namespace
 *    It includes some helper functions to split/join a string,
 *    reading from file descriptors, waiting on a process, fcntl
 *    options on file descriptors etc.
 *
 * 4. Detail namespace
 *    This includes some metaprogramming and helper classes.
 */


namespace subprocess {

// Max buffer size allocated on stack for read error
// from pipe
static const size_t SP_MAX_ERR_BUF_SIZ = 1024;

// Default buffer capacity for OutBuffer and ErrBuffer.
// If the data exceeds this capacity, the buffer size is grown
// by 1.5 times its previous capacity
static const size_t DEFAULT_BUF_CAP_BYTES = 8192;


/*-----------------------------------------------
 *    EXCEPTION CLASSES
 *-----------------------------------------------
 */

/*!
 * class: CalledProcessError
 * Thrown when there was error executing the command.
 * Check Popen class API's to know when this exception
 * can be thrown.
 *
 */
class CalledProcessError: public std::runtime_error
{
public:
  int retcode;
  CalledProcessError(const std::string& error_msg, int retcode):
    std::runtime_error(error_msg), retcode(retcode)
  {}
};


/*!
 * class: OSError
 * Thrown when some system call fails to execute or give result.
 * The exception message contains the name of the failed system call
 * with the stringisized errno code.
 * Check Popen class API's to know when this exception would be
 * thrown.
 * Its usual that the API exception specification would have
 * this exception together with CalledProcessError.
 */
class OSError: public std::runtime_error
{
public:
  OSError(const std::string& err_msg, int err_code):
    std::runtime_error(err_msg + ": " + SysErrorString(err_code))
  {}
};

//--------------------------------------------------------------------
namespace util
{
  inline void quote_argument(const std::wstring &argument, std::wstring &command_line,
                      bool force)
  {
    //
    // Unless we're told otherwise, don't quote unless we actually
    // need to do so --- hopefully avoid problems if programs won't
    // parse quotes properly
    //

    if (force == false && argument.empty() == false &&
        argument.find_first_of(L" \t\n\v\"") == argument.npos) {
      command_line.append(argument);
    }
    else {
      command_line.push_back(L'"');

      for (auto it = argument.begin();; ++it) {
        unsigned number_backslashes = 0;

        while (it != argument.end() && *it == L'\\') {
          ++it;
          ++number_backslashes;
        }

        if (it == argument.end()) {

          //
          // Escape all backslashes, but let the terminating
          // double quotation mark we add below be interpreted
          // as a metacharacter.
          //

          command_line.append(number_backslashes * 2, L'\\');
          break;
        }
        else if (*it == L'"') {

          //
          // Escape all backslashes and the following
          // double quotation mark.
          //

          command_line.append(number_backslashes * 2 + 1, L'\\');
          command_line.push_back(*it);
        }
        else {

          //
          // Backslashes aren't special here.
          //

          command_line.append(number_backslashes, L'\\');
          command_line.push_back(*it);
        }
      }

      command_line.push_back(L'"');
    }
  }

#ifdef __USING_WINDOWS__
  inline std::string get_last_error(DWORD errorMessageID)
  {
    if (errorMessageID == 0)
      return std::string();

    LPSTR messageBuffer = nullptr;
    size_t size = FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
        NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPSTR)&messageBuffer, 0, NULL);

    std::string message(messageBuffer, size);

    LocalFree(messageBuffer);

    return message;
  }

  inline FILE *file_from_handle(HANDLE h, const char *mode)
  {
    int md;
    if (!mode) {
      throw OSError("invalid_mode", 0);
    }

    if (mode[0] == 'w') {
      md = _O_WRONLY;
    }
    else if (mode[0] == 'r') {
      md = _O_RDONLY;
    }
    else {
      throw OSError("file_from_handle", 0);
    }

    int os_fhandle = _open_osfhandle((intptr_t)h, md);
    if (os_fhandle == -1) {
      CloseHandle(h);
      throw OSError("_open_osfhandle", 0);
    }

    FILE *fp = _fdopen(os_fhandle, mode);
    if (fp == 0) {
      _close(os_fhandle);
      throw OSError("_fdopen", 0);
    }

    return fp;
  }

  inline void configure_pipe(HANDLE* read_handle, HANDLE* write_handle, HANDLE* child_handle)
  {
    SECURITY_ATTRIBUTES saAttr;

    // Set the bInheritHandle flag so pipe handles are inherited.
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    // Create a pipe for the child process's STDIN.
    if (!CreatePipe(read_handle, write_handle, &saAttr,0))
      throw OSError("CreatePipe", 0);

    // Ensure the write handle to the pipe for STDIN is not inherited.
    if (!SetHandleInformation(*child_handle, HANDLE_FLAG_INHERIT, 0))
      throw OSError("SetHandleInformation", 0);
  }
#endif

  /*!
   * Function: split
   * Parameters:
   * [in] str : Input string which needs to be split based upon the
   *            delimiters provided.
   * [in] deleims : Delimiter characters based upon which the string needs
   *                to be split. Default constructed to ' '(space) and '\t'(tab)
   * [out] vector<string> : Vector of strings split at deleimiter.
   */
  static inline std::vector<std::string>
  split(const std::string& str, const std::string& delims=" \t")
  {
    std::vector<std::string> res;
    size_t init = 0;

    while (true) {
      auto pos = str.find_first_of(delims, init);
      if (pos == std::string::npos) {
        res.emplace_back(str.substr(init, str.length()));
        break;
      }
      res.emplace_back(str.substr(init, pos - init));
      pos++;
      init = pos;
    }

    return res;
  }


#ifndef __USING_WINDOWS__
  /*!
   * Function: set_clo_on_exec
   * Sets/Resets the FD_CLOEXEC flag on the provided file descriptor
   * based upon the `set` parameter.
   * Parameters:
   * [in] fd : The descriptor on which FD_CLOEXEC needs to be set/reset.
   * [in] set : If 'true', set FD_CLOEXEC.
   *            If 'false' unset FD_CLOEXEC.
   */
  static inline
  void set_clo_on_exec(int fd, bool set = true)
  {
    int flags = fcntl(fd, F_GETFD, 0);
    if (set) flags |= FD_CLOEXEC;
    else flags &= ~FD_CLOEXEC;
    //TODO: should check for errors
    fcntl(fd, F_SETFD, flags);
  }


  /*!
   * Function: pipe_cloexec
   * Creates a pipe and sets FD_CLOEXEC flag on both
   * read and write descriptors of the pipe.
   * Parameters:
   * [out] : A pair of file descriptors.
   *         First element of pair is the read descriptor of pipe.
   *         Second element is the write descriptor of pipe.
   */
  static inline
  std::pair<int, int> pipe_cloexec() noexcept(false)
  {
    int pipe_fds[2];
    int res = pipe(pipe_fds);
    if (res) {
      throw OSError("pipe failure", errno);
    }

    set_clo_on_exec(pipe_fds[0]);
    set_clo_on_exec(pipe_fds[1]);

    return std::make_pair(pipe_fds[0], pipe_fds[1]);
  }
#endif


  /*!
   * Function: write_n
   * Writes `length` bytes to the file descriptor `fd`
   * from the buffer `buf`.
   * Parameters:
   * [in] fd : The file descriptotr to write to.
   * [in] buf: Buffer from which data needs to be written to fd.
   * [in] length: The number of bytes that needs to be written from
   *              `buf` to `fd`.
   * [out] int : Number of bytes written or -1 in case of failure.
   */
  static inline
  int write_n(int fd, const char* buf, size_t length)
  {
    size_t nwritten = 0;
    while (nwritten < length) {
      int written = write(fd, buf + nwritten, length - nwritten);
      if (written == -1) return -1;
      nwritten += written;
    }
    return nwritten;
  }


  /*!
   * Function: read_atmost_n
   * Reads at the most `read_upto` bytes from the
   * file object `fp` before returning.
   * Parameters:
   * [in] fp : The file object from which it needs to read.
   * [in] buf : The buffer into which it needs to write the data.
   * [in] read_upto: Max number of bytes which must be read from `fd`.
   * [out] int : Number of bytes written to `buf` or read from `fd`
   *             OR -1 in case of error.
   *  NOTE: In case of EINTR while reading from socket, this API
   *  will retry to read from `fd`, but only till the EINTR counter
   *  reaches 50 after which it will return with whatever data it read.
   */
  static inline
  int read_atmost_n(FILE* fp, char* buf, size_t read_upto)
  {
#ifdef __USING_WINDOWS__
    return (int)fread(buf, 1, read_upto, fp);
#else
    int fd = fileno(fp);
    int rbytes = 0;
    int eintr_cnter = 0;

    while (1) {
      int read_bytes = read(fd, buf + rbytes, read_upto - rbytes);
      if (read_bytes == -1) {
        if (errno == EINTR) {
          if (eintr_cnter >= 50) return -1;
          eintr_cnter++;
          continue;
        }
        return -1;
      }
      if (read_bytes == 0) return rbytes;

      rbytes += read_bytes;
    }
    return rbytes;
#endif
  }


  /*!
   * Function: read_all
   * Reads all the available data from `fp` into
   * `buf`. Internally calls read_atmost_n.
   * Parameters:
   * [in] fp : The file object from which to read from.
   * [in] buf : The buffer of type `class Buffer` into which
   *            the read data is written to.
   * [out] int: Number of bytes read OR -1 in case of failure.
   *
   * NOTE: `class Buffer` is a exposed public class. See below.
   */

  static inline int read_all(FILE* fp, std::vector<char>& buf)
  {
    auto buffer = buf.data();
    int total_bytes_read = 0;
    int fill_sz = buf.size();

    while (1) {
      const int rd_bytes = read_atmost_n(fp, buffer, fill_sz);

      if (rd_bytes == -1) { // Read finished
        if (total_bytes_read == 0) return -1;
        break;

      } else if (rd_bytes == fill_sz) { // Buffer full
        const auto orig_sz = buf.size();
        const auto new_sz = orig_sz * 2;
        buf.resize(new_sz);
        fill_sz = new_sz - orig_sz;

        //update the buffer pointer
        buffer = buf.data();
        total_bytes_read += rd_bytes;
        buffer += total_bytes_read;

      } else { // Partial data ? Continue reading
        total_bytes_read += rd_bytes;
        fill_sz -= rd_bytes;
        break;
      }
    }
    buf.erase(buf.begin()+total_bytes_read, buf.end()); // remove extra nulls
    return total_bytes_read;
  }

#ifndef __USING_WINDOWS__
  /*!
   * Function: wait_for_child_exit
   * Waits for the process with pid `pid` to exit
   * and returns its status.
   * Parameters:
   * [in] pid : The pid of the process.
   * [out] pair<int, int>:
   *    pair.first : Return code of the waitpid call.
   *    pair.second : Exit status of the process.
   *
   *  NOTE: This is a blocking call as in, it will loop
   *  till the child is exited.
   */
  static inline
  std::pair<int, int> wait_for_child_exit(int pid)
  {
    int status = 0;
    int ret = -1;
    while (1) {
      ret = waitpid(pid, &status, 0);
      if (ret == -1) break;
      if (ret == 0) continue;
      return std::make_pair(ret, status);
    }

    return std::make_pair(ret, status);
  }
#endif

} // end namespace util



/* -------------------------------
 *     Popen Arguments
 * -------------------------------
 */

/*!
 * Base class for all arguments involving string value.
 */
struct string_arg
{
  string_arg(const char* arg): arg_value(arg) {}
  string_arg(std::string&& arg): arg_value(std::move(arg)) {}
  string_arg(std::string arg): arg_value(std::move(arg)) {}
  std::string arg_value;
};

/*!
 * Option to specify the executable name separately
 * from the args sequence.
 * In this case the cmd args must only contain the
 * options required for this executable.
 *
 * Eg: executable{"ls"}
 */
struct executable: string_arg
{
  template <typename T>
  executable(T&& arg): string_arg(std::forward<T>(arg)) {}
};

/*!
 * Used for redirecting input/output/error
 */
enum IOTYPE {
  STDOUT = 1,
  STDERR,
  PIPE,
};

//TODO: A common base/interface for below stream structures ??

/*!
 * Option to specify the input channel for the child
 * process. It can be:
 * 1. An already open file descriptor.
 * 2. A file name.
 * 3. IOTYPE. Usual a PIPE
 *
 * Eg: input{PIPE}
 * OR in case of redirection, output of another Popen
 * input{popen.output()}
 */
struct input
{
  // For an already existing file descriptor.
  explicit input(int fd): rd_ch_(fd) {}

  // FILE pointer.
  explicit input (FILE* fp):input(fileno(fp)) { assert(fp); }

  explicit input(const char* filename) {
    int fd = open(filename, O_RDONLY);
    if (fd == -1) throw OSError("File not found: ", errno);
    rd_ch_ = fd;
  }
  explicit input(IOTYPE typ) {
    assert (typ == PIPE && "STDOUT/STDERR not allowed");
#ifndef __USING_WINDOWS__
    std::tie(rd_ch_, wr_ch_) = util::pipe_cloexec();
#endif
  }

  int rd_ch_ = -1;
  int wr_ch_ = -1;
};


/*!
 * Option to specify the output channel for the child
 * process. It can be:
 * 1. An already open file descriptor.
 * 2. A file name.
 * 3. IOTYPE. Usually a PIPE.
 *
 * Eg: output{PIPE}
 * OR output{"output.txt"}
 */
struct output
{
  explicit output(int fd): wr_ch_(fd) {}

  explicit output (FILE* fp):output(fileno(fp)) { assert(fp); }

  explicit output(const char* filename) {
    int fd = open(filename, O_APPEND | O_CREAT | O_RDWR, 0640);
    if (fd == -1) throw OSError("File not found: ", errno);
    wr_ch_ = fd;
  }
  explicit output(IOTYPE typ) {
    assert (typ == PIPE && "STDOUT/STDERR not allowed");
#ifndef __USING_WINDOWS__
    std::tie(rd_ch_, wr_ch_) = util::pipe_cloexec();
#endif
  }

  int rd_ch_ = -1;
  int wr_ch_ = -1;
};


/*!
 * Option to specify the error channel for the child
 * process. It can be:
 * 1. An already open file descriptor.
 * 2. A file name.
 * 3. IOTYPE. Usually a PIPE or STDOUT
 *
 */
struct error
{
  explicit error(int fd): wr_ch_(fd) {}

  explicit error(FILE* fp):error(fileno(fp)) { assert(fp); }

  explicit error(const char* filename) {
    int fd = open(filename, O_APPEND | O_CREAT | O_RDWR, 0640);
    if (fd == -1) throw OSError("File not found: ", errno);
    wr_ch_ = fd;
  }
  explicit error(IOTYPE typ) {
    assert ((typ == PIPE || typ == STDOUT) && "STDERR not allowed");
    if (typ == PIPE) {
#ifndef __USING_WINDOWS__
      std::tie(rd_ch_, wr_ch_) = util::pipe_cloexec();
#endif
    } else {
      // Need to defer it till we have checked all arguments
      deferred_ = true;
    }
  }

  bool deferred_ = false;
  int rd_ch_ = -1;
  int wr_ch_ = -1;
};

// ~~~~ End Popen Args ~~~~


/*!
 * class: Buffer
 * This class is a very thin wrapper around std::vector<char>
 * This is basically used to determine the length of the actual
 * data stored inside the dynamically resized vector.
 *
 * This is what is returned as the output to the communicate
 * function, so, users must know about this class.
 *
 * OutBuffer and ErrBuffer are just different typedefs to this class.
 */
class Buffer
{
public:
  Buffer() {}
  explicit Buffer(size_t cap) { buf.resize(cap); }
  void add_cap(size_t cap) { buf.resize(cap); }

public:
  std::vector<char> buf;
  size_t length = 0;
};

// Buffer for storing output written to output fd
using OutBuffer = Buffer;
// Buffer for storing output written to error fd
using ErrBuffer = Buffer;


// Fwd Decl.
class Popen;

/*---------------------------------------------------
 *      DETAIL NAMESPACE
 *---------------------------------------------------
 */

namespace detail {
/*!
 * A helper class to Popen class for setting
 * options as provided in the Popen constructor.
 * This design allows us to _not_ have any fixed position
 * to any arguments and specify them in a way similar to what
 * can be done in python.
 */
struct ArgumentDeducer
{
  ArgumentDeducer(Popen* p): popen_(p) {}

  void set_option(executable&& exe);
  void set_option(input&& inp);
  void set_option(output&& out);
  void set_option(error&& err);

private:
  Popen* popen_ = nullptr;
};

/*!
 * A helper class to Popen.
 * This takes care of all the fork-exec logic
 * in the execute_child API.
 */
class Child
{
public:
  Child(Popen* p, int err_wr_pipe):
    parent_(p),
    err_wr_pipe_(err_wr_pipe)
  {}

  void execute_child();

private:
  // Lets call it parent even though
  // technically a bit incorrect
  Popen* parent_ = nullptr;
  int err_wr_pipe_ = -1;
};

// Fwd Decl.
class Streams;

/*!
 * A helper class to Streams.
 * This takes care of management of communicating
 * with the child process with the means of the correct
 * file descriptor.
 */
class Communication
{
public:
  Communication(Streams* stream): stream_(stream)
  {}
  void operator=(const Communication&) = delete;
public:
  int send(const char* msg, size_t length);
  int send(const std::vector<char>& msg);

  std::pair<OutBuffer, ErrBuffer> communicate(const char* msg, size_t length);
  std::pair<OutBuffer, ErrBuffer> communicate(const std::vector<char>& msg)
  { return communicate(msg.data(), msg.size()); }

  void set_out_buf_cap(size_t cap) { out_buf_cap_ = cap; }
  void set_err_buf_cap(size_t cap) { err_buf_cap_ = cap; }

private:
  std::pair<OutBuffer, ErrBuffer> communicate_threaded(
      const char* msg, size_t length);

private:
  Streams* stream_;
  size_t out_buf_cap_ = DEFAULT_BUF_CAP_BYTES;
  size_t err_buf_cap_ = DEFAULT_BUF_CAP_BYTES;
};



/*!
 * This is a helper class to Popen.
 * It takes care of management of all the file descriptors
 * and file pointers.
 * It dispatches of the communication aspects to the
 * Communication class.
 * Read through the data members to understand about the
 * various file descriptors used.
 */
class Streams
{
public:
  Streams():comm_(this) {}
  void operator=(const Streams&) = delete;

public:
  void setup_comm_channels();

  void cleanup_fds()
  {
    if (write_to_child_ != -1 && read_from_parent_ != -1) {
      close(write_to_child_);
    }
    if (write_to_parent_ != -1 && read_from_child_ != -1) {
      close(read_from_child_);
    }
    if (err_write_ != -1 && err_read_ != -1) {
      close(err_read_);
    }
  }

  void close_parent_fds()
  {
    if (write_to_child_ != -1)  close(write_to_child_);
    if (read_from_child_ != -1) close(read_from_child_);
    if (err_read_ != -1)        close(err_read_);
  }

  void close_child_fds()
  {
    if (write_to_parent_ != -1)  close(write_to_parent_);
    if (read_from_parent_ != -1) close(read_from_parent_);
    if (err_write_ != -1)        close(err_write_);
  }

  FILE* input()  { return input_.get(); }
  FILE* output() { return output_.get(); }
  FILE* error()  { return error_.get(); }

  void input(FILE* fp)  { input_.reset(fp, fclose); }
  void output(FILE* fp) { output_.reset(fp, fclose); }
  void error(FILE* fp)  { error_.reset(fp, fclose); }

  void set_out_buf_cap(size_t cap) { comm_.set_out_buf_cap(cap); }
  void set_err_buf_cap(size_t cap) { comm_.set_err_buf_cap(cap); }

public: /* Communication forwarding API's */
  int send(const char* msg, size_t length)
  { return comm_.send(msg, length); }

  int send(const std::vector<char>& msg)
  { return comm_.send(msg); }

  std::pair<OutBuffer, ErrBuffer> communicate(const char* msg, size_t length)
  { return comm_.communicate(msg, length); }

  std::pair<OutBuffer, ErrBuffer> communicate(const std::vector<char>& msg)
  { return comm_.communicate(msg); }


public:// Yes they are public

  std::shared_ptr<FILE> input_  = nullptr;
  std::shared_ptr<FILE> output_ = nullptr;
  std::shared_ptr<FILE> error_  = nullptr;

#ifdef __USING_WINDOWS__
  HANDLE g_hChildStd_IN_Rd = nullptr;
  HANDLE g_hChildStd_IN_Wr = nullptr;
  HANDLE g_hChildStd_OUT_Rd = nullptr;
  HANDLE g_hChildStd_OUT_Wr = nullptr;
  HANDLE g_hChildStd_ERR_Rd = nullptr;
  HANDLE g_hChildStd_ERR_Wr = nullptr;
#endif

  // Pipes for communicating with child

  // Emulates stdin
  int write_to_child_   = -1; // Parent owned descriptor
  int read_from_parent_ = -1; // Child owned descriptor

  // Emulates stdout
  int write_to_parent_ = -1; // Child owned descriptor
  int read_from_child_ = -1; // Parent owned descriptor

  // Emulates stderr
  int err_write_ = -1; // Write error to parent (Child owned)
  int err_read_  = -1; // Read error from child (Parent owned)

private:
  Communication comm_;
};

} // end namespace detail



/*!
 * class: Popen
 * This is the single most important class in the whole library
 * and glues together all the helper classes to provide a common
 * interface to the client.
 *
 * API's provided by the class:
 * Popen({"cmd"}, output{..}, error{..}, ....)
 *    Command provided as a sequence.
 * Popen("cmd arg1", output{..}, error{..}, ....)
 *    Command provided in a single string.
 * wait()             - Wait for the child to exit.
 * retcode()          - The return code of the exited child.
 * send(...)          - Send input to the input channel of the child.
 * communicate(...)   - Get the output/error from the child and close the channels
 *                      from the parent side.
 */
class Popen
{
public:
  friend struct detail::ArgumentDeducer;
  friend class detail::Child;

  template <typename... Args>
  Popen(const std::string& cmd_args, Args&& ...args):
    args_(cmd_args)
  {
    vargs_ = util::split(cmd_args);
    init_args(std::forward<Args>(args)...);

    // Setup the communication channels of the Popen class
    stream_.setup_comm_channels();

    execute_process();
  }

  template <typename... Args>
  Popen(std::initializer_list<const char*> cmd_args, Args&& ...args)
  {
    vargs_.insert(vargs_.end(), cmd_args.begin(), cmd_args.end());
    init_args(std::forward<Args>(args)...);

    // Setup the communication channels of the Popen class
    stream_.setup_comm_channels();

    execute_process();
  }

  template <typename... Args>
  Popen(std::vector<std::string> vargs_, Args &&... args) : vargs_(vargs_)
  {
    init_args(std::forward<Args>(args)...);

    // Setup the communication channels of the Popen class
    stream_.setup_comm_channels();

    execute_process();
  }

  int retcode() const noexcept { return retcode_; }

  int wait() noexcept(false);

  void set_out_buf_cap(size_t cap) { stream_.set_out_buf_cap(cap); }

  void set_err_buf_cap(size_t cap) { stream_.set_err_buf_cap(cap); }

  int send(const char* msg, size_t length)
  { return stream_.send(msg, length); }

  int send(const std::string& msg)
  { return send(msg.c_str(), msg.size()); }

  int send(const std::vector<char>& msg)
  { return stream_.send(msg); }

  std::pair<OutBuffer, ErrBuffer> communicate(const char* msg, size_t length)
  {
    auto res = stream_.communicate(msg, length);
    retcode_ = wait();
    return res;
  }

  std::pair<OutBuffer, ErrBuffer> communicate(const std::string& msg)
  {
    return communicate(msg.c_str(), msg.size());
  }

  std::pair<OutBuffer, ErrBuffer> communicate(const std::vector<char>& msg)
  {
    auto res = stream_.communicate(msg);
    retcode_ = wait();
    return res;
  }

  std::pair<OutBuffer, ErrBuffer> communicate()
  {
    return communicate(nullptr, 0);
  }

private:
  template <typename F, typename... Args>
  void init_args(F&& farg, Args&&... args);
  void init_args();
  void populate_c_argv();
  void execute_process() noexcept(false);

private:
  detail::Streams stream_;

#ifdef __USING_WINDOWS__
  HANDLE process_handle_;
  std::future<void> cleanup_future_;
#endif

  std::string exe_name_;

  // Command in string format
  std::string args_;
  // Command provided as sequence
  std::vector<std::string> vargs_;
  std::vector<char*> cargv_;

  // Pid of the child process
  int child_pid_ = -1;

  int retcode_ = -1;
};

inline void Popen::init_args() {
  populate_c_argv();
}

template <typename F, typename... Args>
inline void Popen::init_args(F&& farg, Args&&... args)
{
  detail::ArgumentDeducer argd(this);
  argd.set_option(std::forward<F>(farg));
  init_args(std::forward<Args>(args)...);
}

inline void Popen::populate_c_argv()
{
  cargv_.clear();
  cargv_.reserve(vargs_.size() + 1);
  for (auto& arg : vargs_) cargv_.push_back(&arg[0]);
  cargv_.push_back(nullptr);
}

inline int Popen::wait() noexcept(false)
{
#ifdef __USING_WINDOWS__
  int ret = WaitForSingleObject(process_handle_, INFINITE);

  return 0;
#else
  int ret, status;
  std::tie(ret, status) = util::wait_for_child_exit(child_pid_);
  if (ret == -1) {
    if (errno != ECHILD) throw OSError("waitpid failed", errno);
    return 0;
  }
  if (WIFEXITED(status)) return WEXITSTATUS(status);
  if (WIFSIGNALED(status)) return WTERMSIG(status);
  else return 255;

  return 0;
#endif
}

inline void Popen::execute_process() noexcept(false)
{
#ifdef __USING_WINDOWS__
  if (exe_name_.length()) {
    this->vargs_.insert(this->vargs_.begin(), this->exe_name_);
    this->populate_c_argv();
  }
  this->exe_name_ = vargs_[0];

  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
  std::wstring argument;
  std::wstring command_line;

  for (auto arg : this->vargs_) {
    argument = converter.from_bytes(arg);
    util::quote_argument(argument, command_line, false);
    command_line += L" ";
  }

  // CreateProcessW can modify szCmdLine so we allocate needed memory
  wchar_t *szCmdline = new wchar_t[command_line.size() + 1];
  wcscpy_s(szCmdline, command_line.size() + 1, command_line.c_str());
  PROCESS_INFORMATION piProcInfo;
  STARTUPINFOW siStartInfo;
  BOOL bSuccess = FALSE;
  DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW;

  // Set up members of the PROCESS_INFORMATION structure.
  ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));

  // Set up members of the STARTUPINFOW structure.
  // This structure specifies the STDIN and STDOUT handles for redirection.

  ZeroMemory(&siStartInfo, sizeof(STARTUPINFOW));
  siStartInfo.cb = sizeof(STARTUPINFOW);

  siStartInfo.hStdError = this->stream_.g_hChildStd_ERR_Wr;
  siStartInfo.hStdOutput = this->stream_.g_hChildStd_OUT_Wr;
  siStartInfo.hStdInput = this->stream_.g_hChildStd_IN_Rd;

  siStartInfo.dwFlags |= STARTF_USESTDHANDLES;

  // Create the child process.
  bSuccess = CreateProcessW(NULL,
                            szCmdline,    // command line
                            NULL,         // process security attributes
                            NULL,         // primary thread security attributes
                            TRUE,         // handles are inherited
                            creation_flags,	// creation flags
                            NULL,         // use parent's environment
                            NULL,         // use parent's current directory
                            &siStartInfo, // STARTUPINFOW pointer
                            &piProcInfo); // receives PROCESS_INFORMATION

  // If an error occurs, exit the application.
  if (!bSuccess) {
    DWORD errorMessageID = ::GetLastError();
    throw CalledProcessError("CreateProcess failed: " + util::get_last_error(errorMessageID), errorMessageID);
  }

  CloseHandle(piProcInfo.hThread);

  /*
    TODO: use common apis to close linux handles
  */

  this->process_handle_ = piProcInfo.hProcess;

  this->cleanup_future_ = std::async(std::launch::async, [this] {
    WaitForSingleObject(this->process_handle_, INFINITE);

    CloseHandle(this->stream_.g_hChildStd_ERR_Wr);
    CloseHandle(this->stream_.g_hChildStd_OUT_Wr);
    CloseHandle(this->stream_.g_hChildStd_IN_Rd);
  });

/*
  NOTE: In the linux version, there is a check to make sure that the process
        has been started. Here, we do nothing because CreateProcess will throw
        if we fail to create the process.
*/


#else

  int err_rd_pipe, err_wr_pipe;
  std::tie(err_rd_pipe, err_wr_pipe) = util::pipe_cloexec();

  if (exe_name_.length()) {
    vargs_.insert(vargs_.begin(), exe_name_);
    populate_c_argv();
  }
  exe_name_ = vargs_[0];

  child_pid_ = fork();

  if (child_pid_ < 0) {
    close(err_rd_pipe);
    close(err_wr_pipe);
    throw OSError("fork failed", errno);
  }

  if (child_pid_ == 0)
  {
    // Close descriptors belonging to parent
    stream_.close_parent_fds();

    //Close the read end of the error pipe
    close(err_rd_pipe);

    detail::Child chld(this, err_wr_pipe);
    chld.execute_child();
  }
  else
  {
    close (err_wr_pipe);// close child side of pipe, else get stuck in read below

    stream_.close_child_fds();

    try {
      char err_buf[SP_MAX_ERR_BUF_SIZ] = {0,};

      int read_bytes = util::read_atmost_n(
                                  fdopen(err_rd_pipe, "r"),
                                  err_buf,
                                  SP_MAX_ERR_BUF_SIZ);
      close(err_rd_pipe);

      if (read_bytes || strlen(err_buf)) {
        // Call waitpid to reap the child process
        // waitpid suspends the calling process until the
        // child terminates.
        int retcode = wait();

        // Throw whatever information we have about child failure
        throw CalledProcessError(err_buf, retcode);
      }
    } catch (std::exception& exp) {
      stream_.cleanup_fds();
      throw;
    }

  }
#endif
}

namespace detail {

  inline void ArgumentDeducer::set_option(executable&& exe) {
    popen_->exe_name_ = std::move(exe.arg_value);
  }

  inline void ArgumentDeducer::set_option(input&& inp) {
    if (inp.rd_ch_ != -1) popen_->stream_.read_from_parent_ = inp.rd_ch_;
    if (inp.wr_ch_ != -1) popen_->stream_.write_to_child_ = inp.wr_ch_;
  }

  inline void ArgumentDeducer::set_option(output&& out) {
    if (out.wr_ch_ != -1) popen_->stream_.write_to_parent_ = out.wr_ch_;
    if (out.rd_ch_ != -1) popen_->stream_.read_from_child_ = out.rd_ch_;
  }

  inline void ArgumentDeducer::set_option(error&& err) {
    if (err.deferred_) {
      if (popen_->stream_.write_to_parent_) {
        popen_->stream_.err_write_ = popen_->stream_.write_to_parent_;
      } else {
        throw std::runtime_error("Set output before redirecting error to output");
      }
    }
    if (err.wr_ch_ != -1) popen_->stream_.err_write_ = err.wr_ch_;
    if (err.rd_ch_ != -1) popen_->stream_.err_read_ = err.rd_ch_;
  }


  inline void Child::execute_child() {
#ifndef __USING_WINDOWS__
    int sys_ret = -1;
    auto& stream = parent_->stream_;

    try {
      if (stream.write_to_parent_ == 0)
        stream.write_to_parent_ = dup(stream.write_to_parent_);

      if (stream.err_write_ == 0 || stream.err_write_ == 1)
        stream.err_write_ = dup(stream.err_write_);

      // Make the child owned descriptors as the
      // stdin, stdout and stderr for the child process
      auto _dup2_ = [](int fd, int to_fd) {
        if (fd == to_fd) {
          // dup2 syscall does not reset the
          // CLOEXEC flag if the descriptors
          // provided to it are same.
          // But, we need to reset the CLOEXEC
          // flag as the provided descriptors
          // are now going to be the standard
          // input, output and error
          util::set_clo_on_exec(fd, false);
        } else if(fd != -1) {
          int res = dup2(fd, to_fd);
          if (res == -1) throw OSError("dup2 failed", errno);
        }
      };

      // Create the standard streams
      _dup2_(stream.read_from_parent_, 0); // Input stream
      _dup2_(stream.write_to_parent_,  1); // Output stream
      _dup2_(stream.err_write_,        2); // Error stream

      // Close the duped descriptors
      if (stream.read_from_parent_ != -1 && stream.read_from_parent_ > 2)
        close(stream.read_from_parent_);

      if (stream.write_to_parent_ != -1 && stream.write_to_parent_ > 2)
        close(stream.write_to_parent_);

      if (stream.err_write_ != -1 && stream.err_write_ > 2)
        close(stream.err_write_);

      // Replace the current image with the executable
      sys_ret = execvp(parent_->exe_name_.c_str(), parent_->cargv_.data());

      if (sys_ret == -1) throw OSError("execve failed", errno);

    } catch (const OSError& exp) {
      // Just write the exception message
      // TODO: Give back stack trace ?
      std::string err_msg(exp.what());
      //ATTN: Can we do something on error here ?
      util::write_n(err_wr_pipe_, err_msg.c_str(), err_msg.length());
    }

    // Calling application would not get this
    // exit failure
    _exit (EXIT_FAILURE);
#endif
  }


  inline void Streams::setup_comm_channels()
  {
#ifdef __USING_WINDOWS__
    util::configure_pipe(&this->g_hChildStd_IN_Rd, &this->g_hChildStd_IN_Wr, &this->g_hChildStd_IN_Wr);
    this->input(util::file_from_handle(this->g_hChildStd_IN_Wr, "w"));
    this->write_to_child_ = _fileno(this->input());

    util::configure_pipe(&this->g_hChildStd_OUT_Rd, &this->g_hChildStd_OUT_Wr, &this->g_hChildStd_OUT_Rd);
    this->output(util::file_from_handle(this->g_hChildStd_OUT_Rd, "r"));
    this->read_from_child_ = _fileno(this->output());

    util::configure_pipe(&this->g_hChildStd_ERR_Rd, &this->g_hChildStd_ERR_Wr, &this->g_hChildStd_ERR_Rd);
    this->error(util::file_from_handle(this->g_hChildStd_ERR_Rd, "r"));
    this->err_read_ = _fileno(this->error());
#else

    if (write_to_child_ != -1)  input(fdopen(write_to_child_, "wb"));
    if (read_from_child_ != -1) output(fdopen(read_from_child_, "rb"));
    if (err_read_ != -1)        error(fdopen(err_read_, "rb"));

    auto handles = {input(), output(), error()};

    for (auto& h : handles) {
      if (h == nullptr) continue;
      setvbuf(h, nullptr, _IONBF, BUFSIZ);
    }
  #endif
  }

  inline int Communication::send(const char* msg, size_t length)
  {
    if (stream_->input() == nullptr) return -1;
    return std::fwrite(msg, sizeof(char), length, stream_->input());
  }

  inline int Communication::send(const std::vector<char>& msg)
  {
    return send(msg.data(), msg.size());
  }

  inline std::pair<OutBuffer, ErrBuffer>
  Communication::communicate(const char* msg, size_t length)
  {
    // Optimization from subprocess.py
    // If we are using one pipe, or no pipe
    // at all, using select() or threads is unnecessary.
    auto hndls = {stream_->input(), stream_->output(), stream_->error()};
    int count = std::count(std::begin(hndls), std::end(hndls), nullptr);
    const int len_conv = length;

    if (count >= 2) {
      OutBuffer obuf;
      ErrBuffer ebuf;
      if (stream_->input()) {
        if (msg) {
          int wbytes = std::fwrite(msg, sizeof(char), length, stream_->input());
          if (wbytes < len_conv) {
            if (errno != EPIPE && errno != EINVAL) {
              throw OSError("fwrite error", errno);
            }
          }
        }
        // Close the input stream
        stream_->input_.reset();
      } else if (stream_->output()) {
        // Read till EOF
        // ATTN: This could be blocking, if the process
        // at the other end screws up, we get screwed as well
        obuf.add_cap(out_buf_cap_);

        int rbytes = util::read_all(
                            stream_->output(),
                            obuf.buf);

        if (rbytes == -1) {
          throw OSError("read to obuf failed", errno);
        }

        obuf.length = rbytes;
        // Close the output stream
        stream_->output_.reset();

      } else if (stream_->error()) {
        // Same screwness applies here as well
        ebuf.add_cap(err_buf_cap_);

        int rbytes = util::read_atmost_n(
                                  stream_->error(),
                                  ebuf.buf.data(),
                                  ebuf.buf.size());

        if (rbytes == -1) {
          throw OSError("read to ebuf failed", errno);
        }

        ebuf.length = rbytes;
        // Close the error stream
        stream_->error_.reset();
      }
      return std::make_pair(std::move(obuf), std::move(ebuf));
    }

    return communicate_threaded(msg, length);
  }


  inline std::pair<OutBuffer, ErrBuffer>
  Communication::communicate_threaded(const char* msg, size_t length)
  {
    OutBuffer obuf;
    ErrBuffer ebuf;
    std::future<int> out_fut, err_fut;
    const int length_conv = length;

    if (stream_->output()) {
      obuf.add_cap(out_buf_cap_);

      out_fut = std::async(std::launch::async,
                          [&obuf, this] {
                            return util::read_all(this->stream_->output(), obuf.buf);
                          });
    }
    if (stream_->error()) {
      ebuf.add_cap(err_buf_cap_);

      err_fut = std::async(std::launch::async,
                          [&ebuf, this] {
                            return util::read_all(this->stream_->error(), ebuf.buf);
                          });
    }
    if (stream_->input()) {
      if (msg) {
        int wbytes = std::fwrite(msg, sizeof(char), length, stream_->input());
        if (wbytes < length_conv) {
          if (errno != EPIPE && errno != EINVAL) {
            throw OSError("fwrite error", errno);
          }
        }
      }
      stream_->input_.reset();
    }

    if (out_fut.valid()) {
      int res = out_fut.get();
      if (res != -1) obuf.length = res;
      else obuf.length = 0;
    }
    if (err_fut.valid()) {
      int res = err_fut.get();
      if (res != -1) ebuf.length = res;
      else ebuf.length = 0;
    }

    return std::make_pair(std::move(obuf), std::move(ebuf));
  }

} // end namespace detail

}

#endif // BITCOIN_UTIL_SUBPROCESS_H