GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/spawn_sync.cc Lines: 429 456 94.1 %
Date: 2017-01-02 Branches: 206 348 59.2 %

Line Branch Exec Source
1
#include "spawn_sync.h"
2
#include "env-inl.h"
3
#include "string_bytes.h"
4
#include "util.h"
5
6
#include <string.h>
7
#include <stdlib.h>
8
9
10
namespace node {
11
12
using v8::Array;
13
using v8::Context;
14
using v8::EscapableHandleScope;
15
using v8::FunctionCallbackInfo;
16
using v8::HandleScope;
17
using v8::Integer;
18
using v8::Isolate;
19
using v8::Local;
20
using v8::Null;
21
using v8::Number;
22
using v8::Object;
23
using v8::String;
24
using v8::Value;
25
26
27
SyncProcessOutputBuffer::SyncProcessOutputBuffer()
28
    : used_(0),
29
186
      next_(nullptr) {
30
}
31
32
33
270
void SyncProcessOutputBuffer::OnAlloc(size_t suggested_size,
34
                                      uv_buf_t* buf) const {
35
270
  if (used() == kBufferSize)
36
    *buf = uv_buf_init(nullptr, 0);
37
  else
38
270
    *buf = uv_buf_init(data_ + used(), available());
39
270
}
40
41
42
void SyncProcessOutputBuffer::OnRead(const uv_buf_t* buf, size_t nread) {
43
  // If we hand out the same chunk twice, this should catch it.
44
93
  CHECK_EQ(buf->base, data_ + used());
45
93
  used_ += static_cast<unsigned int>(nread);
46
}
47
48
49
size_t SyncProcessOutputBuffer::Copy(char* dest) const {
50
372
  memcpy(dest, data_, used());
51
186
  return used();
52
}
53
54
55
unsigned int SyncProcessOutputBuffer::available() const {
56
357
  return sizeof data_ - used();
57
}
58
59
60
unsigned int SyncProcessOutputBuffer::used() const {
61
  return used_;
62
}
63
64
65
SyncProcessOutputBuffer* SyncProcessOutputBuffer::next() const {
66
  return next_;
67
}
68
69
70
void SyncProcessOutputBuffer::set_next(SyncProcessOutputBuffer* next) {
71
3
  next_ = next;
72
}
73
74
75
406
SyncProcessStdioPipe::SyncProcessStdioPipe(SyncProcessRunner* process_handler,
76
                                           bool readable,
77
                                           bool writable,
78
                                           uv_buf_t input_buffer)
79
    : process_handler_(process_handler),
80
      readable_(readable),
81
      writable_(writable),
82
      input_buffer_(input_buffer),
83
84
      first_output_buffer_(nullptr),
85
      last_output_buffer_(nullptr),
86
87
      uv_pipe_(),
88
      write_req_(),
89
      shutdown_req_(),
90
91
406
      lifecycle_(kUninitialized) {
92
406
  CHECK(readable || writable);
93
406
}
94
95
96
812
SyncProcessStdioPipe::~SyncProcessStdioPipe() {
97
406
  CHECK(lifecycle_ == kUninitialized || lifecycle_ == kClosed);
98
99
  SyncProcessOutputBuffer* buf;
100
  SyncProcessOutputBuffer* next;
101
102
592
  for (buf = first_output_buffer_; buf != nullptr; buf = next) {
103
186
    next = buf->next();
104
186
    delete buf;
105
  }
106
406
}
107
108
109
406
int SyncProcessStdioPipe::Initialize(uv_loop_t* loop) {
110
406
  CHECK_EQ(lifecycle_, kUninitialized);
111
112
406
  int r = uv_pipe_init(loop, uv_pipe(), 0);
113
406
  if (r < 0)
114
    return r;
115
116
406
  uv_pipe()->data = this;
117
118
406
  lifecycle_ = kInitialized;
119
406
  return 0;
120
}
121
122
123
292
int SyncProcessStdioPipe::Start() {
124
292
  CHECK_EQ(lifecycle_, kInitialized);
125
126
  // Set the busy flag already. If this function fails no recovery is
127
  // possible.
128
292
  lifecycle_ = kStarted;
129
130
292
  if (readable()) {
131
98
    if (input_buffer_.len > 0) {
132
2
      CHECK_NE(input_buffer_.base, nullptr);
133
134
4
      int r = uv_write(&write_req_,
135
                       uv_stream(),
136
                       &input_buffer_,
137
                       1,
138
2
                       WriteCallback);
139
2
      if (r < 0)
140
        return r;
141
    }
142
143
98
    int r = uv_shutdown(&shutdown_req_, uv_stream(), ShutdownCallback);
144
98
    if (r < 0)
145
      return r;
146
  }
147
148
292
  if (writable()) {
149
194
    int r = uv_read_start(uv_stream(), AllocCallback, ReadCallback);
150
194
    if (r < 0)
151
      return r;
152
  }
153
154
  return 0;
155
}
156
157
158
406
void SyncProcessStdioPipe::Close() {
159
406
  CHECK(lifecycle_ == kInitialized || lifecycle_ == kStarted);
160
161
406
  uv_close(uv_handle(), CloseCallback);
162
163
406
  lifecycle_ = kClosing;
164
406
}
165
166
167
194
Local<Object> SyncProcessStdioPipe::GetOutputAsBuffer(Environment* env) const {
168
388
  size_t length = OutputLength();
169
388
  Local<Object> js_buffer = Buffer::New(env, length).ToLocalChecked();
170
194
  CopyOutput(Buffer::Data(js_buffer));
171
194
  return js_buffer;
172
}
173
174
175
bool SyncProcessStdioPipe::readable() const {
176
  return readable_;
177
}
178
179
180
bool SyncProcessStdioPipe::writable() const {
181
  return writable_;
182
}
183
184
185
uv_stdio_flags SyncProcessStdioPipe::uv_flags() const {
186
  unsigned int flags;
187
188
406
  flags = UV_CREATE_PIPE;
189
406
  if (readable())
190
136
    flags |= UV_READABLE_PIPE;
191
406
  if (writable())
192
270
    flags |= UV_WRITABLE_PIPE;
193
194
  return static_cast<uv_stdio_flags>(flags);
195
}
196
197
198
uv_pipe_t* SyncProcessStdioPipe::uv_pipe() const {
199



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

280
    if (uv_process_handle->type == UV_PROCESS &&
509
140
        !uv_is_closing(uv_process_handle))
510
38
      uv_close(uv_process_handle, nullptr);
511
512
    // Give closing watchers a chance to finish closing and get their close
513
    // callbacks called.
514
140
    int r = uv_run(uv_loop_, UV_RUN_DEFAULT);
515
140
    if (r < 0)
516
      ABORT();
517
518
140
    CHECK_EQ(uv_loop_close(uv_loop_), 0);
519
140
    delete uv_loop_;
520
140
    uv_loop_ = nullptr;
521
522
  } else {
523
    // If the loop doesn't exist, neither should any pipes or timers.
524
    CHECK_EQ(false, stdio_pipes_initialized_);
525
    CHECK_EQ(false, kill_timer_initialized_);
526
  }
527
528
140
  lifecycle_ = kHandlesClosed;
529
140
}
530
531
532
146
void SyncProcessRunner::CloseStdioPipes() {
533
146
  CHECK_LT(lifecycle_, kHandlesClosed);
534
535
146
  if (stdio_pipes_initialized_) {
536
140
    CHECK_NE(stdio_pipes_, nullptr);
537
140
    CHECK_NE(uv_loop_, nullptr);
538
539
980
    for (uint32_t i = 0; i < stdio_count_; i++) {
540
420
      if (stdio_pipes_[i] != nullptr)
541
406
        stdio_pipes_[i]->Close();
542
    }
543
544
140
    stdio_pipes_initialized_ = false;
545
  }
546
146
}
547
548
549
146
void SyncProcessRunner::CloseKillTimer() {
550
146
  CHECK_LT(lifecycle_, kHandlesClosed);
551
552
146
  if (kill_timer_initialized_) {
553
6
    CHECK_GT(timeout_, 0);
554
6
    CHECK_NE(uv_loop_, nullptr);
555
556
6
    uv_handle_t* uv_timer_handle = reinterpret_cast<uv_handle_t*>(&uv_timer_);
557
6
    uv_ref(uv_timer_handle);
558
6
    uv_close(uv_timer_handle, KillTimerCloseCallback);
559
560
6
    kill_timer_initialized_ = false;
561
  }
562
146
}
563
564
565
6
void SyncProcessRunner::Kill() {
566
  // Only attempt to kill once.
567
6
  if (killed_)
568
    return;
569
6
  killed_ = true;
570
571
  // We might get here even if the process we spawned has already exited. This
572
  // could happen when our child process spawned another process which
573
  // inherited (one of) the stdio pipes. In this case we won't attempt to send
574
  // a signal to the process, however we will still close our end of the stdio
575
  // pipes so this situation won't make us hang.
576
6
  if (exit_status_ < 0) {
577
6
    int r = uv_process_kill(&uv_process_, kill_signal_);
578
579
    // If uv_kill failed with an error that isn't ESRCH, the user probably
580
    // specified an invalid or unsupported signal. Signal this to the user as
581
    // and error and kill the process with SIGKILL instead.
582
6
    if (r < 0 && r != UV_ESRCH) {
583
      SetError(r);
584
585
      r = uv_process_kill(&uv_process_, SIGKILL);
586
      CHECK(r >= 0 || r == UV_ESRCH);
587
    }
588
  }
589
590
  // Close all stdio pipes.
591
6
  CloseStdioPipes();
592
593
  // Stop the timeout timer immediately.
594
6
  CloseKillTimer();
595
}
596
597
598
93
void SyncProcessRunner::IncrementBufferSizeAndCheckOverflow(ssize_t length) {
599
93
  buffered_output_size_ += length;
600
601

93
  if (max_buffer_ > 0 && buffered_output_size_ > max_buffer_) {
602
1
    SetError(UV_ENOBUFS);
603
1
    Kill();
604
  }
605
93
}
606
607
608
void SyncProcessRunner::OnExit(int64_t exit_status, int term_signal) {
609

102
  if (exit_status < 0)
610
    return SetError(static_cast<int>(exit_status));
611
612
102
  exit_status_ = exit_status;
613
102
  term_signal_ = term_signal;
614
}
615
616
617
void SyncProcessRunner::OnKillTimerTimeout() {
618
5
  SetError(UV_ETIMEDOUT);
619
5
  Kill();
620
}
621
622
623
int SyncProcessRunner::GetError() {
624

184
  if (error_ != 0)
625
    return error_;
626
  else
627
96
    return pipe_error_;
628
}
629
630
631
void SyncProcessRunner::SetError(int error) {
632






44
  if (error_ == 0)
633
44
    error_ = error;
634
}
635
636
637
void SyncProcessRunner::SetPipeError(int pipe_error) {
638
  if (pipe_error_ == 0)
639
    pipe_error_ = pipe_error;
640
}
641
642
643
140
Local<Object> SyncProcessRunner::BuildResultObject() {
644
280
  EscapableHandleScope scope(env()->isolate());
645
646
140
  Local<Object> js_result = Object::New(env()->isolate());
647
648
140
  if (GetError() != 0) {
649
220
    js_result->Set(env()->error_string(),
650
44
                   Integer::New(env()->isolate(), GetError()));
651
  }
652
653
140
  if (exit_status_ >= 0)
654
510
    js_result->Set(env()->status_string(),
655
102
        Number::New(env()->isolate(), static_cast<double>(exit_status_)));
656
  else
657
    // If exit_status_ < 0 the process was never started because of some error.
658
190
    js_result->Set(env()->status_string(), Null(env()->isolate()));
659
660
140
  if (term_signal_ > 0)
661
30
    js_result->Set(env()->signal_string(),
662
6
        String::NewFromUtf8(env()->isolate(), signo_string(term_signal_)));
663
  else
664
670
    js_result->Set(env()->signal_string(), Null(env()->isolate()));
665
666
140
  if (exit_status_ >= 0)
667
408
    js_result->Set(env()->output_string(), BuildOutputArray());
668
  else
669
190
    js_result->Set(env()->output_string(), Null(env()->isolate()));
670
671
700
  js_result->Set(env()->pid_string(),
672
280
                 Number::New(env()->isolate(), uv_process_.pid));
673
674
280
  return scope.Escape(js_result);
675
}
676
677
678
102
Local<Array> SyncProcessRunner::BuildOutputArray() {
679
102
  CHECK_GE(lifecycle_, kInitialized);
680
102
  CHECK_NE(stdio_pipes_, nullptr);
681
682
204
  EscapableHandleScope scope(env()->isolate());
683
102
  Local<Array> js_output = Array::New(env()->isolate(), stdio_count_);
684
685
408
  for (uint32_t i = 0; i < stdio_count_; i++) {
686
306
    SyncProcessStdioPipe* h = stdio_pipes_[i];
687

306
    if (h != nullptr && h->writable())
688
388
      js_output->Set(i, h->GetOutputAsBuffer(env()));
689
    else
690
336
      js_output->Set(i, Null(env()->isolate()));
691
  }
692
693
204
  return scope.Escape(js_output);
694
}
695
696
697
140
int SyncProcessRunner::ParseOptions(Local<Value> js_value) {
698
280
  HandleScope scope(env()->isolate());
699
  int r;
700
701
140
  if (!js_value->IsObject())
702
    return UV_EINVAL;
703
704
140
  Local<Object> js_options = js_value.As<Object>();
705
706
420
  Local<Value> js_file = js_options->Get(env()->file_string());
707
140
  r = CopyJsString(js_file, &file_buffer_);
708
140
  if (r < 0)
709
    return r;
710
140
  uv_process_options_.file = file_buffer_;
711
712
420
  Local<Value> js_args = js_options->Get(env()->args_string());
713
140
  r = CopyJsStringArray(js_args, &args_buffer_);
714
140
  if (r < 0)
715
    return r;
716
140
  uv_process_options_.args = reinterpret_cast<char**>(args_buffer_);
717
718
719
420
  Local<Value> js_cwd = js_options->Get(env()->cwd_string());
720
140
  if (IsSet(js_cwd)) {
721
20
    r = CopyJsString(js_cwd, &cwd_buffer_);
722
20
    if (r < 0)
723
      return r;
724
20
    uv_process_options_.cwd = cwd_buffer_;
725
  }
726
727
420
  Local<Value> js_env_pairs = js_options->Get(env()->env_pairs_string());
728
140
  if (IsSet(js_env_pairs)) {
729
140
    r = CopyJsStringArray(js_env_pairs, &env_buffer_);
730
140
    if (r < 0)
731
      return r;
732
733
140
    uv_process_options_.env = reinterpret_cast<char**>(env_buffer_);
734
  }
735
420
  Local<Value> js_uid = js_options->Get(env()->uid_string());
736
140
  if (IsSet(js_uid)) {
737
1
    CHECK(js_uid->IsInt32());
738
3
    const int32_t uid = js_uid->Int32Value(env()->context()).FromJust();
739
1
    uv_process_options_.uid = static_cast<uv_uid_t>(uid);
740
1
    uv_process_options_.flags |= UV_PROCESS_SETUID;
741
  }
742
743
420
  Local<Value> js_gid = js_options->Get(env()->gid_string());
744
140
  if (IsSet(js_gid)) {
745
1
    CHECK(js_gid->IsInt32());
746
3
    const int32_t gid = js_gid->Int32Value(env()->context()).FromJust();
747
1
    uv_process_options_.gid = static_cast<uv_gid_t>(gid);
748
1
    uv_process_options_.flags |= UV_PROCESS_SETGID;
749
  }
750
751
560
  if (js_options->Get(env()->detached_string())->BooleanValue())
752
1
    uv_process_options_.flags |= UV_PROCESS_DETACHED;
753
754
280
  Local<String> wba = env()->windows_verbatim_arguments_string();
755
756
280
  if (js_options->Get(wba)->BooleanValue())
757
1
    uv_process_options_.flags |= UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS;
758
759
420
  Local<Value> js_timeout = js_options->Get(env()->timeout_string());
760
140
  if (IsSet(js_timeout)) {
761
7
    CHECK(js_timeout->IsNumber());
762
7
    int64_t timeout = js_timeout->IntegerValue();
763
7
    timeout_ = static_cast<uint64_t>(timeout);
764
  }
765
766
420
  Local<Value> js_max_buffer = js_options->Get(env()->max_buffer_string());
767
140
  if (IsSet(js_max_buffer)) {
768
3
    CHECK(js_max_buffer->IsUint32());
769
3
    max_buffer_ = js_max_buffer->Uint32Value();
770
  }
771
772
420
  Local<Value> js_kill_signal = js_options->Get(env()->kill_signal_string());
773
140
  if (IsSet(js_kill_signal)) {
774
4
    CHECK(js_kill_signal->IsInt32());
775
4
    kill_signal_ = js_kill_signal->Int32Value();
776
  }
777
778
420
  Local<Value> js_stdio = js_options->Get(env()->stdio_string());
779
140
  r = ParseStdioOptions(js_stdio);
780
140
  if (r < 0)
781
    return r;
782
783
  return 0;
784
}
785
786
787
140
int SyncProcessRunner::ParseStdioOptions(Local<Value> js_value) {
788
280
  HandleScope scope(env()->isolate());
789
140
  Local<Array> js_stdio_options;
790
791
140
  if (!js_value->IsArray())
792
    return UV_EINVAL;
793
794
140
  js_stdio_options = js_value.As<Array>();
795
796
140
  stdio_count_ = js_stdio_options->Length();
797
140
  uv_stdio_containers_ = new uv_stdio_container_t[stdio_count_];
798
799

140
  stdio_pipes_ = new SyncProcessStdioPipe*[stdio_count_]();
800
140
  stdio_pipes_initialized_ = true;
801
802
560
  for (uint32_t i = 0; i < stdio_count_; i++) {
803
420
    Local<Value> js_stdio_option = js_stdio_options->Get(i);
804
805
420
    if (!js_stdio_option->IsObject())
806
      return UV_EINVAL;
807
808
420
    int r = ParseStdioOption(i, js_stdio_option.As<Object>());
809
420
    if (r < 0)
810
      return r;
811
  }
812
813
140
  uv_process_options_.stdio = uv_stdio_containers_;
814
140
  uv_process_options_.stdio_count = stdio_count_;
815
816
140
  return 0;
817
}
818
819
820
420
int SyncProcessRunner::ParseStdioOption(int child_fd,
821
                                        Local<Object> js_stdio_option) {
822
1260
  Local<Value> js_type = js_stdio_option->Get(env()->type_string());
823
824
1260
  if (js_type->StrictEquals(env()->ignore_string())) {
825
6
    return AddStdioIgnore(child_fd);
826
827
1242
  } else if (js_type->StrictEquals(env()->pipe_string())) {
828
812
    Local<String> rs = env()->readable_string();
829
812
    Local<String> ws = env()->writable_string();
830
831
812
    bool readable = js_stdio_option->Get(rs)->BooleanValue();
832
812
    bool writable = js_stdio_option->Get(ws)->BooleanValue();
833
834
406
    uv_buf_t buf = uv_buf_init(nullptr, 0);
835
836
406
    if (readable) {
837
408
      Local<Value> input = js_stdio_option->Get(env()->input_string());
838
136
      if (Buffer::HasInstance(input)) {
839
        buf = uv_buf_init(Buffer::Data(input),
840
2
                          static_cast<unsigned int>(Buffer::Length(input)));
841

268
      } else if (!input->IsUndefined() && !input->IsNull()) {
842
        // Strings, numbers etc. are currently unsupported. It's not possible
843
        // to create a buffer for them here because there is no way to free
844
        // them afterwards.
845
        return UV_EINVAL;
846
      }
847
    }
848
849
406
    return AddStdioPipe(child_fd, readable, writable, buf);
850
851

34
  } else if (js_type->StrictEquals(env()->inherit_string()) ||
852
20
             js_type->StrictEquals(env()->fd_string())) {
853
32
    int inherit_fd = js_stdio_option->Get(env()->fd_string())->Int32Value();
854
8
    return AddStdioInheritFD(child_fd, inherit_fd);
855
856
  } else {
857
    CHECK(0 && "invalid child stdio type");
858
    return UV_EINVAL;
859
  }
860
}
861
862
863
6
int SyncProcessRunner::AddStdioIgnore(uint32_t child_fd) {
864
6
  CHECK_LT(child_fd, stdio_count_);
865
6
  CHECK_EQ(stdio_pipes_[child_fd], nullptr);
866
867
6
  uv_stdio_containers_[child_fd].flags = UV_IGNORE;
868
869
6
  return 0;
870
}
871
872
873
406
int SyncProcessRunner::AddStdioPipe(uint32_t child_fd,
874
                                    bool readable,
875
                                    bool writable,
876
                                    uv_buf_t input_buffer) {
877
406
  CHECK_LT(child_fd, stdio_count_);
878
406
  CHECK_EQ(stdio_pipes_[child_fd], nullptr);
879
880
  SyncProcessStdioPipe* h = new SyncProcessStdioPipe(this,
881
                                                     readable,
882
                                                     writable,
883
406
                                                     input_buffer);
884
885
406
  int r = h->Initialize(uv_loop_);
886
406
  if (r < 0) {
887
    delete h;
888
    return r;
889
  }
890
891
406
  stdio_pipes_[child_fd] = h;
892
893
812
  uv_stdio_containers_[child_fd].flags = h->uv_flags();
894
812
  uv_stdio_containers_[child_fd].data.stream = h->uv_stream();
895
896
406
  return 0;
897
}
898
899
900
8
int SyncProcessRunner::AddStdioInheritFD(uint32_t child_fd, int inherit_fd) {
901
8
  CHECK_LT(child_fd, stdio_count_);
902
8
  CHECK_EQ(stdio_pipes_[child_fd], nullptr);
903
904
8
  uv_stdio_containers_[child_fd].flags = UV_INHERIT_FD;
905
8
  uv_stdio_containers_[child_fd].data.fd = inherit_fd;
906
907
8
  return 0;
908
}
909
910
911
980
bool SyncProcessRunner::IsSet(Local<Value> value) {
912

2142
  return !value->IsUndefined() && !value->IsNull();
913
}
914
915
916
160
int SyncProcessRunner::CopyJsString(Local<Value> js_value,
917
                                    const char** target) {
918
160
  Isolate* isolate = env()->isolate();
919
160
  Local<String> js_string;
920
  size_t size, written;
921
  char* buffer;
922
923
320
  if (js_value->IsString())
924
    js_string = js_value.As<String>();
925
  else
926
    js_string = js_value->ToString(env()->isolate());
927
928
  // Include space for null terminator byte.
929
160
  size = StringBytes::StorageSize(isolate, js_string, UTF8) + 1;
930
931
160
  buffer = new char[size];
932
933
160
  written = StringBytes::Write(isolate, buffer, -1, js_string, UTF8);
934
160
  buffer[written] = '\0';
935
936
160
  *target = buffer;
937
160
  return 0;
938
}
939
940
941
280
int SyncProcessRunner::CopyJsStringArray(Local<Value> js_value,
942
                                         char** target) {
943
280
  Isolate* isolate = env()->isolate();
944
280
  Local<Array> js_array;
945
  uint32_t length;
946
  size_t list_size, data_size, data_offset;
947
  char** list;
948
  char* buffer;
949
950
280
  if (!js_value->IsArray())
951
    return UV_EINVAL;
952
953
560
  js_array = js_value.As<Array>()->Clone().As<Array>();
954
280
  length = js_array->Length();
955
956
  // Convert all array elements to string. Modify the js object itself if
957
  // needed - it's okay since we cloned the original object.
958
2586
  for (uint32_t i = 0; i < length; i++) {
959
6918
    if (!js_array->Get(i)->IsString())
960
6
      js_array->Set(i, js_array->Get(i)->ToString(env()->isolate()));
961
  }
962
963
  // Index has a pointer to every string element, plus one more for a final
964
  // null pointer.
965
280
  list_size = (length + 1) * sizeof *list;
966
967
  // Compute the length of all strings. Include room for null terminator
968
  // after every string. Align strings to cache lines.
969
280
  data_size = 0;
970
2586
  for (uint32_t i = 0; i < length; i++) {
971
2306
    data_size += StringBytes::StorageSize(isolate, js_array->Get(i), UTF8) + 1;
972
2306
    data_size = ROUND_UP(data_size, sizeof(void*));
973
  }
974
975
280
  buffer = new char[list_size + data_size];
976
977
280
  list = reinterpret_cast<char**>(buffer);
978
280
  data_offset = list_size;
979
980
2586
  for (uint32_t i = 0; i < length; i++) {
981
2306
    list[i] = buffer + data_offset;
982
2306
    data_offset += StringBytes::Write(isolate,
983
                                      buffer + data_offset,
984
                                      -1,
985
2306
                                      js_array->Get(i),
986
2306
                                      UTF8);
987
2306
    buffer[data_offset++] = '\0';
988
2306
    data_offset = ROUND_UP(data_offset, sizeof(void*));
989
  }
990
991
280
  list[length] = nullptr;
992
993
280
  *target = buffer;
994
280
  return 0;
995
}
996
997
998
102
void SyncProcessRunner::ExitCallback(uv_process_t* handle,
999
                                     int64_t exit_status,
1000
                                     int term_signal) {
1001
102
  SyncProcessRunner* self = reinterpret_cast<SyncProcessRunner*>(handle->data);
1002
102
  uv_close(reinterpret_cast<uv_handle_t*>(handle), nullptr);
1003
102
  self->OnExit(exit_status, term_signal);
1004
102
}
1005
1006
1007
5
void SyncProcessRunner::KillTimerCallback(uv_timer_t* handle) {
1008
5
  SyncProcessRunner* self = reinterpret_cast<SyncProcessRunner*>(handle->data);
1009
5
  self->OnKillTimerTimeout();
1010
5
}
1011
1012
1013
6
void SyncProcessRunner::KillTimerCloseCallback(uv_handle_t* handle) {
1014
  // No-op.
1015
6
}
1016
1017
}  // namespace node
1018
1019
1757
NODE_MODULE_CONTEXT_AWARE_BUILTIN(spawn_sync,
1020
  node::SyncProcessRunner::Initialize)