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
|
// file : butl/process.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2016 Code Synthesis Ltd
// license : MIT; see accompanying LICENSE file
#include <butl/process>
#ifndef _WIN32
# include <unistd.h> // execvp, fork, dup2, pipe, chdir, *_FILENO, getpid
# include <sys/wait.h> // waitpid
#else
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h> // CreatePipe(), CreateProcess()
# include <io.h> // _open_osfhandle(), _get_osfhandle(), _close()
# include <fcntl.h> // _O_TEXT
# include <stdlib.h> // getenv()
# include <sys/types.h> // stat
# include <sys/stat.h> // stat(), S_IS*
# include <memory> // unique_ptr
# include <butl/path>
#endif
#include <cassert>
using namespace std;
namespace butl
{
class auto_fd
{
public:
explicit
auto_fd (int fd = -1) noexcept: fd_ (fd) {}
auto_fd (const auto_fd&) = delete;
auto_fd& operator= (const auto_fd&) = delete;
~auto_fd () noexcept {reset ();}
int
get () const noexcept {return fd_;}
int
release () noexcept
{
int r (fd_);
fd_ = -1;
return r;
}
void
reset (int fd = -1) noexcept
{
if (fd_ != -1)
{
#ifndef _WIN32
int r (close (fd_));
#else
int r (_close (fd_));
#endif
// The valid file descriptor that has no IO operations being
// performed on it should close successfully, unless something is
// severely damaged.
//
assert (r != -1);
}
fd_ = fd;
}
private:
int fd_;
};
#ifndef _WIN32
process::
process (const char* cwd, char const* const args[], int in, int out, int err)
{
using pipe = auto_fd[2];
pipe out_fd;
pipe in_ofd;
pipe in_efd;
auto fail = [](bool child) {throw process_error (errno, child);};
auto create_pipe = [&fail](pipe& p)
{
int pd[2];
if (::pipe (pd) == -1)
fail (false);
p[0].reset (pd[0]);
p[1].reset (pd[1]);
};
if (in == -1)
create_pipe (out_fd);
if (out == -1)
create_pipe (in_ofd);
if (err == -1)
create_pipe (in_efd);
handle = fork ();
if (handle == -1)
fail (false);
if (handle == 0)
{
// Child.
//
// Duplicate the user-supplied (fd != -1) or the created pipe descriptor
// to the standard stream descriptor (read end for STDIN_FILENO, write
// end otherwise). Close the the pipe afterwards.
//
auto duplicate = [&fail](int sd, int fd, pipe& pd)
{
if (fd == -1)
fd = pd[sd == STDIN_FILENO ? 0 : 1].get ();
assert (fd != -1);
if (dup2 (fd, sd) == -1)
fail (true);
pd[0].reset (); // Close.
pd[1].reset (); // Close.
};
if (in != STDIN_FILENO)
duplicate (STDIN_FILENO, in, out_fd);
if (out != STDOUT_FILENO)
duplicate (STDOUT_FILENO, out, in_ofd);
if (err != STDERR_FILENO)
duplicate (STDERR_FILENO, err, in_efd);
// Change current working directory if requested.
//
if (cwd != nullptr && *cwd != '\0' && chdir (cwd) != 0)
fail (true);
if (execvp (args[0], const_cast<char**> (&args[0])) == -1)
fail (true);
}
assert (handle != 0); // Shouldn't get here unless in the parent process.
this->out_fd = out_fd[1].release ();
this->in_ofd = in_ofd[0].release ();
this->in_efd = in_efd[0].release ();
}
process::
process (const char* cwd, char const* const args[],
process& in, int out, int err)
: process (cwd, args, in.in_ofd, out, err)
{
assert (in.in_ofd != -1); // Should be a pipe.
close (in.in_ofd); // Close it on our side.
}
bool process::
wait ()
{
if (handle != 0)
{
int r (waitpid (handle, &status, 0));
handle = 0; // We have tried.
if (r == -1)
throw process_error (errno, false);
}
return WIFEXITED (status) && WEXITSTATUS (status) == 0;
}
bool process::
try_wait (bool& s)
{
if (handle != 0)
{
int r (waitpid (handle, &status, WNOHANG));
if (r == 0) // Not exited yet.
return false;
handle = 0; // We have tried.
if (r == -1)
throw process_error (errno, false);
}
s = WIFEXITED (status) && WEXITSTATUS (status) == 0;
return true;
}
process::id_type process::
current_id ()
{
return getpid ();
}
#else // _WIN32
struct msg_deleter
{
void operator() (char* p) const {LocalFree (p);}
};
static string
error (DWORD e)
{
char* msg;
if (!FormatMessageA (
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK,
0,
e,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
(char*)&msg,
0,
0))
return "unknown error code " + to_string (e);
unique_ptr<char, msg_deleter> m (msg);
return msg;
}
static inline string
last_error ()
{
return error (GetLastError ());
}
static path
path_search (const path& f)
{
typedef path::traits traits;
// If there is a directory component in the file, then the PATH search
// does not apply.
//
if (!f.directory ().empty ())
return f;
string paths;
// If there is no PATH in the environment then the default search path is
// the current directory.
//
if (const char* s = getenv ("PATH"))
{
paths = s;
// Also check the current directory.
//
paths += traits::path_separator;
}
else
paths = traits::path_separator;
struct stat info;
for (size_t b (0), e (paths.find (traits::path_separator));
b != string::npos;)
{
path p (string (paths, b, e != string::npos ? e - b : e));
// Empty path (i.e., a double colon or a colon at the beginning or end
// of PATH) means search in the current dirrectory.
//
if (p.empty ())
p = path (".");
path dp (p / f);
// Just check that the file exist without checking for permissions, etc.
//
if (stat (dp.string ().c_str (), &info) == 0 && S_ISREG (info.st_mode))
return dp;
// Also try the path with the .exe extension.
//
dp += ".exe";
if (stat (dp.string ().c_str (), &info) == 0 && S_ISREG (info.st_mode))
return dp;
if (e == string::npos)
b = e;
else
{
b = e + 1;
e = paths.find (traits::path_separator, b);
}
}
return path ();
}
class auto_handle
{
public:
explicit
auto_handle (HANDLE h = INVALID_HANDLE_VALUE) noexcept: handle_ (h) {}
auto_handle (const auto_handle&) = delete;
auto_handle& operator= (const auto_handle&) = delete;
~auto_handle () noexcept {reset ();}
HANDLE
get () const noexcept {return handle_;}
HANDLE
release () noexcept
{
HANDLE r (handle_);
handle_ = INVALID_HANDLE_VALUE;
return r;
}
void
reset (HANDLE h = INVALID_HANDLE_VALUE) noexcept
{
if (handle_ != INVALID_HANDLE_VALUE)
{
bool r (CloseHandle (handle_));
// The valid process, thread or file handle that has no IO operations
// being performed on it should close successfully, unless something
// is severely damaged.
//
assert (r);
}
handle_ = h;
}
private:
HANDLE handle_;
};
process::
process (const char* cwd, char const* const args[], int in, int out, int err)
{
using pipe = auto_handle[2];
pipe out_h;
pipe in_oh;
pipe in_eh;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof (SECURITY_ATTRIBUTES);
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = 0;
auto fail = [](const char* m = nullptr)
{
throw process_error (m == nullptr ? last_error () : m);
};
// Create a pipe and clear the inherit flag on the parent side.
//
auto create_pipe = [&sa, &fail](pipe& p, int parent)
{
HANDLE ph[2];
if (!CreatePipe (&ph[0], &ph[1], &sa, 0))
fail ();
p[0].reset (ph[0]);
p[1].reset (ph[1]);
if (!SetHandleInformation (p[parent].get (), HANDLE_FLAG_INHERIT, 0))
fail ();
};
if (in == -1)
create_pipe (out_h, 1);
if (out == -1)
create_pipe (in_oh, 0);
if (err == -1)
create_pipe (in_eh, 0);
// Create the process.
//
path file (args[0]);
// Do PATH search.
//
if (file.directory ().empty ())
file = path_search (file);
if (file.empty ())
fail ("file not found");
// Serialize the arguments to string.
//
string cmd_line;
for (char const* const* p (args); *p != 0; ++p)
{
if (p != args)
cmd_line += ' ';
// On Windows we need to protect values with spaces using quotes. Since
// there could be actual quotes in the value, we need to escape them.
//
string a (*p);
bool quote (a.find (' ') != string::npos);
if (quote)
cmd_line += '"';
for (size_t i (0); i < a.size (); ++i)
{
if (a[i] == '"')
cmd_line += "\\\"";
else
cmd_line += a[i];
}
if (quote)
cmd_line += '"';
}
// Prepare other process information.
//
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset (&si, 0, sizeof (STARTUPINFO));
memset (&pi, 0, sizeof (PROCESS_INFORMATION));
si.cb = sizeof (STARTUPINFO);
si.dwFlags |= STARTF_USESTDHANDLES;
// Resolve file descriptor to HANDLE and make sure it is inherited. Note
// that the handle is closed when _close() is called for the associated
// file descriptor.
//
auto get_osfhandle = [&fail](int fd) -> HANDLE
{
HANDLE h (reinterpret_cast<HANDLE> (_get_osfhandle (fd)));
if (h == INVALID_HANDLE_VALUE)
fail ("unable to obtain file handle");
// SetHandleInformation() fails for standard handles. We assume they are
// inherited by default.
//
if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
{
if (!SetHandleInformation (
h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
fail ();
}
return h;
};
si.hStdInput = in == -1
? out_h[0].get ()
: in == STDIN_FILENO
? GetStdHandle (STD_INPUT_HANDLE)
: get_osfhandle (in);
si.hStdOutput = out == -1
? in_oh[1].get ()
: out == STDOUT_FILENO
? GetStdHandle (STD_OUTPUT_HANDLE)
: get_osfhandle (out);
si.hStdError = err == -1
? in_eh[1].get ()
: err == STDERR_FILENO
? GetStdHandle (STD_ERROR_HANDLE)
: get_osfhandle (err);
// Perform standard stream redirection if requested.
//
if (si.hStdError == GetStdHandle (STD_OUTPUT_HANDLE))
si.hStdError = si.hStdOutput;
else if (si.hStdOutput == GetStdHandle (STD_ERROR_HANDLE))
si.hStdOutput = si.hStdError;
if (si.hStdError == GetStdHandle (STD_INPUT_HANDLE) ||
si.hStdOutput == GetStdHandle (STD_INPUT_HANDLE) ||
si.hStdInput == GetStdHandle (STD_OUTPUT_HANDLE) ||
si.hStdInput == GetStdHandle (STD_ERROR_HANDLE))
fail ("invalid file descriptor");
if (!CreateProcess (
file.string ().c_str (),
const_cast<char*> (cmd_line.c_str ()),
0, // Process security attributes.
0, // Primary thread security attributes.
true, // Inherit handles.
0, // Creation flags.
0, // Use our environment.
cwd != nullptr && *cwd != '\0' ? cwd : nullptr,
&si,
&pi))
fail ();
auto_handle (pi.hThread).reset (); // Close.
auto_handle process (pi.hProcess);
// Convert file handles to file descriptors. Note that the handle is
// closed when _close() is called for the returned file descriptor.
//
auto open_osfhandle = [&fail](auto_handle& h) -> int
{
int fd (
_open_osfhandle (reinterpret_cast<intptr_t> (h.get ()), _O_TEXT));
if (fd == -1)
fail ("unable to convert file handle to file descriptor");
h.release ();
return fd;
};
auto_fd out_fd (in == -1 ? open_osfhandle (out_h[1]) : -1);
auto_fd in_ofd (out == -1 ? open_osfhandle (in_oh[0]) : -1);
auto_fd in_efd (err == -1 ? open_osfhandle (in_eh[0]) : -1);
this->out_fd = out_fd.release ();
this->in_ofd = in_ofd.release ();
this->in_efd = in_efd.release ();
this->handle = process.release ();
// 0 has a special meaning denoting a terminated process handle.
//
assert (this->handle != 0 && this->handle != INVALID_HANDLE_VALUE);
}
process::
process (const char* cwd, char const* const args[],
process& in, int out, int err)
: process (cwd, args, in.in_ofd, out, err)
{
assert (in.in_ofd != -1); // Should be a pipe.
_close (in.in_ofd); // Close it on our side.
}
bool process::
wait ()
{
if (handle != 0)
{
DWORD s;
DWORD e (NO_ERROR);
if (WaitForSingleObject (handle, INFINITE) != WAIT_OBJECT_0 ||
!GetExitCodeProcess (handle, &s))
e = GetLastError ();
auto_handle h (handle); // Auto-deleter.
handle = 0; // We have tried.
if (e != NO_ERROR)
throw process_error (error (e));
status = s;
}
return status == 0;
}
bool process::
try_wait (bool& s)
{
if (handle != 0)
{
DWORD r (WaitForSingleObject (handle, 0));
if (r == WAIT_TIMEOUT)
return false;
DWORD s;
DWORD e (NO_ERROR);
if (r != WAIT_OBJECT_0 || !GetExitCodeProcess (handle, &s))
e = GetLastError ();
auto_handle h (handle);
handle = 0; // We have tried.
if (e != NO_ERROR)
throw process_error (error (e));
status = s;
}
s = status == 0;
return true;
}
process::id_type process::
current_id ()
{
return GetCurrentProcessId ();
}
#endif // _WIN32
}
|