v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
d8-posix.cc
Go to the documentation of this file.
1// Copyright 2009 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <errno.h>
6#include <fcntl.h>
7
8#include "src/d8/d8.h"
9
10#ifndef V8_OS_ZOS
11#include <netinet/ip.h>
12#endif
13#include <signal.h>
14#include <stdlib.h>
15#include <string.h>
16#include <sys/select.h>
17#include <sys/socket.h>
18#include <sys/stat.h>
19#include <sys/time.h>
20#include <sys/types.h>
21#include <sys/wait.h>
22#include <unistd.h>
23
25#include "include/v8-template.h"
26
27namespace v8 {
28
29// If the buffer ends in the middle of a UTF-8 sequence then we return
30// the length of the string up to but not including the incomplete UTF-8
31// sequence. If the buffer ends with a valid UTF-8 sequence then we
32// return the whole buffer.
33static int LengthWithoutIncompleteUtf8(char* buffer, int len) {
34 int answer = len;
35 // 1-byte encoding.
36 static const int kUtf8SingleByteMask = 0x80;
37 static const int kUtf8SingleByteValue = 0x00;
38 // 2-byte encoding.
39 static const int kUtf8TwoByteMask = 0xE0;
40 static const int kUtf8TwoByteValue = 0xC0;
41 // 3-byte encoding.
42 static const int kUtf8ThreeByteMask = 0xF0;
43 static const int kUtf8ThreeByteValue = 0xE0;
44 // 4-byte encoding.
45 static const int kUtf8FourByteMask = 0xF8;
46 static const int kUtf8FourByteValue = 0xF0;
47 // Subsequent bytes of a multi-byte encoding.
48 static const int kMultiByteMask = 0xC0;
49 static const int kMultiByteValue = 0x80;
50 int multi_byte_bytes_seen = 0;
51 while (answer > 0) {
52 int c = buffer[answer - 1];
53 // Ends in valid single-byte sequence?
54 if ((c & kUtf8SingleByteMask) == kUtf8SingleByteValue) return answer;
55 // Ends in one or more subsequent bytes of a multi-byte value?
56 if ((c & kMultiByteMask) == kMultiByteValue) {
57 multi_byte_bytes_seen++;
58 answer--;
59 } else {
60 if ((c & kUtf8TwoByteMask) == kUtf8TwoByteValue) {
61 if (multi_byte_bytes_seen >= 1) {
62 return answer + 2;
63 }
64 return answer - 1;
65 } else if ((c & kUtf8ThreeByteMask) == kUtf8ThreeByteValue) {
66 if (multi_byte_bytes_seen >= 2) {
67 return answer + 3;
68 }
69 return answer - 1;
70 } else if ((c & kUtf8FourByteMask) == kUtf8FourByteValue) {
71 if (multi_byte_bytes_seen >= 3) {
72 return answer + 4;
73 }
74 return answer - 1;
75 } else {
76 return answer; // Malformed UTF-8.
77 }
78 }
79 }
80 return 0;
81}
82
83// Suspends the thread until there is data available from the child process.
84// Returns false on timeout, true on data ready.
85static bool WaitOnFD(int fd, int read_timeout, int total_timeout,
86 const struct timeval& start_time) {
87 fd_set readfds, writefds, exceptfds;
88 struct timeval timeout;
89 int gone = 0;
90 if (total_timeout != -1) {
91 struct timeval time_now;
92 gettimeofday(&time_now, nullptr);
93 time_t seconds = time_now.tv_sec - start_time.tv_sec;
94 gone = static_cast<int>(seconds * 1000 +
95 (time_now.tv_usec - start_time.tv_usec) / 1000);
96 if (gone >= total_timeout) return false;
97 }
98 FD_ZERO(&readfds);
99 FD_ZERO(&writefds);
100 FD_ZERO(&exceptfds);
101 FD_SET(fd, &readfds);
102 FD_SET(fd, &exceptfds);
103 if (read_timeout == -1 ||
104 (total_timeout != -1 && total_timeout - gone < read_timeout)) {
105 read_timeout = total_timeout - gone;
106 }
107 timeout.tv_usec = (read_timeout % 1000) * 1000;
108 timeout.tv_sec = read_timeout / 1000;
109 int number_of_fds_ready = select(fd + 1, &readfds, &writefds, &exceptfds,
110 read_timeout != -1 ? &timeout : nullptr);
111 return number_of_fds_ready == 1;
112}
113
114// Checks whether we ran out of time on the timeout. Returns true if we ran out
115// of time, false if we still have time.
116static bool TimeIsOut(const struct timeval& start_time, const int& total_time) {
117 if (total_time == -1) return false;
118 struct timeval time_now;
119 gettimeofday(&time_now, nullptr);
120 // Careful about overflow.
121 int seconds = static_cast<int>(time_now.tv_sec - start_time.tv_sec);
122 if (seconds > 100) {
123 if (seconds * 1000 > total_time) return true;
124 return false;
125 }
126 int useconds = static_cast<int>(time_now.tv_usec - start_time.tv_usec);
127 if (seconds * 1000000 + useconds > total_time * 1000) {
128 return true;
129 }
130 return false;
131}
132
133// A utility class that does a non-hanging waitpid on the child process if we
134// bail out of the System() function early. If you don't ever do a waitpid on
135// a subprocess then it turns into one of those annoying 'zombie processes'.
137 public:
138 explicit ZombieProtector(int pid) : pid_(pid) {}
140 if (pid_ != 0) waitpid(pid_, nullptr, 0);
141 }
142 void ChildIsDeadNow() { pid_ = 0; }
143
144 private:
145 int pid_;
146};
147
148// A utility class that closes a file descriptor when it goes out of scope.
150 public:
151 explicit OpenFDCloser(int fd) : fd_(fd) {}
152 ~OpenFDCloser() { close(fd_); }
153
154 private:
155 int fd_;
156};
157
158// A utility class that takes the array of command arguments and puts then in an
159// array of new[]ed UTF-8 C strings. Deallocates them again when it goes out of
160// scope.
161class ExecArgs {
162 public:
163 ExecArgs() { exec_args_[0] = nullptr; }
164 bool Init(Isolate* isolate, Local<Value> arg0, Local<Array> command_args) {
165 String::Utf8Value prog(isolate, arg0);
166 if (*prog == nullptr) {
167 isolate->ThrowError(
168 "os.system(): String conversion of program name failed");
169 return false;
170 }
171 {
172 size_t len = prog.length() + 3;
173 char* c_arg = new char[len];
174 snprintf(c_arg, len, "%s", *prog);
175 exec_args_[0] = c_arg;
176 }
177 int i = 1;
178 for (unsigned j = 0; j < command_args->Length(); i++, j++) {
179 Local<Value> arg(
180 command_args
181 ->Get(isolate->GetCurrentContext(), Integer::New(isolate, j))
182 .ToLocalChecked());
183 String::Utf8Value utf8_arg(isolate, arg);
184 if (*utf8_arg == nullptr) {
185 exec_args_[i] = nullptr; // Consistent state for destructor.
186 isolate->ThrowError(
187 "os.system(): String conversion of argument failed.");
188 return false;
189 }
190 size_t len = utf8_arg.length() + 1;
191 char* c_arg = new char[len];
192 snprintf(c_arg, len, "%s", *utf8_arg);
193 exec_args_[i] = c_arg;
194 }
195 exec_args_[i] = nullptr;
196 return true;
197 }
199 for (unsigned i = 0; i < kMaxArgs; i++) {
200 if (exec_args_[i] == nullptr) {
201 return;
202 }
203 delete[] exec_args_[i];
204 exec_args_[i] = nullptr;
205 }
206 }
207 static const unsigned kMaxArgs = 1000;
208 char* const* arg_array() const { return exec_args_; }
209 const char* arg0() const { return exec_args_[0]; }
210
211 private:
213};
214
215// Gets the optional timeouts from the arguments to the system() call.
217 int* read_timeout, int* total_timeout) {
218 if (info.Length() > 3) {
219 if (info[3]->IsNumber()) {
220 *total_timeout = info[3]
221 ->Int32Value(info.GetIsolate()->GetCurrentContext())
222 .FromJust();
223 } else {
224 info.GetIsolate()->ThrowError("system: Argument 4 must be a number");
225 return false;
226 }
227 }
228 if (info.Length() > 2) {
229 if (info[2]->IsNumber()) {
230 *read_timeout = info[2]
231 ->Int32Value(info.GetIsolate()->GetCurrentContext())
232 .FromJust();
233 } else {
234 info.GetIsolate()->ThrowError("system: Argument 3 must be a number");
235 return false;
236 }
237 }
238 return true;
239}
240
241namespace {
242v8::Local<v8::String> v8_strerror(v8::Isolate* isolate, int err) {
243 return v8::String::NewFromUtf8(isolate, strerror(err)).ToLocalChecked();
244}
245} // namespace
246
247static const int kReadFD = 0;
248static const int kWriteFD = 1;
249
250// This is run in the child process after fork() but before exec(). It normally
251// ends with the child process being replaced with the desired child program.
252// It only returns if an error occurred.
253static void ExecSubprocess(int* exec_error_fds, int* stdout_fds,
254 const ExecArgs& exec_args) {
255 close(exec_error_fds[kReadFD]); // Don't need this in the child.
256 close(stdout_fds[kReadFD]); // Don't need this in the child.
257 close(1); // Close stdout.
258 dup2(stdout_fds[kWriteFD], 1); // Dup pipe fd to stdout.
259 close(stdout_fds[kWriteFD]); // Don't need the original fd now.
260 fcntl(exec_error_fds[kWriteFD], F_SETFD, FD_CLOEXEC);
261 execvp(exec_args.arg0(), exec_args.arg_array());
262 // Only get here if the exec failed. Write errno to the parent to tell
263 // them it went wrong. If it went well the pipe is closed.
264 int err = errno;
265 ssize_t bytes_written;
266 do {
267 bytes_written = write(exec_error_fds[kWriteFD], &err, sizeof(err));
268 } while (bytes_written == -1 && errno == EINTR);
269 // Return (and exit child process).
270}
271
272// Runs in the parent process. Checks that the child was able to exec (closing
273// the file desriptor), or reports an error if it failed.
274static bool ChildLaunchedOK(Isolate* isolate, int* exec_error_fds) {
275 ssize_t bytes_read;
276 int err;
277 do {
278 bytes_read = read(exec_error_fds[kReadFD], &err, sizeof(err));
279 } while (bytes_read == -1 && errno == EINTR);
280 if (bytes_read != 0) {
281 isolate->ThrowError(v8_strerror(isolate, err));
282 return false;
283 }
284 return true;
285}
286
287// Accumulates the output from the child in a string handle. Returns true if it
288// succeeded or false if an exception was thrown.
289static Local<Value> GetStdout(Isolate* isolate, int child_fd,
290 const struct timeval& start_time,
291 int read_timeout, int total_timeout) {
292 Local<String> accumulator = String::Empty(isolate);
293
294 int fullness = 0;
295 static const int kStdoutReadBufferSize = 4096;
296 char buffer[kStdoutReadBufferSize];
297
298 if (fcntl(child_fd, F_SETFL, O_NONBLOCK) != 0) {
299 return isolate->ThrowError(v8_strerror(isolate, errno));
300 }
301
302 int bytes_read;
303 do {
304 bytes_read = static_cast<int>(
305 read(child_fd, buffer + fullness, kStdoutReadBufferSize - fullness));
306 if (bytes_read == -1) {
307 if (errno == EAGAIN) {
308 if (!WaitOnFD(child_fd, read_timeout, total_timeout, start_time) ||
309 (TimeIsOut(start_time, total_timeout))) {
310 return isolate->ThrowError("Timed out waiting for output");
311 }
312 continue;
313 } else if (errno == EINTR) {
314 continue;
315 } else {
316 break;
317 }
318 }
319 if (bytes_read + fullness > 0) {
320 int length = bytes_read == 0 ? bytes_read + fullness
322 buffer, bytes_read + fullness);
323 Local<String> addition =
324 String::NewFromUtf8(isolate, buffer, NewStringType::kNormal, length)
325 .ToLocalChecked();
326 accumulator = String::Concat(isolate, accumulator, addition);
327 fullness = bytes_read + fullness - length;
328 memcpy(buffer, buffer + length, fullness);
329 }
330 } while (bytes_read != 0);
331 return accumulator;
332}
333
334// Modern Linux has the waitid call, which is like waitpid, but more useful
335// if you want a timeout. If we don't have waitid we can't limit the time
336// waiting for the process to exit without losing the information about
337// whether it exited normally. In the common case this doesn't matter because
338// we don't get here before the child has closed stdout and most programs don't
339// do that before they exit.
340//
341// We're disabling usage of waitid in Mac OS X because it doesn't work for us:
342// a parent process hangs on waiting while a child process is already a zombie.
343// See http://code.google.com/p/v8/issues/detail?id=401.
344#if defined(WNOWAIT) && !defined(ANDROID) && !defined(__APPLE__) && \
345 !defined(__NetBSD__) && !defined(__Fuchsia__)
346#if !defined(__FreeBSD__)
347#define HAS_WAITID 1
348#endif
349#endif
350
351// Get exit status of child.
352static bool WaitForChild(Isolate* isolate, int pid,
353 ZombieProtector& child_waiter,
354 const struct timeval& start_time, int read_timeout,
355 int total_timeout) {
356#ifdef HAS_WAITID
357
358 siginfo_t child_info;
359 child_info.si_pid = 0;
360 int useconds = 1;
361 // Wait for child to exit.
362 while (child_info.si_pid == 0) {
363 waitid(P_PID, pid, &child_info, WEXITED | WNOHANG | WNOWAIT);
364 usleep(useconds);
365 if (useconds < 1000000) useconds <<= 1;
366 if ((read_timeout != -1 && useconds / 1000 > read_timeout) ||
367 (TimeIsOut(start_time, total_timeout))) {
368 isolate->ThrowError("Timed out waiting for process to terminate");
369 kill(pid, SIGINT);
370 return false;
371 }
372 }
373 if (child_info.si_code == CLD_KILLED) {
374 char message[999];
375 snprintf(message, sizeof(message), "Child killed by signal %d",
376 child_info.si_status);
377 isolate->ThrowError(message);
378 return false;
379 }
380 if (child_info.si_code == CLD_EXITED && child_info.si_status != 0) {
381 char message[999];
382 snprintf(message, sizeof(message), "Child exited with status %d",
383 child_info.si_status);
384 isolate->ThrowError(message);
385 return false;
386 }
387
388#else // No waitid call.
389
390 int child_status;
391 waitpid(pid, &child_status, 0); // We hang here if the child doesn't exit.
392 child_waiter.ChildIsDeadNow();
393 if (WIFSIGNALED(child_status)) {
394 char message[999];
395 snprintf(message, sizeof(message), "Child killed by signal %d",
396 WTERMSIG(child_status));
397 isolate->ThrowError(message);
398 return false;
399 }
400 if (WEXITSTATUS(child_status) != 0) {
401 char message[999];
402 int exit_status = WEXITSTATUS(child_status);
403 snprintf(message, sizeof(message), "Child exited with status %d",
404 exit_status);
405 isolate->ThrowError(message);
406 return false;
407 }
408
409#endif // No waitid call.
410
411 return true;
412}
413
414#undef HAS_WAITID
415
416// Implementation of the system() function (see d8.h for details).
419 HandleScope scope(info.GetIsolate());
420 int read_timeout = -1;
421 int total_timeout = -1;
422 if (!GetTimeouts(info, &read_timeout, &total_timeout)) return;
423 Local<Array> command_args;
424 if (info.Length() > 1) {
425 if (!info[1]->IsArray()) {
426 info.GetIsolate()->ThrowError("system: Argument 2 must be an array");
427 return;
428 }
429 command_args = info[1].As<Array>();
430 } else {
431 command_args = Array::New(info.GetIsolate(), 0);
432 }
433 if (command_args->Length() > ExecArgs::kMaxArgs) {
434 info.GetIsolate()->ThrowError("Too many arguments to system()");
435 return;
436 }
437 if (info.Length() < 1) {
438 info.GetIsolate()->ThrowError("Too few arguments to system()");
439 return;
440 }
441
442 struct timeval start_time;
443 gettimeofday(&start_time, nullptr);
444
445 ExecArgs exec_args;
446 if (!exec_args.Init(info.GetIsolate(), info[0], command_args)) {
447 return;
448 }
449 int exec_error_fds[2];
450 int stdout_fds[2];
451
452 if (pipe(exec_error_fds) != 0) {
453 info.GetIsolate()->ThrowError("pipe syscall failed.");
454 return;
455 }
456 if (pipe(stdout_fds) != 0) {
457 info.GetIsolate()->ThrowError("pipe syscall failed.");
458 return;
459 }
460
461 pid_t pid = fork();
462 if (pid == 0) { // Child process.
463 ExecSubprocess(exec_error_fds, stdout_fds, exec_args);
464 exit(1);
465 }
466
467 // Parent process. Ensure that we clean up if we exit this function early.
468 ZombieProtector child_waiter(pid);
469 close(exec_error_fds[kWriteFD]);
470 close(stdout_fds[kWriteFD]);
471 OpenFDCloser error_read_closer(exec_error_fds[kReadFD]);
472 OpenFDCloser stdout_read_closer(stdout_fds[kReadFD]);
473
474 Isolate* isolate = info.GetIsolate();
475 if (!ChildLaunchedOK(isolate, exec_error_fds)) return;
476
477 Local<Value> accumulator = GetStdout(isolate, stdout_fds[kReadFD], start_time,
478 read_timeout, total_timeout);
479 if (accumulator->IsUndefined()) {
480 kill(pid, SIGINT); // On timeout, kill the subprocess.
481 info.GetReturnValue().Set(accumulator);
482 return;
483 }
484
485 if (!WaitForChild(isolate, pid, child_waiter, start_time, read_timeout,
486 total_timeout)) {
487 return;
488 }
489
490 info.GetReturnValue().Set(accumulator);
491}
492
495 if (info.Length() != 1) {
496 info.GetIsolate()->ThrowError("chdir() takes one argument");
497 return;
498 }
499 String::Utf8Value directory(info.GetIsolate(), info[0]);
500 if (*directory == nullptr) {
501 info.GetIsolate()->ThrowError(
502 "os.chdir(): String conversion of argument failed.");
503 return;
504 }
505 if (chdir(*directory) != 0) {
506 info.GetIsolate()->ThrowError(v8_strerror(info.GetIsolate(), errno));
507 return;
508 }
509}
510
513 if (info.Length() != 1) {
514 info.GetIsolate()->ThrowError("umask() takes one argument");
515 return;
516 }
517 if (info[0]->IsNumber()) {
518 int previous = umask(
519 info[0]->Int32Value(info.GetIsolate()->GetCurrentContext()).FromJust());
520 info.GetReturnValue().Set(previous);
521 return;
522 } else {
523 info.GetIsolate()->ThrowError("umask() argument must be numeric");
524 return;
525 }
526}
527
528static bool CheckItsADirectory(Isolate* isolate, char* directory) {
529 struct stat stat_buf;
530 int stat_result = stat(directory, &stat_buf);
531 if (stat_result != 0) {
532 isolate->ThrowError(v8_strerror(isolate, errno));
533 return false;
534 }
535 if ((stat_buf.st_mode & S_IFDIR) != 0) return true;
536 isolate->ThrowError(v8_strerror(isolate, EEXIST));
537 return false;
538}
539
540// Returns true for success. Creates intermediate directories as needed. No
541// error if the directory exists already.
542static bool mkdirp(Isolate* isolate, char* directory, mode_t mask) {
543 int result = mkdir(directory, mask);
544 if (result == 0) return true;
545 if (errno == EEXIST) {
546 return CheckItsADirectory(isolate, directory);
547 } else if (errno == ENOENT) { // Intermediate path element is missing.
548 char* last_slash = strrchr(directory, '/');
549 if (last_slash == nullptr) {
550 isolate->ThrowError(v8_strerror(isolate, errno));
551 return false;
552 }
553 *last_slash = 0;
554 if (!mkdirp(isolate, directory, mask)) return false;
555 *last_slash = '/';
556 result = mkdir(directory, mask);
557 if (result == 0) return true;
558 if (errno == EEXIST) {
559 return CheckItsADirectory(isolate, directory);
560 }
561 isolate->ThrowError(v8_strerror(isolate, errno));
562 return false;
563 } else {
564 isolate->ThrowError(v8_strerror(isolate, errno));
565 return false;
566 }
567}
568
571 mode_t mask = 0777;
572 if (info.Length() == 2) {
573 if (info[1]->IsNumber()) {
574 mask = info[1]
575 ->Int32Value(info.GetIsolate()->GetCurrentContext())
576 .FromJust();
577 } else {
578 info.GetIsolate()->ThrowError("mkdirp() second argument must be numeric");
579 return;
580 }
581 } else if (info.Length() != 1) {
582 info.GetIsolate()->ThrowError("mkdirp() takes one or two arguments");
583 return;
584 }
585 String::Utf8Value directory(info.GetIsolate(), info[0]);
586 if (*directory == nullptr) {
587 info.GetIsolate()->ThrowError(
588 "os.mkdirp(): String conversion of argument failed.");
589 return;
590 }
591 mkdirp(info.GetIsolate(), *directory, mask);
592}
593
596 if (info.Length() != 1) {
597 info.GetIsolate()->ThrowError("rmdir() takes one arguments");
598 return;
599 }
600 String::Utf8Value directory(info.GetIsolate(), info[0]);
601 if (*directory == nullptr) {
602 info.GetIsolate()->ThrowError(
603 "os.rmdir(): String conversion of argument failed.");
604 return;
605 }
606 rmdir(*directory);
607}
608
611 if (info.Length() != 2) {
612 info.GetIsolate()->ThrowError("setenv() takes two arguments");
613 return;
614 }
615 String::Utf8Value var(info.GetIsolate(), info[0]);
616 String::Utf8Value value(info.GetIsolate(), info[1]);
617 if (*var == nullptr) {
618 info.GetIsolate()->ThrowError(
619 "os.setenv(): String conversion of variable name failed.");
620 return;
621 }
622 if (*value == nullptr) {
623 info.GetIsolate()->ThrowError(
624 "os.setenv(): String conversion of variable contents failed.");
625 return;
626 }
627 setenv(*var, *value, 1);
628}
629
632 if (info.Length() != 1) {
633 info.GetIsolate()->ThrowError("unsetenv() takes one argument");
634 return;
635 }
636 String::Utf8Value var(info.GetIsolate(), info[0]);
637 if (*var == nullptr) {
638 info.GetIsolate()->ThrowError(
639 "os.setenv(): String conversion of variable name failed.");
640 return;
641 }
642 unsetenv(*var);
643}
644
645char* Shell::ReadCharsFromTcpPort(const char* name, int* size_out) {
646 DCHECK_GE(Shell::options.read_from_tcp_port, 0);
647
648 int sockfd = socket(PF_INET, SOCK_STREAM, 0);
649 if (sockfd < 0) {
650 fprintf(stderr, "Failed to create IPv4 socket\n");
651 return nullptr;
652 }
653
654 // Create an address for localhost:PORT where PORT is specified by the shell
655 // option --read-from-tcp-port.
656 sockaddr_in serv_addr;
657 memset(&serv_addr, 0, sizeof(sockaddr_in));
658 serv_addr.sin_family = AF_INET;
659 serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
660 serv_addr.sin_port = htons(Shell::options.read_from_tcp_port);
661
662 if (connect(sockfd, reinterpret_cast<sockaddr*>(&serv_addr),
663 sizeof(serv_addr)) < 0) {
664 fprintf(stderr, "Failed to connect to localhost:%d\n",
665 Shell::options.read_from_tcp_port.get());
666 close(sockfd);
667 return nullptr;
668 }
669
670 // The file server follows the simple protocol for requesting and receiving
671 // a file with a given filename:
672 //
673 // REQUEST client -> server: {filename}"\0"
674 // RESPONSE server -> client: {4-byte file-length}{file contents}
675 //
676 // i.e. the request sends the filename with a null terminator, and response
677 // sends the file contents by sending the length (as a 4-byte big-endian
678 // value) and the contents.
679
680 // If the file length is <0, there was an error sending the file, and the
681 // rest of the response is undefined (and may, in the future, contain an error
682 // message). The socket should be closed to avoid trying to interpret the
683 // undefined data.
684
685 // REQUEST
686 // Send the filename.
687 size_t sent_len = 0;
688 size_t name_len = strlen(name) + 1; // Includes the null terminator
689 while (sent_len < name_len) {
690 ssize_t sent_now = send(sockfd, name + sent_len, name_len - sent_len, 0);
691 if (sent_now < 0) {
692 fprintf(stderr, "Failed to send %s to localhost:%d\n", name,
693 Shell::options.read_from_tcp_port.get());
694 close(sockfd);
695 return nullptr;
696 }
697 sent_len += sent_now;
698 }
699
700 // RESPONSE
701 // Receive the file.
702 ssize_t received = 0;
703
704 // First, read the (zero-terminated) file length.
705 uint32_t big_endian_file_length;
706 received = recv(sockfd, &big_endian_file_length, 4, 0);
707 // We need those 4 bytes to read off the file length.
708 if (received < 4) {
709 fprintf(stderr, "Failed to receive %s's length from localhost:%d\n", name,
710 Shell::options.read_from_tcp_port.get());
711 close(sockfd);
712 return nullptr;
713 }
714 // Reinterpretet the received file length as a signed big-endian integer.
715 int32_t file_length = base::bit_cast<int32_t>(htonl(big_endian_file_length));
716
717 if (file_length < 0) {
718 fprintf(stderr, "Received length %d for %s from localhost:%d\n",
719 file_length, name, Shell::options.read_from_tcp_port.get());
720 close(sockfd);
721 return nullptr;
722 }
723
724 // Allocate the output array.
725 char* chars = new char[file_length];
726
727 // Now keep receiving and copying until the whole file is received.
728 ssize_t total_received = 0;
729 while (total_received < file_length) {
730 received =
731 recv(sockfd, chars + total_received, file_length - total_received, 0);
732 if (received < 0) {
733 fprintf(stderr, "Failed to receive %s from localhost:%d\n", name,
734 Shell::options.read_from_tcp_port.get());
735 close(sockfd);
736 delete[] chars;
737 return nullptr;
738 }
739 total_received += received;
740 }
741
742 close(sockfd);
743 *size_out = file_length;
744 return chars;
745}
746
748 if (options.enable_os_system) {
749 os_templ->Set(isolate, "system", FunctionTemplate::New(isolate, System));
750 }
751 os_templ->Set(isolate, "chdir",
753 os_templ->Set(isolate, "setenv",
755 os_templ->Set(isolate, "unsetenv",
757 os_templ->Set(isolate, "umask", FunctionTemplate::New(isolate, SetUMask));
758 os_templ->Set(isolate, "mkdirp",
760 os_templ->Set(isolate, "rmdir",
762}
763
764} // namespace v8
static Local< Array > New(Isolate *isolate, int length=0)
Definition api.cc:8119
bool Init(Isolate *isolate, Local< Value > arg0, Local< Array > command_args)
Definition d8-posix.cc:164
char *const * arg_array() const
Definition d8-posix.cc:208
char * exec_args_[kMaxArgs+1]
Definition d8-posix.cc:212
const char * arg0() const
Definition d8-posix.cc:209
static const unsigned kMaxArgs
Definition d8-posix.cc:207
static Local< FunctionTemplate > New(Isolate *isolate, FunctionCallback callback=nullptr, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect, const CFunction *c_function=nullptr, uint16_t instance_type=0, uint16_t allowed_receiver_instance_type_range_start=0, uint16_t allowed_receiver_instance_type_range_end=0)
Definition api.cc:1101
static Local< Integer > New(Isolate *isolate, int32_t value)
Definition api.cc:9568
V8_INLINE Local< S > As() const
OpenFDCloser(int fd)
Definition d8-posix.cc:151
static void AddOSMethods(v8::Isolate *isolate, Local< ObjectTemplate > os_template)
Definition d8-posix.cc:747
static void System(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:417
static void MakeDirectory(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:569
static void UnsetEnvironment(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:630
static void SetEnvironment(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:609
static void SetUMask(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:511
static void RemoveDirectory(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:594
static char * ReadCharsFromTcpPort(const char *name, int *size_out)
Definition d8-posix.cc:645
static void ChangeDirectory(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition d8-posix.cc:493
static ShellOptions options
Definition d8.h:760
size_t length() const
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromUtf8(Isolate *isolate, const char *data, NewStringType type=NewStringType::kNormal, int length=-1)
Definition api.cc:7593
static Local< String > Concat(Isolate *isolate, Local< String > left, Local< String > right)
Definition api.cc:7613
static V8_INLINE Local< String > Empty(Isolate *isolate)
ZombieProtector(int pid)
Definition d8-posix.cc:138
LineAndColumn previous
ZoneVector< RpoNumber > & result
uint32_t const mask
V8_INLINE Dest bit_cast(Source const &source)
Definition macros.h:95
bool V8_EXPORT ValidateCallbackInfo(const FunctionCallbackInfo< void > &info)
Definition api.cc:12301
static bool CheckItsADirectory(Isolate *isolate, char *directory)
Definition d8-posix.cc:528
static bool WaitForChild(Isolate *isolate, int pid, ZombieProtector &child_waiter, const struct timeval &start_time, int read_timeout, int total_timeout)
Definition d8-posix.cc:352
static bool mkdirp(Isolate *isolate, char *directory, mode_t mask)
Definition d8-posix.cc:542
static bool TimeIsOut(const struct timeval &start_time, const int &total_time)
Definition d8-posix.cc:116
static void ExecSubprocess(int *exec_error_fds, int *stdout_fds, const ExecArgs &exec_args)
Definition d8-posix.cc:253
static int LengthWithoutIncompleteUtf8(char *buffer, int len)
Definition d8-posix.cc:33
static bool WaitOnFD(int fd, int read_timeout, int total_timeout, const struct timeval &start_time)
Definition d8-posix.cc:85
static bool GetTimeouts(const v8::FunctionCallbackInfo< v8::Value > &info, int *read_timeout, int *total_timeout)
Definition d8-posix.cc:216
static const int kWriteFD
Definition d8-posix.cc:248
static bool ChildLaunchedOK(Isolate *isolate, int *exec_error_fds)
Definition d8-posix.cc:274
static const int kReadFD
Definition d8-posix.cc:247
static Local< Value > GetStdout(Isolate *isolate, int child_fd, const struct timeval &start_time, int read_timeout, int total_timeout)
Definition d8-posix.cc:289
#define DCHECK_GE(v1, v2)
Definition logging.h:488
#define DCHECK(condition)
Definition logging.h:482
std::unique_ptr< ValueMirror > value