GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/spawn_sync.cc Lines: 490 537 91.2 %
Date: 2020-05-27 22:15:15 Branches: 201 306 65.7 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "spawn_sync.h"
23
#include "debug_utils-inl.h"
24
#include "env-inl.h"
25
#include "node_internals.h"
26
#include "string_bytes.h"
27
#include "util-inl.h"
28
29
#include <cstring>
30
31
32
namespace node {
33
34
using v8::Array;
35
using v8::Context;
36
using v8::EscapableHandleScope;
37
using v8::FunctionCallbackInfo;
38
using v8::HandleScope;
39
using v8::Int32;
40
using v8::Integer;
41
using v8::Isolate;
42
using v8::Just;
43
using v8::Local;
44
using v8::Maybe;
45
using v8::MaybeLocal;
46
using v8::Nothing;
47
using v8::Null;
48
using v8::Number;
49
using v8::Object;
50
using v8::String;
51
using v8::Value;
52
53
18743
void SyncProcessOutputBuffer::OnAlloc(size_t suggested_size,
54
                                      uv_buf_t* buf) const {
55
18743
  if (used() == kBufferSize)
56
    *buf = uv_buf_init(nullptr, 0);
57
  else
58
18743
    *buf = uv_buf_init(data_ + used(), available());
59
18743
}
60
61
62
17807
void SyncProcessOutputBuffer::OnRead(const uv_buf_t* buf, size_t nread) {
63
  // If we hand out the same chunk twice, this should catch it.
64
17807
  CHECK_EQ(buf->base, data_ + used());
65
17807
  used_ += static_cast<unsigned int>(nread);
66
17807
}
67
68
69
1159
size_t SyncProcessOutputBuffer::Copy(char* dest) const {
70
1159
  memcpy(dest, data_, used());
71
1159
  return used();
72
}
73
74
75
36518
unsigned int SyncProcessOutputBuffer::available() const {
76
36518
  return sizeof data_ - used();
77
}
78
79
80
95288
unsigned int SyncProcessOutputBuffer::used() const {
81
95288
  return used_;
82
}
83
84
85
3477
SyncProcessOutputBuffer* SyncProcessOutputBuffer::next() const {
86
3477
  return next_;
87
}
88
89
90
191
void SyncProcessOutputBuffer::set_next(SyncProcessOutputBuffer* next) {
91
191
  next_ = next;
92
191
}
93
94
95
1904
SyncProcessStdioPipe::SyncProcessStdioPipe(SyncProcessRunner* process_handler,
96
                                           bool readable,
97
                                           bool writable,
98
1904
                                           uv_buf_t input_buffer)
99
    : process_handler_(process_handler),
100
      readable_(readable),
101
      writable_(writable),
102
      input_buffer_(input_buffer),
103
104
      first_output_buffer_(nullptr),
105
      last_output_buffer_(nullptr),
106
107
      uv_pipe_(),
108
      write_req_(),
109
      shutdown_req_(),
110
111
1904
      lifecycle_(kUninitialized) {
112

1904
  CHECK(readable || writable);
113
1904
}
114
115
116
3808
SyncProcessStdioPipe::~SyncProcessStdioPipe() {
117

1904
  CHECK(lifecycle_ == kUninitialized || lifecycle_ == kClosed);
118
119
  SyncProcessOutputBuffer* buf;
120
  SyncProcessOutputBuffer* next;
121
122
3063
  for (buf = first_output_buffer_; buf != nullptr; buf = next) {
123
1159
    next = buf->next();
124
1159
    delete buf;
125
  }
126
1904
}
127
128
129
1904
int SyncProcessStdioPipe::Initialize(uv_loop_t* loop) {
130
1904
  CHECK_EQ(lifecycle_, kUninitialized);
131
132
1904
  int r = uv_pipe_init(loop, uv_pipe(), 0);
133
1904
  if (r < 0)
134
    return r;
135
136
1904
  uv_pipe()->data = this;
137
138
1904
  lifecycle_ = kInitialized;
139
1904
  return 0;
140
}
141
142
143
1469
int SyncProcessStdioPipe::Start() {
144
1469
  CHECK_EQ(lifecycle_, kInitialized);
145
146
  // Set the busy flag already. If this function fails no recovery is
147
  // possible.
148
1469
  lifecycle_ = kStarted;
149
150
1469
  if (readable()) {
151
483
    if (input_buffer_.len > 0) {
152
22
      CHECK_NOT_NULL(input_buffer_.base);
153
154
22
      int r = uv_write(&write_req_,
155
                       uv_stream(),
156
22
                       &input_buffer_,
157
                       1,
158
22
                       WriteCallback);
159
22
      if (r < 0)
160
        return r;
161
    }
162
163
483
    int r = uv_shutdown(&shutdown_req_, uv_stream(), ShutdownCallback);
164
483
    if (r < 0)
165
      return r;
166
  }
167
168
1469
  if (writable()) {
169
986
    int r = uv_read_start(uv_stream(), AllocCallback, ReadCallback);
170
986
    if (r < 0)
171
      return r;
172
  }
173
174
1469
  return 0;
175
}
176
177
178
1904
void SyncProcessStdioPipe::Close() {
179

1904
  CHECK(lifecycle_ == kInitialized || lifecycle_ == kStarted);
180
181
1904
  uv_close(uv_handle(), CloseCallback);
182
183
1904
  lifecycle_ = kClosing;
184
1904
}
185
186
187
986
Local<Object> SyncProcessStdioPipe::GetOutputAsBuffer(Environment* env) const {
188
986
  size_t length = OutputLength();
189
1972
  Local<Object> js_buffer = Buffer::New(env, length).ToLocalChecked();
190
986
  CopyOutput(Buffer::Data(js_buffer));
191
986
  return js_buffer;
192
}
193
194
195
3373
bool SyncProcessStdioPipe::readable() const {
196
3373
  return readable_;
197
}
198
199
200
4842
bool SyncProcessStdioPipe::writable() const {
201
4842
  return writable_;
202
}
203
204
205
1904
uv_stdio_flags SyncProcessStdioPipe::uv_flags() const {
206
  unsigned int flags;
207
208
1904
  flags = UV_CREATE_PIPE;
209
1904
  if (readable())
210
628
    flags |= UV_READABLE_PIPE;
211
1904
  if (writable())
212
1276
    flags |= UV_WRITABLE_PIPE;
213
214
1904
  return static_cast<uv_stdio_flags>(flags);
215
}
216
217
218
9107
uv_pipe_t* SyncProcessStdioPipe::uv_pipe() const {
219
9107
  CHECK_LT(lifecycle_, kClosing);
220
9107
  return &uv_pipe_;
221
}
222
223
224
3395
uv_stream_t* SyncProcessStdioPipe::uv_stream() const {
225
3395
  return reinterpret_cast<uv_stream_t*>(uv_pipe());
226
}
227
228
229
1904
uv_handle_t* SyncProcessStdioPipe::uv_handle() const {
230
1904
  return reinterpret_cast<uv_handle_t*>(uv_pipe());
231
}
232
233
234
986
size_t SyncProcessStdioPipe::OutputLength() const {
235
  SyncProcessOutputBuffer* buf;
236
986
  size_t size = 0;
237
238
2145
  for (buf = first_output_buffer_; buf != nullptr; buf = buf->next())
239
1159
    size += buf->used();
240
241
986
  return size;
242
}
243
244
245
986
void SyncProcessStdioPipe::CopyOutput(char* dest) const {
246
  SyncProcessOutputBuffer* buf;
247
986
  size_t offset = 0;
248
249
2145
  for (buf = first_output_buffer_; buf != nullptr; buf = buf->next())
250
1159
    offset += buf->Copy(dest + offset);
251
986
}
252
253
254
18743
void SyncProcessStdioPipe::OnAlloc(size_t suggested_size, uv_buf_t* buf) {
255
  // This function assumes that libuv will never allocate two buffers for the
256
  // same stream at the same time. There's an assert in
257
  // SyncProcessOutputBuffer::OnRead that would fail if this assumption was
258
  // ever violated.
259
260
18743
  if (last_output_buffer_ == nullptr) {
261
    // Allocate the first capture buffer.
262
968
    first_output_buffer_ = new SyncProcessOutputBuffer();
263
968
    last_output_buffer_ = first_output_buffer_;
264
265
17775
  } else if (last_output_buffer_->available() == 0) {
266
    // The current capture buffer is full so get us a new one.
267
191
    SyncProcessOutputBuffer* buf = new SyncProcessOutputBuffer();
268
191
    last_output_buffer_->set_next(buf);
269
191
    last_output_buffer_ = buf;
270
  }
271
272
18743
  last_output_buffer_->OnAlloc(suggested_size, buf);
273
18743
}
274
275
276
18767
void SyncProcessStdioPipe::OnRead(const uv_buf_t* buf, ssize_t nread) {
277
18767
  if (nread == UV_EOF) {
278
    // Libuv implicitly stops reading on EOF.
279
280
17807
  } else if (nread < 0) {
281
    SetError(static_cast<int>(nread));
282
    // At some point libuv should really implicitly stop reading on error.
283
    uv_read_stop(uv_stream());
284
285
  } else {
286
17807
    last_output_buffer_->OnRead(buf, nread);
287
17807
    process_handler_->IncrementBufferSizeAndCheckOverflow(nread);
288
  }
289
18767
}
290
291
292
22
void SyncProcessStdioPipe::OnWriteDone(int result) {
293
22
  if (result < 0)
294
    SetError(result);
295
22
}
296
297
298
483
void SyncProcessStdioPipe::OnShutdownDone(int result) {
299
483
  if (result < 0)
300
    SetError(result);
301
483
}
302
303
304
1904
void SyncProcessStdioPipe::OnClose() {
305
1904
  lifecycle_ = kClosed;
306
1904
}
307
308
309
void SyncProcessStdioPipe::SetError(int error) {
310
  CHECK_NE(error, 0);
311
  process_handler_->SetPipeError(error);
312
}
313
314
315
18743
void SyncProcessStdioPipe::AllocCallback(uv_handle_t* handle,
316
                                         size_t suggested_size,
317
                                         uv_buf_t* buf) {
318
  SyncProcessStdioPipe* self =
319
18743
      reinterpret_cast<SyncProcessStdioPipe*>(handle->data);
320
18743
  self->OnAlloc(suggested_size, buf);
321
18743
}
322
323
324
18767
void SyncProcessStdioPipe::ReadCallback(uv_stream_t* stream,
325
                                        ssize_t nread,
326
                                        const uv_buf_t* buf) {
327
  SyncProcessStdioPipe* self =
328
18767
        reinterpret_cast<SyncProcessStdioPipe*>(stream->data);
329
18767
  self->OnRead(buf, nread);
330
18767
}
331
332
333
22
void SyncProcessStdioPipe::WriteCallback(uv_write_t* req, int result) {
334
  SyncProcessStdioPipe* self =
335
22
      reinterpret_cast<SyncProcessStdioPipe*>(req->handle->data);
336
22
  self->OnWriteDone(result);
337
22
}
338
339
340
483
void SyncProcessStdioPipe::ShutdownCallback(uv_shutdown_t* req, int result) {
341
  SyncProcessStdioPipe* self =
342
483
      reinterpret_cast<SyncProcessStdioPipe*>(req->handle->data);
343
344
  // On AIX, OS X and the BSDs, calling shutdown() on one end of a pipe
345
  // when the other end has closed the connection fails with ENOTCONN.
346
  // Libuv is not the right place to handle that because it can't tell
347
  // if the error is genuine but we here can.
348
483
  if (result == UV_ENOTCONN)
349
    result = 0;
350
351
483
  self->OnShutdownDone(result);
352
483
}
353
354
355
1904
void SyncProcessStdioPipe::CloseCallback(uv_handle_t* handle) {
356
  SyncProcessStdioPipe* self =
357
1904
      reinterpret_cast<SyncProcessStdioPipe*>(handle->data);
358
1904
  self->OnClose();
359
1904
}
360
361
362
3765
void SyncProcessRunner::Initialize(Local<Object> target,
363
                                   Local<Value> unused,
364
                                   Local<Context> context,
365
                                   void* priv) {
366
3765
  Environment* env = Environment::GetCurrent(context);
367
3765
  env->SetMethod(target, "spawn", Spawn);
368
3765
}
369
370
371
661
void SyncProcessRunner::Spawn(const FunctionCallbackInfo<Value>& args) {
372
661
  Environment* env = Environment::GetCurrent(args);
373
661
  env->PrintSyncTrace();
374
1322
  SyncProcessRunner p(env);
375
  Local<Value> result;
376
1322
  if (!p.Run(args[0]).ToLocal(&result)) return;
377
1322
  args.GetReturnValue().Set(result);
378
}
379
380
381
661
SyncProcessRunner::SyncProcessRunner(Environment* env)
382
    : max_buffer_(0),
383
      timeout_(0),
384
      kill_signal_(SIGTERM),
385
386
      uv_loop_(nullptr),
387
388
      stdio_count_(0),
389
      uv_stdio_containers_(nullptr),
390
      stdio_pipes_initialized_(false),
391
392
      uv_process_options_(),
393
      file_buffer_(nullptr),
394
      args_buffer_(nullptr),
395
      env_buffer_(nullptr),
396
      cwd_buffer_(nullptr),
397
398
      uv_process_(),
399
      killed_(false),
400
401
      buffered_output_size_(0),
402
      exit_status_(-1),
403
      term_signal_(-1),
404
405
      uv_timer_(),
406
      kill_timer_initialized_(false),
407
408
      error_(0),
409
      pipe_error_(0),
410
411
      lifecycle_(kUninitialized),
412
413
661
      env_(env) {
414
661
}
415
416
417
1322
SyncProcessRunner::~SyncProcessRunner() {
418
661
  CHECK_EQ(lifecycle_, kHandlesClosed);
419
420
661
  stdio_pipes_.clear();
421
661
  delete[] file_buffer_;
422
661
  delete[] args_buffer_;
423
661
  delete[] cwd_buffer_;
424
661
  delete[] env_buffer_;
425
661
  delete[] uv_stdio_containers_;
426
661
}
427
428
429
39447
Environment* SyncProcessRunner::env() const {
430
39447
  return env_;
431
}
432
433
661
MaybeLocal<Object> SyncProcessRunner::Run(Local<Value> options) {
434
661
  EscapableHandleScope scope(env()->isolate());
435
436
661
  CHECK_EQ(lifecycle_, kUninitialized);
437
438
661
  Maybe<bool> r = TryInitializeAndRunLoop(options);
439
661
  CloseHandlesAndDeleteLoop();
440
661
  if (r.IsNothing()) return MaybeLocal<Object>();
441
442
661
  Local<Object> result = BuildResultObject();
443
444
661
  return scope.Escape(result);
445
}
446
447
661
Maybe<bool> SyncProcessRunner::TryInitializeAndRunLoop(Local<Value> options) {
448
  int r;
449
450
  // There is no recovery from failure inside TryInitializeAndRunLoop - the
451
  // only option we'd have is to close all handles and destroy the loop.
452
661
  CHECK_EQ(lifecycle_, kUninitialized);
453
661
  lifecycle_ = kInitialized;
454
455
661
  uv_loop_ = new uv_loop_t;
456
661
  if (uv_loop_ == nullptr) {
457
    SetError(UV_ENOMEM);
458
    return Just(false);
459
  }
460
661
  CHECK_EQ(uv_loop_init(uv_loop_), 0);
461
462
1322
  if (!ParseOptions(options).To(&r)) return Nothing<bool>();
463
661
  if (r < 0) {
464
    SetError(r);
465
    return Just(false);
466
  }
467
468
661
  if (timeout_ > 0) {
469
7
    r = uv_timer_init(uv_loop_, &uv_timer_);
470
7
    if (r < 0) {
471
      SetError(r);
472
      return Just(false);
473
    }
474
475
7
    uv_unref(reinterpret_cast<uv_handle_t*>(&uv_timer_));
476
477
7
    uv_timer_.data = this;
478
7
    kill_timer_initialized_ = true;
479
480
    // Start the timer immediately. If uv_spawn fails then
481
    // CloseHandlesAndDeleteLoop() will immediately close the timer handle
482
    // which implicitly stops it, so there is no risk that the timeout callback
483
    // runs when the process didn't start.
484
7
    r = uv_timer_start(&uv_timer_, KillTimerCallback, timeout_, 0);
485
7
    if (r < 0) {
486
      SetError(r);
487
      return Just(false);
488
    }
489
  }
490
491
661
  uv_process_options_.exit_cb = ExitCallback;
492
661
  r = uv_spawn(uv_loop_, &uv_process_, &uv_process_options_);
493
661
  if (r < 0) {
494
145
    SetError(r);
495
145
    return Just(false);
496
  }
497
516
  uv_process_.data = this;
498
499
2064
  for (const auto& pipe : stdio_pipes_) {
500
1548
    if (pipe != nullptr) {
501
1469
      r = pipe->Start();
502
1469
      if (r < 0) {
503
        SetPipeError(r);
504
        return Just(false);
505
      }
506
    }
507
  }
508
509
516
  r = uv_run(uv_loop_, UV_RUN_DEFAULT);
510
516
  if (r < 0)
511
    // We can't handle uv_run failure.
512
    ABORT();
513
514
  // If we get here the process should have exited.
515
516
  CHECK_GE(exit_status_, 0);
516
516
  return Just(true);
517
}
518
519
520
661
void SyncProcessRunner::CloseHandlesAndDeleteLoop() {
521
661
  CHECK_LT(lifecycle_, kHandlesClosed);
522
523
661
  if (uv_loop_ != nullptr) {
524
661
    CloseStdioPipes();
525
661
    CloseKillTimer();
526
    // Close the process handle when ExitCallback was not called.
527
    uv_handle_t* uv_process_handle =
528
661
        reinterpret_cast<uv_handle_t*>(&uv_process_);
529
530
    // Close the process handle if it is still open. The handle type also
531
    // needs to be checked because TryInitializeAndRunLoop() won't spawn a
532
    // process if input validation fails.
533

1322
    if (uv_process_handle->type == UV_PROCESS &&
534
661
        !uv_is_closing(uv_process_handle))
535
145
      uv_close(uv_process_handle, nullptr);
536
537
    // Give closing watchers a chance to finish closing and get their close
538
    // callbacks called.
539
661
    int r = uv_run(uv_loop_, UV_RUN_DEFAULT);
540
661
    if (r < 0)
541
      ABORT();
542
543
661
    CheckedUvLoopClose(uv_loop_);
544
661
    delete uv_loop_;
545
661
    uv_loop_ = nullptr;
546
547
  } else {
548
    // If the loop doesn't exist, neither should any pipes or timers.
549
    CHECK_EQ(false, stdio_pipes_initialized_);
550
    CHECK_EQ(false, kill_timer_initialized_);
551
  }
552
553
661
  lifecycle_ = kHandlesClosed;
554
661
}
555
556
557
674
void SyncProcessRunner::CloseStdioPipes() {
558
674
  CHECK_LT(lifecycle_, kHandlesClosed);
559
560
674
  if (stdio_pipes_initialized_) {
561
661
    CHECK(!stdio_pipes_.empty());
562
661
    CHECK_NOT_NULL(uv_loop_);
563
564
2644
    for (const auto& pipe : stdio_pipes_) {
565
1983
      if (pipe)
566
1904
        pipe->Close();
567
    }
568
569
661
    stdio_pipes_initialized_ = false;
570
  }
571
674
}
572
573
574
674
void SyncProcessRunner::CloseKillTimer() {
575
674
  CHECK_LT(lifecycle_, kHandlesClosed);
576
577
674
  if (kill_timer_initialized_) {
578
7
    CHECK_GT(timeout_, 0);
579
7
    CHECK_NOT_NULL(uv_loop_);
580
581
7
    uv_handle_t* uv_timer_handle = reinterpret_cast<uv_handle_t*>(&uv_timer_);
582
7
    uv_ref(uv_timer_handle);
583
7
    uv_close(uv_timer_handle, KillTimerCloseCallback);
584
585
7
    kill_timer_initialized_ = false;
586
  }
587
674
}
588
589
590
13
void SyncProcessRunner::Kill() {
591
  // Only attempt to kill once.
592
13
  if (killed_)
593
    return;
594
13
  killed_ = true;
595
596
  // We might get here even if the process we spawned has already exited. This
597
  // could happen when our child process spawned another process which
598
  // inherited (one of) the stdio pipes. In this case we won't attempt to send
599
  // a signal to the process, however we will still close our end of the stdio
600
  // pipes so this situation won't make us hang.
601
13
  if (exit_status_ < 0) {
602
13
    int r = uv_process_kill(&uv_process_, kill_signal_);
603
604
    // If uv_kill failed with an error that isn't ESRCH, the user probably
605
    // specified an invalid or unsupported signal. Signal this to the user as
606
    // and error and kill the process with SIGKILL instead.
607

13
    if (r < 0 && r != UV_ESRCH) {
608
      SetError(r);
609
610
      // Deliberately ignore the return value, we might not have
611
      // sufficient privileges to signal the child process.
612
      USE(uv_process_kill(&uv_process_, SIGKILL));
613
    }
614
  }
615
616
  // Close all stdio pipes.
617
13
  CloseStdioPipes();
618
619
  // Stop the timeout timer immediately.
620
13
  CloseKillTimer();
621
}
622
623
624
17807
void SyncProcessRunner::IncrementBufferSizeAndCheckOverflow(ssize_t length) {
625
17807
  buffered_output_size_ += length;
626
627

17807
  if (max_buffer_ > 0 && buffered_output_size_ > max_buffer_) {
628
8
    SetError(UV_ENOBUFS);
629
8
    Kill();
630
  }
631
17807
}
632
633
634
516
void SyncProcessRunner::OnExit(int64_t exit_status, int term_signal) {
635
516
  if (exit_status < 0)
636
    return SetError(static_cast<int>(exit_status));
637
638
516
  exit_status_ = exit_status;
639
516
  term_signal_ = term_signal;
640
}
641
642
643
5
void SyncProcessRunner::OnKillTimerTimeout() {
644
5
  SetError(UV_ETIMEDOUT);
645
5
  Kill();
646
5
}
647
648
649
819
int SyncProcessRunner::GetError() {
650
819
  if (error_ != 0)
651
316
    return error_;
652
  else
653
503
    return pipe_error_;
654
}
655
656
657
158
void SyncProcessRunner::SetError(int error) {
658
158
  if (error_ == 0)
659
158
    error_ = error;
660
158
}
661
662
663
void SyncProcessRunner::SetPipeError(int pipe_error) {
664
  if (pipe_error_ == 0)
665
    pipe_error_ = pipe_error;
666
}
667
668
669
661
Local<Object> SyncProcessRunner::BuildResultObject() {
670
661
  EscapableHandleScope scope(env()->isolate());
671
661
  Local<Context> context = env()->context();
672
673
661
  Local<Object> js_result = Object::New(env()->isolate());
674
675
661
  if (GetError() != 0) {
676
316
    js_result->Set(context, env()->error_string(),
677
632
                   Integer::New(env()->isolate(), GetError())).Check();
678
  }
679
680
661
  if (exit_status_ >= 0) {
681
516
    if (term_signal_ > 0) {
682
60
      js_result->Set(context, env()->status_string(),
683
120
                     Null(env()->isolate())).Check();
684
    } else {
685
972
      js_result->Set(context, env()->status_string(),
686
                     Number::New(env()->isolate(),
687
1944
                                 static_cast<double>(exit_status_))).Check();
688
    }
689
  } else {
690
    // If exit_status_ < 0 the process was never started because of some error.
691
290
    js_result->Set(context, env()->status_string(),
692
580
                   Null(env()->isolate())).Check();
693
  }
694
695
661
  if (term_signal_ > 0)
696
60
    js_result->Set(context, env()->signal_string(),
697
60
                   String::NewFromUtf8(env()->isolate(),
698
                                       signo_string(term_signal_),
699
30
                                       v8::NewStringType::kNormal)
700
90
                       .ToLocalChecked())
701
        .Check();
702
  else
703
1262
    js_result->Set(context, env()->signal_string(),
704
2524
                   Null(env()->isolate())).Check();
705
706
661
  if (exit_status_ >= 0)
707
1032
    js_result->Set(context, env()->output_string(),
708
2064
                   BuildOutputArray()).Check();
709
  else
710
290
    js_result->Set(context, env()->output_string(),
711
580
                   Null(env()->isolate())).Check();
712
713
1322
  js_result->Set(context, env()->pid_string(),
714
2644
                 Number::New(env()->isolate(), uv_process_.pid)).Check();
715
716
661
  return scope.Escape(js_result);
717
}
718
719
720
516
Local<Array> SyncProcessRunner::BuildOutputArray() {
721
516
  CHECK_GE(lifecycle_, kInitialized);
722
516
  CHECK(!stdio_pipes_.empty());
723
724
516
  EscapableHandleScope scope(env()->isolate());
725
1032
  MaybeStackBuffer<Local<Value>, 8> js_output(stdio_pipes_.size());
726
727
2064
  for (uint32_t i = 0; i < stdio_pipes_.size(); i++) {
728
1548
    SyncProcessStdioPipe* h = stdio_pipes_[i].get();
729

1548
    if (h != nullptr && h->writable())
730
1972
      js_output[i] = h->GetOutputAsBuffer(env());
731
    else
732
1124
      js_output[i] = Null(env()->isolate());
733
  }
734
735
  return scope.Escape(
736
1032
      Array::New(env()->isolate(), js_output.out(), js_output.length()));
737
}
738
739
661
Maybe<int> SyncProcessRunner::ParseOptions(Local<Value> js_value) {
740
661
  Isolate* isolate = env()->isolate();
741
1322
  HandleScope scope(isolate);
742
  int r;
743
744
661
  if (!js_value->IsObject()) return Just<int>(UV_EINVAL);
745
746
661
  Local<Context> context = env()->context();
747
661
  Local<Object> js_options = js_value.As<Object>();
748
749
  Local<Value> js_file =
750
1983
      js_options->Get(context, env()->file_string()).ToLocalChecked();
751
1322
  if (!CopyJsString(js_file, &file_buffer_).To(&r)) return Nothing<int>();
752
661
  if (r < 0) return Just(r);
753
661
  uv_process_options_.file = file_buffer_;
754
755
  Local<Value> js_args =
756
1983
      js_options->Get(context, env()->args_string()).ToLocalChecked();
757
1322
  if (!CopyJsStringArray(js_args, &args_buffer_).To(&r)) return Nothing<int>();
758
661
  if (r < 0) return Just(r);
759
661
  uv_process_options_.args = reinterpret_cast<char**>(args_buffer_);
760
761
  Local<Value> js_cwd =
762
1983
      js_options->Get(context, env()->cwd_string()).ToLocalChecked();
763
661
  if (IsSet(js_cwd)) {
764
192
    if (!CopyJsString(js_cwd, &cwd_buffer_).To(&r)) return Nothing<int>();
765
96
    if (r < 0) return Just(r);
766
96
    uv_process_options_.cwd = cwd_buffer_;
767
  }
768
769
  Local<Value> js_env_pairs =
770
1983
      js_options->Get(context, env()->env_pairs_string()).ToLocalChecked();
771
661
  if (IsSet(js_env_pairs)) {
772
1322
    if (!CopyJsStringArray(js_env_pairs, &env_buffer_).To(&r))
773
      return Nothing<int>();
774
661
    if (r < 0) return Just(r);
775
776
661
    uv_process_options_.env = reinterpret_cast<char**>(env_buffer_);
777
  }
778
  Local<Value> js_uid =
779
1983
      js_options->Get(context, env()->uid_string()).ToLocalChecked();
780
661
  if (IsSet(js_uid)) {
781
1
    CHECK(js_uid->IsInt32());
782
2
    const int32_t uid = js_uid.As<Int32>()->Value();
783
1
    uv_process_options_.uid = static_cast<uv_uid_t>(uid);
784
1
    uv_process_options_.flags |= UV_PROCESS_SETUID;
785
  }
786
787
  Local<Value> js_gid =
788
1983
      js_options->Get(context, env()->gid_string()).ToLocalChecked();
789
661
  if (IsSet(js_gid)) {
790
1
    CHECK(js_gid->IsInt32());
791
2
    const int32_t gid = js_gid.As<Int32>()->Value();
792
1
    uv_process_options_.gid = static_cast<uv_gid_t>(gid);
793
1
    uv_process_options_.flags |= UV_PROCESS_SETGID;
794
  }
795
796
  Local<Value> js_detached =
797
1983
      js_options->Get(context, env()->detached_string()).ToLocalChecked();
798
661
  if (js_detached->BooleanValue(isolate))
799
1
    uv_process_options_.flags |= UV_PROCESS_DETACHED;
800
801
  Local<Value> js_win_hide =
802
1983
      js_options->Get(context, env()->windows_hide_string()).ToLocalChecked();
803
661
  if (js_win_hide->BooleanValue(isolate))
804
2
    uv_process_options_.flags |= UV_PROCESS_WINDOWS_HIDE;
805
806
  Local<Value> js_wva =
807
1983
      js_options->Get(context, env()->windows_verbatim_arguments_string())
808
661
          .ToLocalChecked();
809
810
661
  if (js_wva->BooleanValue(isolate))
811
1
    uv_process_options_.flags |= UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS;
812
813
  Local<Value> js_timeout =
814
1983
      js_options->Get(context, env()->timeout_string()).ToLocalChecked();
815
661
  if (IsSet(js_timeout)) {
816
8
    CHECK(js_timeout->IsNumber());
817
16
    int64_t timeout = js_timeout->IntegerValue(context).FromJust();
818
8
    timeout_ = static_cast<uint64_t>(timeout);
819
  }
820
821
  Local<Value> js_max_buffer =
822
1983
      js_options->Get(context, env()->max_buffer_string()).ToLocalChecked();
823
661
  if (IsSet(js_max_buffer)) {
824
659
    CHECK(js_max_buffer->IsNumber());
825
1318
    max_buffer_ = js_max_buffer->NumberValue(context).FromJust();
826
  }
827
828
  Local<Value> js_kill_signal =
829
1983
      js_options->Get(context, env()->kill_signal_string()).ToLocalChecked();
830
661
  if (IsSet(js_kill_signal)) {
831
105
    CHECK(js_kill_signal->IsInt32());
832
210
    kill_signal_ = js_kill_signal.As<Int32>()->Value();
833
  }
834
835
  Local<Value> js_stdio =
836
1983
      js_options->Get(context, env()->stdio_string()).ToLocalChecked();
837
661
  r = ParseStdioOptions(js_stdio);
838
661
  if (r < 0) return Just(r);
839
840
661
  return Just(0);
841
}
842
843
844
661
int SyncProcessRunner::ParseStdioOptions(Local<Value> js_value) {
845
1322
  HandleScope scope(env()->isolate());
846
  Local<Array> js_stdio_options;
847
848
661
  if (!js_value->IsArray())
849
    return UV_EINVAL;
850
851
661
  Local<Context> context = env()->context();
852
661
  js_stdio_options = js_value.As<Array>();
853
854
661
  stdio_count_ = js_stdio_options->Length();
855
661
  uv_stdio_containers_ = new uv_stdio_container_t[stdio_count_];
856
857
661
  stdio_pipes_.clear();
858
661
  stdio_pipes_.resize(stdio_count_);
859
661
  stdio_pipes_initialized_ = true;
860
861
2644
  for (uint32_t i = 0; i < stdio_count_; i++) {
862
    Local<Value> js_stdio_option =
863
3966
        js_stdio_options->Get(context, i).ToLocalChecked();
864
865
1983
    if (!js_stdio_option->IsObject())
866
      return UV_EINVAL;
867
868
1983
    int r = ParseStdioOption(i, js_stdio_option.As<Object>());
869
1983
    if (r < 0)
870
      return r;
871
  }
872
873
661
  uv_process_options_.stdio = uv_stdio_containers_;
874
661
  uv_process_options_.stdio_count = stdio_count_;
875
876
661
  return 0;
877
}
878
879
880
1983
int SyncProcessRunner::ParseStdioOption(int child_fd,
881
                                        Local<Object> js_stdio_option) {
882
1983
  Local<Context> context = env()->context();
883
  Local<Value> js_type =
884
5949
      js_stdio_option->Get(context, env()->type_string()).ToLocalChecked();
885
886
3966
  if (js_type->StrictEquals(env()->ignore_string())) {
887
3
    return AddStdioIgnore(child_fd);
888
889
3960
  } else if (js_type->StrictEquals(env()->pipe_string())) {
890
1904
    Isolate* isolate = env()->isolate();
891
1904
    Local<String> rs = env()->readable_string();
892
1904
    Local<String> ws = env()->writable_string();
893
894
3808
    bool readable = js_stdio_option->Get(context, rs)
895
3808
        .ToLocalChecked()->BooleanValue(isolate);
896
    bool writable =
897
3808
        js_stdio_option->Get(context, ws)
898
3808
        .ToLocalChecked()->BooleanValue(isolate);
899
900
1904
    uv_buf_t buf = uv_buf_init(nullptr, 0);
901
902
1904
    if (readable) {
903
      Local<Value> input =
904
1884
          js_stdio_option->Get(context, env()->input_string()).ToLocalChecked();
905
628
      if (Buffer::HasInstance(input)) {
906
        buf = uv_buf_init(Buffer::Data(input),
907
22
                          static_cast<unsigned int>(Buffer::Length(input)));
908

1212
      } else if (!input->IsUndefined() && !input->IsNull()) {
909
        // Strings, numbers etc. are currently unsupported. It's not possible
910
        // to create a buffer for them here because there is no way to free
911
        // them afterwards.
912
        return UV_EINVAL;
913
      }
914
    }
915
916
1904
    return AddStdioPipe(child_fd, readable, writable, buf);
917
918

261
  } else if (js_type->StrictEquals(env()->inherit_string()) ||
919
142
             js_type->StrictEquals(env()->fd_string())) {
920
228
    int inherit_fd = js_stdio_option->Get(context, env()->fd_string())
921
228
        .ToLocalChecked()->Int32Value(context).FromJust();
922
76
    return AddStdioInheritFD(child_fd, inherit_fd);
923
924
  } else {
925
    CHECK(0 && "invalid child stdio type");
926
    return UV_EINVAL;
927
  }
928
}
929
930
931
3
int SyncProcessRunner::AddStdioIgnore(uint32_t child_fd) {
932
3
  CHECK_LT(child_fd, stdio_count_);
933
3
  CHECK(!stdio_pipes_[child_fd]);
934
935
3
  uv_stdio_containers_[child_fd].flags = UV_IGNORE;
936
937
3
  return 0;
938
}
939
940
941
1904
int SyncProcessRunner::AddStdioPipe(uint32_t child_fd,
942
                                    bool readable,
943
                                    bool writable,
944
                                    uv_buf_t input_buffer) {
945
1904
  CHECK_LT(child_fd, stdio_count_);
946
1904
  CHECK(!stdio_pipes_[child_fd]);
947
948
  std::unique_ptr<SyncProcessStdioPipe> h(
949
3808
      new SyncProcessStdioPipe(this, readable, writable, input_buffer));
950
951
1904
  int r = h->Initialize(uv_loop_);
952
1904
  if (r < 0) {
953
    h.reset();
954
    return r;
955
  }
956
957
1904
  uv_stdio_containers_[child_fd].flags = h->uv_flags();
958
1904
  uv_stdio_containers_[child_fd].data.stream = h->uv_stream();
959
960
1904
  stdio_pipes_[child_fd] = std::move(h);
961
962
1904
  return 0;
963
}
964
965
966
76
int SyncProcessRunner::AddStdioInheritFD(uint32_t child_fd, int inherit_fd) {
967
76
  CHECK_LT(child_fd, stdio_count_);
968
76
  CHECK(!stdio_pipes_[child_fd]);
969
970
76
  uv_stdio_containers_[child_fd].flags = UV_INHERIT_FD;
971
76
  uv_stdio_containers_[child_fd].data.fd = inherit_fd;
972
973
76
  return 0;
974
}
975
976
977
4627
bool SyncProcessRunner::IsSet(Local<Value> value) {
978

12326
  return !value->IsUndefined() && !value->IsNull();
979
}
980
981
757
Maybe<int> SyncProcessRunner::CopyJsString(Local<Value> js_value,
982
                                           const char** target) {
983
757
  Isolate* isolate = env()->isolate();
984
  Local<String> js_string;
985
  size_t size, written;
986
  char* buffer;
987
988
1514
  if (js_value->IsString())
989
757
    js_string = js_value.As<String>();
990
  else if (!js_value->ToString(env()->isolate()->GetCurrentContext())
991
                .ToLocal(&js_string))
992
    return Nothing<int>();
993
994
  // Include space for null terminator byte.
995
1514
  if (!StringBytes::StorageSize(isolate, js_string, UTF8).To(&size))
996
    return Nothing<int>();
997
757
  size += 1;
998
999
757
  buffer = new char[size];
1000
1001
757
  written = StringBytes::Write(isolate, buffer, -1, js_string, UTF8);
1002
757
  buffer[written] = '\0';
1003
1004
757
  *target = buffer;
1005
757
  return Just(0);
1006
}
1007
1008
1322
Maybe<int> SyncProcessRunner::CopyJsStringArray(Local<Value> js_value,
1009
                                                char** target) {
1010
1322
  Isolate* isolate = env()->isolate();
1011
  Local<Array> js_array;
1012
  uint32_t length;
1013
  size_t list_size, data_size, data_offset;
1014
  char** list;
1015
  char* buffer;
1016
1017
1322
  if (!js_value->IsArray()) return Just<int>(UV_EINVAL);
1018
1019
1322
  Local<Context> context = env()->context();
1020
3966
  js_array = js_value.As<Array>()->Clone().As<Array>();
1021
1322
  length = js_array->Length();
1022
1322
  data_size = 0;
1023
1024
  // Index has a pointer to every string element, plus one more for a final
1025
  // null pointer.
1026
1322
  list_size = (length + 1) * sizeof *list;
1027
1028
  // Convert all array elements to string. Modify the js object itself if
1029
  // needed - it's okay since we cloned the original object. Also compute the
1030
  // length of all strings, including room for a null terminator after every
1031
  // string. Align strings to cache lines.
1032
48990
  for (uint32_t i = 0; i < length; i++) {
1033
95336
    auto value = js_array->Get(context, i).ToLocalChecked();
1034
1035
95336
    if (!value->IsString()) {
1036
      Local<String> string;
1037
129
      if (!value->ToString(env()->isolate()->GetCurrentContext())
1038
43
               .ToLocal(&string))
1039
        return Nothing<int>();
1040
      js_array
1041
86
          ->Set(context,
1042
                i,
1043
43
                string)
1044
          .Check();
1045
    }
1046
1047
47668
    Maybe<size_t> maybe_size = StringBytes::StorageSize(isolate, value, UTF8);
1048
47668
    if (maybe_size.IsNothing()) return Nothing<int>();
1049
47668
    data_size += maybe_size.FromJust() + 1;
1050
47668
    data_size = RoundUp(data_size, sizeof(void*));
1051
  }
1052
1053
1322
  buffer = new char[list_size + data_size];
1054
1055
1322
  list = reinterpret_cast<char**>(buffer);
1056
1322
  data_offset = list_size;
1057
1058
48990
  for (uint32_t i = 0; i < length; i++) {
1059
47668
    list[i] = buffer + data_offset;
1060
95336
    auto value = js_array->Get(context, i).ToLocalChecked();
1061
47668
    data_offset += StringBytes::Write(isolate,
1062
                                      buffer + data_offset,
1063
                                      -1,
1064
                                      value,
1065
                                      UTF8);
1066
47668
    buffer[data_offset++] = '\0';
1067
47668
    data_offset = RoundUp(data_offset, sizeof(void*));
1068
  }
1069
1070
1322
  list[length] = nullptr;
1071
1072
1322
  *target = buffer;
1073
1322
  return Just(0);
1074
}
1075
1076
1077
516
void SyncProcessRunner::ExitCallback(uv_process_t* handle,
1078
                                     int64_t exit_status,
1079
                                     int term_signal) {
1080
516
  SyncProcessRunner* self = reinterpret_cast<SyncProcessRunner*>(handle->data);
1081
516
  uv_close(reinterpret_cast<uv_handle_t*>(handle), nullptr);
1082
516
  self->OnExit(exit_status, term_signal);
1083
516
}
1084
1085
1086
5
void SyncProcessRunner::KillTimerCallback(uv_timer_t* handle) {
1087
5
  SyncProcessRunner* self = reinterpret_cast<SyncProcessRunner*>(handle->data);
1088
5
  self->OnKillTimerTimeout();
1089
5
}
1090
1091
1092
7
void SyncProcessRunner::KillTimerCloseCallback(uv_handle_t* handle) {
1093
  // No-op.
1094
7
}
1095
1096
}  // namespace node
1097
1098
4325
NODE_MODULE_CONTEXT_AWARE_INTERNAL(spawn_sync,
1099
  node::SyncProcessRunner::Initialize)