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.
10 #include <sys/select.h>
13 #include <sys/types.h>
23 // If the buffer ends in the middle of a UTF-8 sequence then we return
24 // the length of the string up to but not including the incomplete UTF-8
25 // sequence. If the buffer ends with a valid UTF-8 sequence then we
26 // return the whole buffer.
27 static int LengthWithoutIncompleteUtf8(char* buffer, int len) {
30 static const int kUtf8SingleByteMask = 0x80;
31 static const int kUtf8SingleByteValue = 0x00;
33 static const int kUtf8TwoByteMask = 0xe0;
34 static const int kUtf8TwoByteValue = 0xc0;
36 static const int kUtf8ThreeByteMask = 0xf0;
37 static const int kUtf8ThreeByteValue = 0xe0;
39 static const int kUtf8FourByteMask = 0xf8;
40 static const int kUtf8FourByteValue = 0xf0;
41 // Subsequent bytes of a multi-byte encoding.
42 static const int kMultiByteMask = 0xc0;
43 static const int kMultiByteValue = 0x80;
44 int multi_byte_bytes_seen = 0;
46 int c = buffer[answer - 1];
47 // Ends in valid single-byte sequence?
48 if ((c & kUtf8SingleByteMask) == kUtf8SingleByteValue) return answer;
49 // Ends in one or more subsequent bytes of a multi-byte value?
50 if ((c & kMultiByteMask) == kMultiByteValue) {
51 multi_byte_bytes_seen++;
54 if ((c & kUtf8TwoByteMask) == kUtf8TwoByteValue) {
55 if (multi_byte_bytes_seen >= 1) {
59 } else if ((c & kUtf8ThreeByteMask) == kUtf8ThreeByteValue) {
60 if (multi_byte_bytes_seen >= 2) {
64 } else if ((c & kUtf8FourByteMask) == kUtf8FourByteValue) {
65 if (multi_byte_bytes_seen >= 3) {
70 return answer; // Malformed UTF-8.
78 // Suspends the thread until there is data available from the child process.
79 // Returns false on timeout, true on data ready.
80 static bool WaitOnFD(int fd,
83 const struct timeval& start_time) {
84 fd_set readfds, writefds, exceptfds;
85 struct timeval timeout;
87 if (total_timeout != -1) {
88 struct timeval time_now;
89 gettimeofday(&time_now, NULL);
90 int seconds = time_now.tv_sec - start_time.tv_sec;
91 gone = seconds * 1000 + (time_now.tv_usec - start_time.tv_usec) / 1000;
92 if (gone >= total_timeout) return false;
98 FD_SET(fd, &exceptfds);
99 if (read_timeout == -1 ||
100 (total_timeout != -1 && total_timeout - gone < read_timeout)) {
101 read_timeout = total_timeout - gone;
103 timeout.tv_usec = (read_timeout % 1000) * 1000;
104 timeout.tv_sec = read_timeout / 1000;
105 int number_of_fds_ready = select(fd + 1,
109 read_timeout != -1 ? &timeout : NULL);
110 return number_of_fds_ready == 1;
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.
116 static 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, NULL);
120 // Careful about overflow.
121 int seconds = time_now.tv_sec - start_time.tv_sec;
123 if (seconds * 1000 > total_time) return true;
126 int useconds = time_now.tv_usec - start_time.tv_usec;
127 if (seconds * 1000000 + useconds > total_time * 1000) {
134 // A utility class that does a non-hanging waitpid on the child process if we
135 // bail out of the System() function early. If you don't ever do a waitpid on
136 // a subprocess then it turns into one of those annoying 'zombie processes'.
137 class ZombieProtector {
139 explicit ZombieProtector(int pid): pid_(pid) { }
140 ~ZombieProtector() { if (pid_ != 0) waitpid(pid_, NULL, 0); }
141 void ChildIsDeadNow() { pid_ = 0; }
147 // A utility class that closes a file descriptor when it goes out of scope.
150 explicit OpenFDCloser(int fd): fd_(fd) { }
151 ~OpenFDCloser() { close(fd_); }
157 // A utility class that takes the array of command arguments and puts then in an
158 // array of new[]ed UTF-8 C strings. Deallocates them again when it goes out of
163 exec_args_[0] = NULL;
165 bool Init(Isolate* isolate, Handle<Value> arg0, Handle<Array> command_args) {
166 String::Utf8Value prog(arg0);
168 const char* message =
169 "os.system(): String conversion of program name failed";
170 isolate->ThrowException(String::NewFromUtf8(isolate, message));
173 int len = prog.length() + 3;
174 char* c_arg = new char[len];
175 snprintf(c_arg, len, "%s", *prog);
176 exec_args_[0] = c_arg;
178 for (unsigned j = 0; j < command_args->Length(); i++, j++) {
179 Handle<Value> arg(command_args->Get(Integer::New(isolate, j)));
180 String::Utf8Value utf8_arg(arg);
181 if (*utf8_arg == NULL) {
182 exec_args_[i] = NULL; // Consistent state for destructor.
183 const char* message =
184 "os.system(): String conversion of argument failed.";
185 isolate->ThrowException(String::NewFromUtf8(isolate, message));
188 int len = utf8_arg.length() + 1;
189 char* c_arg = new char[len];
190 snprintf(c_arg, len, "%s", *utf8_arg);
191 exec_args_[i] = c_arg;
193 exec_args_[i] = NULL;
197 for (unsigned i = 0; i < kMaxArgs; i++) {
198 if (exec_args_[i] == NULL) {
201 delete [] exec_args_[i];
205 static const unsigned kMaxArgs = 1000;
206 char* const* arg_array() const { return exec_args_; }
207 const char* arg0() const { return exec_args_[0]; }
210 char* exec_args_[kMaxArgs + 1];
214 // Gets the optional timeouts from the arguments to the system() call.
215 static bool GetTimeouts(const v8::FunctionCallbackInfo<v8::Value>& args,
217 int* total_timeout) {
218 if (args.Length() > 3) {
219 if (args[3]->IsNumber()) {
220 *total_timeout = args[3]->Int32Value();
222 args.GetIsolate()->ThrowException(String::NewFromUtf8(
223 args.GetIsolate(), "system: Argument 4 must be a number"));
227 if (args.Length() > 2) {
228 if (args[2]->IsNumber()) {
229 *read_timeout = args[2]->Int32Value();
231 args.GetIsolate()->ThrowException(String::NewFromUtf8(
232 args.GetIsolate(), "system: Argument 3 must be a number"));
240 static const int kReadFD = 0;
241 static const int kWriteFD = 1;
244 // This is run in the child process after fork() but before exec(). It normally
245 // ends with the child process being replaced with the desired child program.
246 // It only returns if an error occurred.
247 static void ExecSubprocess(int* exec_error_fds,
249 const ExecArgs& exec_args) {
250 close(exec_error_fds[kReadFD]); // Don't need this in the child.
251 close(stdout_fds[kReadFD]); // Don't need this in the child.
252 close(1); // Close stdout.
253 dup2(stdout_fds[kWriteFD], 1); // Dup pipe fd to stdout.
254 close(stdout_fds[kWriteFD]); // Don't need the original fd now.
255 fcntl(exec_error_fds[kWriteFD], F_SETFD, FD_CLOEXEC);
256 execvp(exec_args.arg0(), exec_args.arg_array());
257 // Only get here if the exec failed. Write errno to the parent to tell
258 // them it went wrong. If it went well the pipe is closed.
262 bytes_written = write(exec_error_fds[kWriteFD], &err, sizeof(err));
263 } while (bytes_written == -1 && errno == EINTR);
264 // Return (and exit child process).
268 // Runs in the parent process. Checks that the child was able to exec (closing
269 // the file desriptor), or reports an error if it failed.
270 static bool ChildLaunchedOK(Isolate* isolate, int* exec_error_fds) {
274 bytes_read = read(exec_error_fds[kReadFD], &err, sizeof(err));
275 } while (bytes_read == -1 && errno == EINTR);
276 if (bytes_read != 0) {
277 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(err)));
284 // Accumulates the output from the child in a string handle. Returns true if it
285 // succeeded or false if an exception was thrown.
286 static Handle<Value> GetStdout(Isolate* isolate,
288 const struct timeval& start_time,
291 Handle<String> accumulator = String::Empty(isolate);
294 static const int kStdoutReadBufferSize = 4096;
295 char buffer[kStdoutReadBufferSize];
297 if (fcntl(child_fd, F_SETFL, O_NONBLOCK) != 0) {
298 return isolate->ThrowException(
299 String::NewFromUtf8(isolate, strerror(errno)));
304 bytes_read = read(child_fd,
306 kStdoutReadBufferSize - fullness);
307 if (bytes_read == -1) {
308 if (errno == EAGAIN) {
309 if (!WaitOnFD(child_fd,
313 (TimeIsOut(start_time, total_timeout))) {
314 return isolate->ThrowException(
315 String::NewFromUtf8(isolate, "Timed out waiting for output"));
318 } else if (errno == EINTR) {
324 if (bytes_read + fullness > 0) {
325 int length = bytes_read == 0 ?
326 bytes_read + fullness :
327 LengthWithoutIncompleteUtf8(buffer, bytes_read + fullness);
328 Handle<String> addition =
329 String::NewFromUtf8(isolate, buffer, String::kNormalString, length);
330 accumulator = String::Concat(accumulator, addition);
331 fullness = bytes_read + fullness - length;
332 memcpy(buffer, buffer + length, fullness);
334 } while (bytes_read != 0);
339 // Modern Linux has the waitid call, which is like waitpid, but more useful
340 // if you want a timeout. If we don't have waitid we can't limit the time
341 // waiting for the process to exit without losing the information about
342 // whether it exited normally. In the common case this doesn't matter because
343 // we don't get here before the child has closed stdout and most programs don't
344 // do that before they exit.
346 // We're disabling usage of waitid in Mac OS X because it doens't work for us:
347 // a parent process hangs on waiting while a child process is already a zombie.
348 // See http://code.google.com/p/v8/issues/detail?id=401.
349 #if defined(WNOWAIT) && !defined(ANDROID) && !defined(__APPLE__) \
350 && !defined(__NetBSD__)
351 #if !defined(__FreeBSD__)
357 // Get exit status of child.
358 static bool WaitForChild(Isolate* isolate,
360 ZombieProtector& child_waiter, // NOLINT
361 const struct timeval& start_time,
366 siginfo_t child_info;
367 child_info.si_pid = 0;
369 // Wait for child to exit.
370 while (child_info.si_pid == 0) {
371 waitid(P_PID, pid, &child_info, WEXITED | WNOHANG | WNOWAIT);
373 if (useconds < 1000000) useconds <<= 1;
374 if ((read_timeout != -1 && useconds / 1000 > read_timeout) ||
375 (TimeIsOut(start_time, total_timeout))) {
376 isolate->ThrowException(String::NewFromUtf8(
377 isolate, "Timed out waiting for process to terminate"));
382 if (child_info.si_code == CLD_KILLED) {
386 "Child killed by signal %d",
387 child_info.si_status);
388 isolate->ThrowException(String::NewFromUtf8(isolate, message));
391 if (child_info.si_code == CLD_EXITED && child_info.si_status != 0) {
395 "Child exited with status %d",
396 child_info.si_status);
397 isolate->ThrowException(String::NewFromUtf8(isolate, message));
401 #else // No waitid call.
404 waitpid(pid, &child_status, 0); // We hang here if the child doesn't exit.
405 child_waiter.ChildIsDeadNow();
406 if (WIFSIGNALED(child_status)) {
410 "Child killed by signal %d",
411 WTERMSIG(child_status));
412 isolate->ThrowException(String::NewFromUtf8(isolate, message));
415 if (WEXITSTATUS(child_status) != 0) {
417 int exit_status = WEXITSTATUS(child_status);
420 "Child exited with status %d",
422 isolate->ThrowException(String::NewFromUtf8(isolate, message));
426 #endif // No waitid call.
432 // Implementation of the system() function (see d8.h for details).
433 void Shell::System(const v8::FunctionCallbackInfo<v8::Value>& args) {
434 HandleScope scope(args.GetIsolate());
435 int read_timeout = -1;
436 int total_timeout = -1;
437 if (!GetTimeouts(args, &read_timeout, &total_timeout)) return;
438 Handle<Array> command_args;
439 if (args.Length() > 1) {
440 if (!args[1]->IsArray()) {
441 args.GetIsolate()->ThrowException(String::NewFromUtf8(
442 args.GetIsolate(), "system: Argument 2 must be an array"));
445 command_args = Handle<Array>::Cast(args[1]);
447 command_args = Array::New(args.GetIsolate(), 0);
449 if (command_args->Length() > ExecArgs::kMaxArgs) {
450 args.GetIsolate()->ThrowException(String::NewFromUtf8(
451 args.GetIsolate(), "Too many arguments to system()"));
454 if (args.Length() < 1) {
455 args.GetIsolate()->ThrowException(String::NewFromUtf8(
456 args.GetIsolate(), "Too few arguments to system()"));
460 struct timeval start_time;
461 gettimeofday(&start_time, NULL);
464 if (!exec_args.Init(args.GetIsolate(), args[0], command_args)) {
467 int exec_error_fds[2];
470 if (pipe(exec_error_fds) != 0) {
471 args.GetIsolate()->ThrowException(
472 String::NewFromUtf8(args.GetIsolate(), "pipe syscall failed."));
475 if (pipe(stdout_fds) != 0) {
476 args.GetIsolate()->ThrowException(
477 String::NewFromUtf8(args.GetIsolate(), "pipe syscall failed."));
482 if (pid == 0) { // Child process.
483 ExecSubprocess(exec_error_fds, stdout_fds, exec_args);
487 // Parent process. Ensure that we clean up if we exit this function early.
488 ZombieProtector child_waiter(pid);
489 close(exec_error_fds[kWriteFD]);
490 close(stdout_fds[kWriteFD]);
491 OpenFDCloser error_read_closer(exec_error_fds[kReadFD]);
492 OpenFDCloser stdout_read_closer(stdout_fds[kReadFD]);
494 if (!ChildLaunchedOK(args.GetIsolate(), exec_error_fds)) return;
496 Handle<Value> accumulator = GetStdout(args.GetIsolate(),
501 if (accumulator->IsUndefined()) {
502 kill(pid, SIGINT); // On timeout, kill the subprocess.
503 args.GetReturnValue().Set(accumulator);
507 if (!WaitForChild(args.GetIsolate(),
516 args.GetReturnValue().Set(accumulator);
520 void Shell::ChangeDirectory(const v8::FunctionCallbackInfo<v8::Value>& args) {
521 if (args.Length() != 1) {
522 const char* message = "chdir() takes one argument";
523 args.GetIsolate()->ThrowException(
524 String::NewFromUtf8(args.GetIsolate(), message));
527 String::Utf8Value directory(args[0]);
528 if (*directory == NULL) {
529 const char* message = "os.chdir(): String conversion of argument failed.";
530 args.GetIsolate()->ThrowException(
531 String::NewFromUtf8(args.GetIsolate(), message));
534 if (chdir(*directory) != 0) {
535 args.GetIsolate()->ThrowException(
536 String::NewFromUtf8(args.GetIsolate(), strerror(errno)));
542 void Shell::SetUMask(const v8::FunctionCallbackInfo<v8::Value>& args) {
543 if (args.Length() != 1) {
544 const char* message = "umask() takes one argument";
545 args.GetIsolate()->ThrowException(
546 String::NewFromUtf8(args.GetIsolate(), message));
549 if (args[0]->IsNumber()) {
550 mode_t mask = args[0]->Int32Value();
551 int previous = umask(mask);
552 args.GetReturnValue().Set(previous);
555 const char* message = "umask() argument must be numeric";
556 args.GetIsolate()->ThrowException(
557 String::NewFromUtf8(args.GetIsolate(), message));
563 static bool CheckItsADirectory(Isolate* isolate, char* directory) {
564 struct stat stat_buf;
565 int stat_result = stat(directory, &stat_buf);
566 if (stat_result != 0) {
567 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
570 if ((stat_buf.st_mode & S_IFDIR) != 0) return true;
571 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(EEXIST)));
576 // Returns true for success. Creates intermediate directories as needed. No
577 // error if the directory exists already.
578 static bool mkdirp(Isolate* isolate, char* directory, mode_t mask) {
579 int result = mkdir(directory, mask);
580 if (result == 0) return true;
581 if (errno == EEXIST) {
582 return CheckItsADirectory(isolate, directory);
583 } else if (errno == ENOENT) { // Intermediate path element is missing.
584 char* last_slash = strrchr(directory, '/');
585 if (last_slash == NULL) {
586 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
590 if (!mkdirp(isolate, directory, mask)) return false;
592 result = mkdir(directory, mask);
593 if (result == 0) return true;
594 if (errno == EEXIST) {
595 return CheckItsADirectory(isolate, directory);
597 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
600 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
606 void Shell::MakeDirectory(const v8::FunctionCallbackInfo<v8::Value>& args) {
608 if (args.Length() == 2) {
609 if (args[1]->IsNumber()) {
610 mask = args[1]->Int32Value();
612 const char* message = "mkdirp() second argument must be numeric";
613 args.GetIsolate()->ThrowException(
614 String::NewFromUtf8(args.GetIsolate(), message));
617 } else if (args.Length() != 1) {
618 const char* message = "mkdirp() takes one or two arguments";
619 args.GetIsolate()->ThrowException(
620 String::NewFromUtf8(args.GetIsolate(), message));
623 String::Utf8Value directory(args[0]);
624 if (*directory == NULL) {
625 const char* message = "os.mkdirp(): String conversion of argument failed.";
626 args.GetIsolate()->ThrowException(
627 String::NewFromUtf8(args.GetIsolate(), message));
630 mkdirp(args.GetIsolate(), *directory, mask);
634 void Shell::RemoveDirectory(const v8::FunctionCallbackInfo<v8::Value>& args) {
635 if (args.Length() != 1) {
636 const char* message = "rmdir() takes one or two arguments";
637 args.GetIsolate()->ThrowException(
638 String::NewFromUtf8(args.GetIsolate(), message));
641 String::Utf8Value directory(args[0]);
642 if (*directory == NULL) {
643 const char* message = "os.rmdir(): String conversion of argument failed.";
644 args.GetIsolate()->ThrowException(
645 String::NewFromUtf8(args.GetIsolate(), message));
652 void Shell::SetEnvironment(const v8::FunctionCallbackInfo<v8::Value>& args) {
653 if (args.Length() != 2) {
654 const char* message = "setenv() takes two arguments";
655 args.GetIsolate()->ThrowException(
656 String::NewFromUtf8(args.GetIsolate(), message));
659 String::Utf8Value var(args[0]);
660 String::Utf8Value value(args[1]);
662 const char* message =
663 "os.setenv(): String conversion of variable name failed.";
664 args.GetIsolate()->ThrowException(
665 String::NewFromUtf8(args.GetIsolate(), message));
668 if (*value == NULL) {
669 const char* message =
670 "os.setenv(): String conversion of variable contents failed.";
671 args.GetIsolate()->ThrowException(
672 String::NewFromUtf8(args.GetIsolate(), message));
675 setenv(*var, *value, 1);
679 void Shell::UnsetEnvironment(const v8::FunctionCallbackInfo<v8::Value>& args) {
680 if (args.Length() != 1) {
681 const char* message = "unsetenv() takes one argument";
682 args.GetIsolate()->ThrowException(
683 String::NewFromUtf8(args.GetIsolate(), message));
686 String::Utf8Value var(args[0]);
688 const char* message =
689 "os.setenv(): String conversion of variable name failed.";
690 args.GetIsolate()->ThrowException(
691 String::NewFromUtf8(args.GetIsolate(), message));
698 void Shell::AddOSMethods(Isolate* isolate, Handle<ObjectTemplate> os_templ) {
699 os_templ->Set(String::NewFromUtf8(isolate, "system"),
700 FunctionTemplate::New(isolate, System));
701 os_templ->Set(String::NewFromUtf8(isolate, "chdir"),
702 FunctionTemplate::New(isolate, ChangeDirectory));
703 os_templ->Set(String::NewFromUtf8(isolate, "setenv"),
704 FunctionTemplate::New(isolate, SetEnvironment));
705 os_templ->Set(String::NewFromUtf8(isolate, "unsetenv"),
706 FunctionTemplate::New(isolate, UnsetEnvironment));
707 os_templ->Set(String::NewFromUtf8(isolate, "umask"),
708 FunctionTemplate::New(isolate, SetUMask));
709 os_templ->Set(String::NewFromUtf8(isolate, "mkdirp"),
710 FunctionTemplate::New(isolate, MakeDirectory));
711 os_templ->Set(String::NewFromUtf8(isolate, "rmdir"),
712 FunctionTemplate::New(isolate, RemoveDirectory));