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: 420 457 91.9 %
Date: 2016-11-20 Branches: 198 348 56.9 %

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
273
void SyncProcessOutputBuffer::OnAlloc(size_t suggested_size,
34
                                      uv_buf_t* buf) const {
35
273
  if (used() == kBufferSize)
36
    *buf = uv_buf_init(nullptr, 0);
37
  else
38
273
    *buf = uv_buf_init(data_ + used(), available());
39
273
}
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
92
  CHECK_EQ(buf->base, data_ + used());
45
92
  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
363
  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
301
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
301
      lifecycle_(kUninitialized) {
92
301
  CHECK(readable || writable);
93
301
}
94
95
96
602
SyncProcessStdioPipe::~SyncProcessStdioPipe() {
97
301
  CHECK(lifecycle_ == kUninitialized || lifecycle_ == kClosed);
98
99
  SyncProcessOutputBuffer* buf;
100
  SyncProcessOutputBuffer* next;
101
102
487
  for (buf = first_output_buffer_; buf != nullptr; buf = next) {
103
186
    next = buf->next();
104
186
    delete buf;
105
  }
106
301
}
107
108
109
301
int SyncProcessStdioPipe::Initialize(uv_loop_t* loop) {
110
301
  CHECK_EQ(lifecycle_, kUninitialized);
111
112
301
  int r = uv_pipe_init(loop, uv_pipe(), 0);
113
301
  if (r < 0)
114
    return r;
115
116
301
  uv_pipe()->data = this;
117
118
301
  lifecycle_ = kInitialized;
119
301
  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
301
void SyncProcessStdioPipe::Close() {
159
301
  CHECK(lifecycle_ == kInitialized || lifecycle_ == kStarted);
160
161
301
  uv_close(uv_handle(), CloseCallback);
162
163
301
  lifecycle_ = kClosing;
164
301
}
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
301
  flags = UV_CREATE_PIPE;
189
301
  if (readable())
190
101
    flags |= UV_READABLE_PIPE;
191
301
  if (writable())
192
200
    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



1496
  CHECK_LT(lifecycle_, kClosing);
200
1197
  return &uv_pipe_;
201
}
202
203
204
uv_stream_t* SyncProcessStdioPipe::uv_stream() const {
205
595
  return reinterpret_cast<uv_stream_t*>(uv_pipe());
206
}
207
208
209
uv_handle_t* SyncProcessStdioPipe::uv_handle() const {
210
301
  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
273
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
273
  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
180
  } 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
273
  last_output_buffer_->OnAlloc(suggested_size, buf);
253
273
}
254
255
256
274
void SyncProcessStdioPipe::OnRead(const uv_buf_t* buf, ssize_t nread) {
257
274
  if (nread == UV_EOF) {
258
    // Libuv implicitly stops reading on EOF.
259
260
92
  } 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
184
    last_output_buffer_->OnRead(buf, nread);
267
92
    process_handler_->IncrementBufferSizeAndCheckOverflow(nread);
268
  }
269
274
}
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
301
  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
273
void SyncProcessStdioPipe::AllocCallback(uv_handle_t* handle,
296
                                         size_t suggested_size,
297
                                         uv_buf_t* buf) {
298
  SyncProcessStdioPipe* self =
299
273
      reinterpret_cast<SyncProcessStdioPipe*>(handle->data);
300
273
  self->OnAlloc(suggested_size, buf);
301
273
}
302
303
304
274
void SyncProcessStdioPipe::ReadCallback(uv_stream_t* stream,
305
                                        ssize_t nread,
306
                                        const uv_buf_t* buf) {
307
  SyncProcessStdioPipe* self =
308
274
        reinterpret_cast<SyncProcessStdioPipe*>(stream->data);
309
274
  self->OnRead(buf, nread);
310
274
}
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
301
void SyncProcessStdioPipe::CloseCallback(uv_handle_t* handle) {
336
  SyncProcessStdioPipe* self =
337
301
      reinterpret_cast<SyncProcessStdioPipe*>(handle->data);
338
301
  self->OnClose();
339
301
}
340
341
342
1559
void SyncProcessRunner::Initialize(Local<Object> target,
343
                                   Local<Value> unused,
344
                                   Local<Context> context) {
345
1559
  Environment* env = Environment::GetCurrent(context);
346
1559
  env->SetMethod(target, "spawn", Spawn);
347
1559
}
348
349
350
105
void SyncProcessRunner::Spawn(const FunctionCallbackInfo<Value>& args) {
351
105
  Environment* env = Environment::GetCurrent(args);
352
105
  env->PrintSyncTrace();
353
210
  SyncProcessRunner p(env);
354
210
  Local<Value> result = p.Run(args[0]);
355
210
  args.GetReturnValue().Set(result);
356
105
}
357
358
359
105
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
105
      env_(env) {
393
105
}
394
395
396
210
SyncProcessRunner::~SyncProcessRunner() {
397
105
  CHECK_EQ(lifecycle_, kHandlesClosed);
398
399
105
  if (stdio_pipes_ != nullptr) {
400
735
    for (size_t i = 0; i < stdio_count_; i++) {
401
315
      if (stdio_pipes_[i] != nullptr)
402
301
        delete stdio_pipes_[i];
403
    }
404
  }
405
406
105
  delete[] stdio_pipes_;
407
105
  delete[] file_buffer_;
408
105
  delete[] args_buffer_;
409
105
  delete[] cwd_buffer_;
410
105
  delete[] env_buffer_;
411
105
  delete[] uv_stdio_containers_;
412
105
}
413
414
415
Environment* SyncProcessRunner::env() const {
416
  return env_;
417
}
418
419
420
105
Local<Object> SyncProcessRunner::Run(Local<Value> options) {
421
210
  EscapableHandleScope scope(env()->isolate());
422
423
105
  CHECK_EQ(lifecycle_, kUninitialized);
424
425
105
  TryInitializeAndRunLoop(options);
426
105
  CloseHandlesAndDeleteLoop();
427
428
105
  Local<Object> result = BuildResultObject();
429
430
210
  return scope.Escape(result);
431
}
432
433
434
105
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
105
  CHECK_EQ(lifecycle_, kUninitialized);
440
105
  lifecycle_ = kInitialized;
441
442
105
  uv_loop_ = new uv_loop_t;
443
105
  if (uv_loop_ == nullptr)
444
    return SetError(UV_ENOMEM);
445
105
  CHECK_EQ(uv_loop_init(uv_loop_), 0);
446
447
105
  r = ParseOptions(options);
448
105
  if (r < 0)
449
    return SetError(r);
450
451
105
  if (timeout_ > 0) {
452
5
    r = uv_timer_init(uv_loop_, &uv_timer_);
453
5
    if (r < 0)
454
      return SetError(r);
455
456
5
    uv_unref(reinterpret_cast<uv_handle_t*>(&uv_timer_));
457
458
5
    uv_timer_.data = this;
459
5
    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
5
    r = uv_timer_start(&uv_timer_, KillTimerCallback, timeout_, 0);
466
5
    if (r < 0)
467
      return SetError(r);
468
  }
469
470
105
  uv_process_options_.exit_cb = ExitCallback;
471
105
  r = uv_spawn(uv_loop_, &uv_process_, &uv_process_options_);
472
105
  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
105
void SyncProcessRunner::CloseHandlesAndDeleteLoop() {
496
105
  CHECK_LT(lifecycle_, kHandlesClosed);
497
498
105
  if (uv_loop_ != nullptr) {
499
105
    CloseStdioPipes();
500
105
    CloseKillTimer();
501
    // Close the process handle when ExitCallback was not called.
502
    uv_handle_t* uv_process_handle =
503
105
        reinterpret_cast<uv_handle_t*>(&uv_process_);
504
105
    if (!uv_is_closing(uv_process_handle))
505
3
      uv_close(uv_process_handle, nullptr);
506
507
    // Give closing watchers a chance to finish closing and get their close
508
    // callbacks called.
509
105
    int r = uv_run(uv_loop_, UV_RUN_DEFAULT);
510
105
    if (r < 0)
511
      ABORT();
512
513
105
    CHECK_EQ(uv_loop_close(uv_loop_), 0);
514
105
    delete uv_loop_;
515
105
    uv_loop_ = nullptr;
516
517
  } else {
518
    // If the loop doesn't exist, neither should any pipes or timers.
519
    CHECK_EQ(false, stdio_pipes_initialized_);
520
    CHECK_EQ(false, kill_timer_initialized_);
521
  }
522
523
105
  lifecycle_ = kHandlesClosed;
524
105
}
525
526
527
111
void SyncProcessRunner::CloseStdioPipes() {
528
111
  CHECK_LT(lifecycle_, kHandlesClosed);
529
530
111
  if (stdio_pipes_initialized_) {
531
105
    CHECK_NE(stdio_pipes_, nullptr);
532
105
    CHECK_NE(uv_loop_, nullptr);
533
534
735
    for (uint32_t i = 0; i < stdio_count_; i++) {
535
315
      if (stdio_pipes_[i] != nullptr)
536
301
        stdio_pipes_[i]->Close();
537
    }
538
539
105
    stdio_pipes_initialized_ = false;
540
  }
541
111
}
542
543
544
111
void SyncProcessRunner::CloseKillTimer() {
545
111
  CHECK_LT(lifecycle_, kHandlesClosed);
546
547
111
  if (kill_timer_initialized_) {
548
5
    CHECK_GT(timeout_, 0);
549
5
    CHECK_NE(uv_loop_, nullptr);
550
551
5
    uv_handle_t* uv_timer_handle = reinterpret_cast<uv_handle_t*>(&uv_timer_);
552
5
    uv_ref(uv_timer_handle);
553
5
    uv_close(uv_timer_handle, KillTimerCloseCallback);
554
555
5
    kill_timer_initialized_ = false;
556
  }
557
111
}
558
559
560
6
void SyncProcessRunner::Kill() {
561
  // Only attempt to kill once.
562
6
  if (killed_)
563
    return;
564
6
  killed_ = true;
565
566
  // We might get here even if the process we spawned has already exited. This
567
  // could happen when our child process spawned another process which
568
  // inherited (one of) the stdio pipes. In this case we won't attempt to send
569
  // a signal to the process, however we will still close our end of the stdio
570
  // pipes so this situation won't make us hang.
571
6
  if (exit_status_ < 0) {
572
6
    int r = uv_process_kill(&uv_process_, kill_signal_);
573
574
    // If uv_kill failed with an error that isn't ESRCH, the user probably
575
    // specified an invalid or unsupported signal. Signal this to the user as
576
    // and error and kill the process with SIGKILL instead.
577
6
    if (r < 0 && r != UV_ESRCH) {
578
      SetError(r);
579
580
      r = uv_process_kill(&uv_process_, SIGKILL);
581
      CHECK(r >= 0 || r == UV_ESRCH);
582
    }
583
  }
584
585
  // Close all stdio pipes.
586
6
  CloseStdioPipes();
587
588
  // Stop the timeout timer immediately.
589
6
  CloseKillTimer();
590
}
591
592
593
92
void SyncProcessRunner::IncrementBufferSizeAndCheckOverflow(ssize_t length) {
594
92
  buffered_output_size_ += length;
595
596

92
  if (max_buffer_ > 0 && buffered_output_size_ > max_buffer_) {
597
1
    SetError(UV_ENOBUFS);
598
1
    Kill();
599
  }
600
92
}
601
602
603
void SyncProcessRunner::OnExit(int64_t exit_status, int term_signal) {
604

102
  if (exit_status < 0)
605
    return SetError(static_cast<int>(exit_status));
606
607
102
  exit_status_ = exit_status;
608
102
  term_signal_ = term_signal;
609
}
610
611
612
void SyncProcessRunner::OnKillTimerTimeout() {
613
5
  SetError(UV_ETIMEDOUT);
614
5
  Kill();
615
}
616
617
618
int SyncProcessRunner::GetError() {
619

114
  if (error_ != 0)
620
    return error_;
621
  else
622
96
    return pipe_error_;
623
}
624
625
626
void SyncProcessRunner::SetError(int error) {
627






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

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

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

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

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

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