Initial implementation of process.evalcx
[platform/upstream/nodejs.git] / src / node.cc
1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
2 #include <node.h>
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <limits.h> /* PATH_MAX */
8 #include <assert.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <dlfcn.h> /* dlopen(), dlsym() */
12 #include <sys/types.h>
13 #include <unistd.h> /* setuid, getuid */
14
15 #include <node_events.h>
16 #include <node_dns.h>
17 #include <node_net.h>
18 #include <node_file.h>
19 #include <node_idle_watcher.h>
20 #include <node_http.h>
21 #include <node_signal_handler.h>
22 #include <node_stat.h>
23 #include <node_timer.h>
24 #include <node_child_process.h>
25 #include <node_constants.h>
26 #include <node_stdio.h>
27 #include <node_natives.h>
28 #include <node_version.h>
29
30 #include <v8-debug.h>
31
32 using namespace v8;
33
34 extern char **environ;
35
36 namespace node {
37
38 static Persistent<Object> process;
39
40 static Persistent<String> dev_symbol;
41 static Persistent<String> ino_symbol;
42 static Persistent<String> mode_symbol;
43 static Persistent<String> nlink_symbol;
44 static Persistent<String> uid_symbol;
45 static Persistent<String> gid_symbol;
46 static Persistent<String> rdev_symbol;
47 static Persistent<String> size_symbol;
48 static Persistent<String> blksize_symbol;
49 static Persistent<String> blocks_symbol;
50 static Persistent<String> atime_symbol;
51 static Persistent<String> mtime_symbol;
52 static Persistent<String> ctime_symbol;
53
54 static Persistent<String> rss_symbol;
55 static Persistent<String> vsize_symbol;
56 static Persistent<String> heap_total_symbol;
57 static Persistent<String> heap_used_symbol;
58
59 static Persistent<String> listeners_symbol;
60 static Persistent<String> uncaught_exception_symbol;
61 static Persistent<String> emit_symbol;
62
63 static int option_end_index = 0;
64 static bool use_debug_agent = false;
65 static bool debug_wait_connect = false;
66 static int debug_port=5858;
67
68
69 static ev_async eio_want_poll_notifier;
70 static ev_async eio_done_poll_notifier;
71 static ev_idle  eio_poller;
72
73 static ev_timer  gc_timer;
74 #define GC_INTERVAL 2.0
75
76
77 // Node calls this every GC_INTERVAL seconds in order to try and call the
78 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
79 // is an effective measure of idleness.
80 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
81   assert(watcher == &gc_timer);
82   assert(revents == EV_TIMER);
83   if (ev_pending_count(EV_DEFAULT_UC) == 0) V8::IdleNotification();
84 }
85
86
87 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
88   assert(watcher == &eio_poller);
89   assert(revents == EV_IDLE);
90
91   //printf("eio_poller\n");
92
93   if (eio_poll() != -1) {
94     //printf("eio_poller stop\n");
95     ev_idle_stop(EV_DEFAULT_UC_ watcher);
96   }
97 }
98
99
100 // Called from the main thread.
101 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
102   assert(watcher == &eio_want_poll_notifier);
103   assert(revents == EV_ASYNC);
104
105   //printf("want poll notifier\n");
106
107   if (eio_poll() == -1) {
108     //printf("eio_poller start\n");
109     ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
110   }
111 }
112
113
114 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
115   assert(watcher == &eio_done_poll_notifier);
116   assert(revents == EV_ASYNC);
117
118   //printf("done poll notifier\n");
119
120   if (eio_poll() != -1) {
121     //printf("eio_poller stop\n");
122     ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
123   }
124 }
125
126
127 // EIOWantPoll() is called from the EIO thread pool each time an EIO
128 // request (that is, one of the node.fs.* functions) has completed.
129 static void EIOWantPoll(void) {
130   // Signal the main thread that eio_poll need to be processed.
131   ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
132 }
133
134
135 static void EIODonePoll(void) {
136   // Signal the main thread that we should stop calling eio_poll().
137   // from the idle watcher.
138   ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
139 }
140
141
142 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
143   HandleScope scope;
144
145   if (!encoding_v->IsString()) return _default;
146
147   String::Utf8Value encoding(encoding_v->ToString());
148
149   if (strcasecmp(*encoding, "utf8") == 0) {
150     return UTF8;
151   } else if (strcasecmp(*encoding, "utf-8") == 0) {
152     return UTF8;
153   } else if (strcasecmp(*encoding, "ascii") == 0) {
154     return ASCII;
155   } else if (strcasecmp(*encoding, "binary") == 0) {
156     return BINARY;
157   } else if (strcasecmp(*encoding, "raw") == 0) {
158     fprintf(stderr, "'raw' (array of integers) has been removed. "
159                     "Use 'binary'.\n");
160     return BINARY;
161   } else if (strcasecmp(*encoding, "raws") == 0) {
162     fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
163                     "Please update your code.\n");
164     return BINARY;
165   } else {
166     return _default;
167   }
168 }
169
170 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
171   HandleScope scope;
172
173   if (!len) return scope.Close(String::Empty());
174
175   if (encoding == BINARY) {
176     const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
177     uint16_t * twobytebuf = new uint16_t[len];
178     for (size_t i = 0; i < len; i++) {
179       // XXX is the following line platform independent?
180       twobytebuf[i] = cbuf[i];
181     }
182     Local<String> chunk = String::New(twobytebuf, len);
183     delete [] twobytebuf; // TODO use ExternalTwoByteString?
184     return scope.Close(chunk);
185   }
186
187   // utf8 or ascii encoding
188   Local<String> chunk = String::New((const char*)buf, len);
189   return scope.Close(chunk);
190 }
191
192 // Returns -1 if the handle was not valid for decoding
193 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
194   HandleScope scope;
195
196   if (val->IsArray()) {
197     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
198                     "Use 'binary'.\n");
199     assert(0);
200     return -1;
201   }
202
203   Local<String> str = val->ToString();
204
205   if (encoding == UTF8) return str->Utf8Length();
206
207   return str->Length();
208 }
209
210 #ifndef MIN
211 # define MIN(a, b) ((a) < (b) ? (a) : (b))
212 #endif
213
214 // Returns number of bytes written.
215 ssize_t DecodeWrite(char *buf, size_t buflen,
216                     v8::Handle<v8::Value> val,
217                     enum encoding encoding) {
218   HandleScope scope;
219
220   // XXX
221   // A lot of improvement can be made here. See:
222   // http://code.google.com/p/v8/issues/detail?id=270
223   // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
224   // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
225
226   if (val->IsArray()) {
227     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
228                     "Use 'binary'.\n");
229     assert(0);
230     return -1;
231   }
232
233   Local<String> str = val->ToString();
234
235   if (encoding == UTF8) {
236     str->WriteUtf8(buf, buflen);
237     return buflen;
238   }
239
240   if (encoding == ASCII) {
241     str->WriteAscii(buf, 0, buflen);
242     return buflen;
243   }
244
245   // THIS IS AWFUL!!! FIXME
246
247   assert(encoding == BINARY);
248
249   uint16_t * twobytebuf = new uint16_t[buflen];
250
251   str->Write(twobytebuf, 0, buflen);
252
253   for (size_t i = 0; i < buflen; i++) {
254     unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
255     assert(b[1] == 0);
256     buf[i] = b[0];
257   }
258
259   delete [] twobytebuf;
260
261   return buflen;
262 }
263
264 static Persistent<FunctionTemplate> stats_constructor_template;
265
266 Local<Object> BuildStatsObject(struct stat * s) {
267   HandleScope scope;
268
269   if (dev_symbol.IsEmpty()) {
270     dev_symbol = NODE_PSYMBOL("dev");
271     ino_symbol = NODE_PSYMBOL("ino");
272     mode_symbol = NODE_PSYMBOL("mode");
273     nlink_symbol = NODE_PSYMBOL("nlink");
274     uid_symbol = NODE_PSYMBOL("uid");
275     gid_symbol = NODE_PSYMBOL("gid");
276     rdev_symbol = NODE_PSYMBOL("rdev");
277     size_symbol = NODE_PSYMBOL("size");
278     blksize_symbol = NODE_PSYMBOL("blksize");
279     blocks_symbol = NODE_PSYMBOL("blocks");
280     atime_symbol = NODE_PSYMBOL("atime");
281     mtime_symbol = NODE_PSYMBOL("mtime");
282     ctime_symbol = NODE_PSYMBOL("ctime");
283   }
284
285   Local<Object> stats =
286     stats_constructor_template->GetFunction()->NewInstance();
287
288   /* ID of device containing file */
289   stats->Set(dev_symbol, Integer::New(s->st_dev));
290
291   /* inode number */
292   stats->Set(ino_symbol, Integer::New(s->st_ino));
293
294   /* protection */
295   stats->Set(mode_symbol, Integer::New(s->st_mode));
296
297   /* number of hard links */
298   stats->Set(nlink_symbol, Integer::New(s->st_nlink));
299
300   /* user ID of owner */
301   stats->Set(uid_symbol, Integer::New(s->st_uid));
302
303   /* group ID of owner */
304   stats->Set(gid_symbol, Integer::New(s->st_gid));
305
306   /* device ID (if special file) */
307   stats->Set(rdev_symbol, Integer::New(s->st_rdev));
308
309   /* total size, in bytes */
310   stats->Set(size_symbol, Integer::New(s->st_size));
311
312   /* blocksize for filesystem I/O */
313   stats->Set(blksize_symbol, Integer::New(s->st_blksize));
314
315   /* number of blocks allocated */
316   stats->Set(blocks_symbol, Integer::New(s->st_blocks));
317
318   /* time of last access */
319   stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
320
321   /* time of last modification */
322   stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
323
324   /* time of last status change */
325   stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
326
327   return scope.Close(stats);
328 }
329
330
331 // Extracts a C str from a V8 Utf8Value.
332 const char* ToCString(const v8::String::Utf8Value& value) {
333   return *value ? *value : "<str conversion failed>";
334 }
335
336 static void ReportException(TryCatch &try_catch, bool show_line = false) {
337   Handle<Message> message = try_catch.Message();
338
339   Handle<Value> error = try_catch.Exception();
340   Handle<String> stack;
341
342   if (error->IsObject()) {
343     Handle<Object> obj = Handle<Object>::Cast(error);
344     Handle<Value> raw_stack = obj->Get(String::New("stack"));
345     if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
346   }
347
348   if (show_line && !message.IsEmpty()) {
349     // Print (filename):(line number): (message).
350     String::Utf8Value filename(message->GetScriptResourceName());
351     const char* filename_string = ToCString(filename);
352     int linenum = message->GetLineNumber();
353     fprintf(stderr, "%s:%i\n", filename_string, linenum);
354     // Print line of source code.
355     String::Utf8Value sourceline(message->GetSourceLine());
356     const char* sourceline_string = ToCString(sourceline);
357     fprintf(stderr, "%s\n", sourceline_string);
358     // Print wavy underline (GetUnderline is deprecated).
359     int start = message->GetStartColumn();
360     for (int i = 0; i < start; i++) {
361       fprintf(stderr, " ");
362     }
363     int end = message->GetEndColumn();
364     for (int i = start; i < end; i++) {
365       fprintf(stderr, "^");
366     }
367     fprintf(stderr, "\n");
368   }
369
370   if (stack.IsEmpty()) {
371     message->PrintCurrentStackTrace(stderr);
372   } else {
373     String::Utf8Value trace(stack);
374     fprintf(stderr, "%s\n", *trace);
375   }
376   fflush(stderr);
377 }
378
379 // Executes a str within the current v8 context.
380 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
381   HandleScope scope;
382   TryCatch try_catch;
383
384   Local<Script> script = Script::Compile(source, filename);
385   if (script.IsEmpty()) {
386     ReportException(try_catch);
387     exit(1);
388   }
389
390   Local<Value> result = script->Run();
391   if (result.IsEmpty()) {
392     ReportException(try_catch);
393     exit(1);
394   }
395
396   return scope.Close(result);
397 }
398
399 static Handle<Value> ByteLength(const Arguments& args) {
400   HandleScope scope;
401
402   if (args.Length() < 1 || !args[0]->IsString()) {
403     return ThrowException(Exception::Error(String::New("Bad argument.")));
404   }
405
406   Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
407
408   return scope.Close(length);
409 }
410
411 static Handle<Value> Loop(const Arguments& args) {
412   HandleScope scope;
413
414   // TODO Probably don't need to start this each time.
415   // Avoids failing on test/mjsunit/test-eio-race3.js though
416   ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
417
418   ev_loop(EV_DEFAULT_UC_ 0);
419   return Undefined();
420 }
421
422 static Handle<Value> Unloop(const Arguments& args) {
423   fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
424   HandleScope scope;
425   int how = EVUNLOOP_ONE;
426   if (args[0]->IsString()) {
427     String::Utf8Value how_s(args[0]->ToString());
428     if (0 == strcmp(*how_s, "all")) {
429       how = EVUNLOOP_ALL;
430     }
431   }
432   ev_unloop(EV_DEFAULT_ how);
433   return Undefined();
434 }
435
436 static Handle<Value> Chdir(const Arguments& args) {
437   HandleScope scope;
438
439   if (args.Length() != 1 || !args[0]->IsString()) {
440     return ThrowException(Exception::Error(String::New("Bad argument.")));
441   }
442
443   String::Utf8Value path(args[0]->ToString());
444
445   int r = chdir(*path);
446
447   if (r != 0) {
448     return ThrowException(Exception::Error(String::New(strerror(errno))));
449   }
450
451   return Undefined();
452 }
453
454 static Handle<Value> Cwd(const Arguments& args) {
455   HandleScope scope;
456
457   char output[PATH_MAX];
458   char *r = getcwd(output, PATH_MAX);
459   if (r == NULL) {
460     return ThrowException(Exception::Error(String::New(strerror(errno))));
461   }
462   Local<String> cwd = String::New(output);
463
464   return scope.Close(cwd);
465 }
466
467 static Handle<Value> Umask(const Arguments& args){
468   HandleScope scope;
469   unsigned int old;
470   if(args.Length() < 1) {
471     old = umask(0);
472     umask((mode_t)old);
473   }
474   else if(!args[0]->IsInt32()) {
475     return ThrowException(Exception::TypeError(
476           String::New("argument must be an integer.")));
477   }
478   else {
479     old = umask((mode_t)args[0]->Uint32Value());
480   }
481   return scope.Close(Uint32::New(old));
482 }
483
484
485 static Handle<Value> GetUid(const Arguments& args) {
486   HandleScope scope;
487   int uid = getuid();
488   return scope.Close(Integer::New(uid));
489 }
490
491 static Handle<Value> GetGid(const Arguments& args) {
492   HandleScope scope;
493   int gid = getgid();
494   return scope.Close(Integer::New(gid));
495 }
496
497
498 static Handle<Value> SetGid(const Arguments& args) {
499   HandleScope scope;
500   
501   if (args.Length() < 1) {
502     return ThrowException(Exception::Error(
503           String::New("setgid requires 1 argument")));
504   }
505
506   Local<Integer> given_gid = args[0]->ToInteger();
507   int gid = given_gid->Int32Value();
508   int result;
509   if ((result = setgid(gid)) != 0) {
510     return ThrowException(Exception::Error(String::New(strerror(errno))));
511   }
512   return Undefined();
513 }
514
515 static Handle<Value> SetUid(const Arguments& args) {
516   HandleScope scope;
517
518   if (args.Length() < 1) {
519     return ThrowException(Exception::Error(
520           String::New("setuid requires 1 argument")));
521   }
522
523   Local<Integer> given_uid = args[0]->ToInteger();
524   int uid = given_uid->Int32Value();
525   int result;
526   if ((result = setuid(uid)) != 0) {
527     return ThrowException(Exception::Error(String::New(strerror(errno))));
528   }
529   return Undefined();
530 }
531
532
533 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
534   HandleScope scope;
535   fflush(stderr);
536   Stdio::Flush();
537   exit(args[0]->IntegerValue());
538   return Undefined();
539 }
540
541 #ifdef __sun
542 #define HAVE_GETMEM 1
543 #include <unistd.h> /* getpagesize() */
544
545 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
546 #define PROCFS_FILE_OFFSET_BITS_HACK 1
547 #undef _FILE_OFFSET_BITS
548 #else
549 #define PROCFS_FILE_OFFSET_BITS_HACK 0
550 #endif
551
552 #include <procfs.h>
553
554 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
555 #define _FILE_OFFSET_BITS 64
556 #endif
557
558 int getmem(size_t *rss, size_t *vsize) {
559   pid_t pid = getpid();
560
561   size_t page_size = getpagesize();
562   char pidpath[1024];
563   sprintf(pidpath, "/proc/%d/psinfo", pid);
564
565   psinfo_t psinfo;
566   FILE *f = fopen(pidpath, "r");
567   if (!f) return -1;
568
569   if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
570     fclose (f);
571     return -1;
572   }
573
574   /* XXX correct? */
575
576   *vsize = (size_t) psinfo.pr_size * page_size;
577   *rss = (size_t) psinfo.pr_rssize * 1024;
578
579   fclose (f);
580
581   return 0;
582 }
583 #endif
584
585
586 #ifdef __FreeBSD__
587 #define HAVE_GETMEM 1
588 #include <kvm.h>
589 #include <sys/param.h>
590 #include <sys/sysctl.h>
591 #include <sys/user.h>
592 #include <fcntl.h>
593 #include <unistd.h>
594
595 int getmem(size_t *rss, size_t *vsize) {
596   kvm_t *kd = NULL;
597   struct kinfo_proc *kinfo = NULL;
598   pid_t pid;
599   int nprocs;
600   size_t page_size = getpagesize();
601
602   pid = getpid();
603
604   kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
605   if (kd == NULL) goto error;
606
607   kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
608   if (kinfo == NULL) goto error;
609
610   *rss = kinfo->ki_rssize * page_size;
611   *vsize = kinfo->ki_size;
612
613   kvm_close(kd);
614
615   return 0;
616
617 error:
618   if (kd) kvm_close(kd);
619   return -1;
620 }
621 #endif  // __FreeBSD__
622
623
624 #ifdef __APPLE__
625 #define HAVE_GETMEM 1
626 /* Researched by Tim Becker and Michael Knight
627  * http://blog.kuriositaet.de/?p=257
628  */
629
630 #include <mach/task.h>
631 #include <mach/mach_init.h>
632
633 int getmem(size_t *rss, size_t *vsize) {
634   struct task_basic_info t_info;
635   mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
636
637   int r = task_info(mach_task_self(),
638                     TASK_BASIC_INFO,
639                     (task_info_t)&t_info,
640                     &t_info_count);
641
642   if (r != KERN_SUCCESS) return -1;
643
644   *rss = t_info.resident_size;
645   *vsize  = t_info.virtual_size;
646
647   return 0;
648 }
649 #endif  // __APPLE__
650
651 #ifdef __linux__
652 # define HAVE_GETMEM 1
653 # include <sys/param.h> /* for MAXPATHLEN */
654
655 int getmem(size_t *rss, size_t *vsize) {
656   FILE *f = fopen("/proc/self/stat", "r");
657   if (!f) return -1;
658
659   int itmp;
660   char ctmp;
661   char buffer[MAXPATHLEN];
662   size_t page_size = getpagesize();
663
664   /* PID */
665   if (fscanf(f, "%d ", &itmp) == 0) goto error;
666   /* Exec file */
667   if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
668   /* State */
669   if (fscanf (f, "%c ", &ctmp) == 0) goto error;
670   /* Parent process */
671   if (fscanf (f, "%d ", &itmp) == 0) goto error;
672   /* Process group */
673   if (fscanf (f, "%d ", &itmp) == 0) goto error;
674   /* Session id */
675   if (fscanf (f, "%d ", &itmp) == 0) goto error;
676   /* TTY */
677   if (fscanf (f, "%d ", &itmp) == 0) goto error;
678   /* TTY owner process group */
679   if (fscanf (f, "%d ", &itmp) == 0) goto error;
680   /* Flags */
681   if (fscanf (f, "%u ", &itmp) == 0) goto error;
682   /* Minor faults (no memory page) */
683   if (fscanf (f, "%u ", &itmp) == 0) goto error;
684   /* Minor faults, children */
685   if (fscanf (f, "%u ", &itmp) == 0) goto error;
686   /* Major faults (memory page faults) */
687   if (fscanf (f, "%u ", &itmp) == 0) goto error;
688   /* Major faults, children */
689   if (fscanf (f, "%u ", &itmp) == 0) goto error;
690   /* utime */
691   if (fscanf (f, "%d ", &itmp) == 0) goto error;
692   /* stime */
693   if (fscanf (f, "%d ", &itmp) == 0) goto error;
694   /* utime, children */
695   if (fscanf (f, "%d ", &itmp) == 0) goto error;
696   /* stime, children */
697   if (fscanf (f, "%d ", &itmp) == 0) goto error;
698   /* jiffies remaining in current time slice */
699   if (fscanf (f, "%d ", &itmp) == 0) goto error;
700   /* 'nice' value */
701   if (fscanf (f, "%d ", &itmp) == 0) goto error;
702   /* jiffies until next timeout */
703   if (fscanf (f, "%u ", &itmp) == 0) goto error;
704   /* jiffies until next SIGALRM */
705   if (fscanf (f, "%u ", &itmp) == 0) goto error;
706   /* start time (jiffies since system boot) */
707   if (fscanf (f, "%d ", &itmp) == 0) goto error;
708
709   /* Virtual memory size */
710   if (fscanf (f, "%u ", &itmp) == 0) goto error;
711   *vsize = (size_t) itmp;
712
713   /* Resident set size */
714   if (fscanf (f, "%u ", &itmp) == 0) goto error;
715   *rss = (size_t) itmp * page_size;
716
717   /* rlim */
718   if (fscanf (f, "%u ", &itmp) == 0) goto error;
719   /* Start of text */
720   if (fscanf (f, "%u ", &itmp) == 0) goto error;
721   /* End of text */
722   if (fscanf (f, "%u ", &itmp) == 0) goto error;
723   /* Start of stack */
724   if (fscanf (f, "%u ", &itmp) == 0) goto error;
725
726   fclose (f);
727
728   return 0;
729
730 error:
731   fclose (f);
732   return -1;
733 }
734 #endif  // __linux__
735
736 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
737   HandleScope scope;
738
739 #ifndef HAVE_GETMEM
740   return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
741 #else
742   size_t rss, vsize;
743
744   int r = getmem(&rss, &vsize);
745
746   if (r != 0) {
747     return ThrowException(Exception::Error(String::New(strerror(errno))));
748   }
749
750   Local<Object> info = Object::New();
751
752   if (rss_symbol.IsEmpty()) {
753     rss_symbol = NODE_PSYMBOL("rss");
754     vsize_symbol = NODE_PSYMBOL("vsize");
755     heap_total_symbol = NODE_PSYMBOL("heapTotal");
756     heap_used_symbol = NODE_PSYMBOL("heapUsed");
757   }
758
759   info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
760   info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
761
762   // V8 memory usage
763   HeapStatistics v8_heap_stats;
764   V8::GetHeapStatistics(&v8_heap_stats);
765   info->Set(heap_total_symbol,
766             Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
767   info->Set(heap_used_symbol,
768             Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
769
770   return scope.Close(info);
771 #endif
772 }
773
774
775 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
776   HandleScope scope;
777
778   if (args.Length() < 1 || !args[0]->IsNumber()) {
779     return ThrowException(Exception::Error(String::New("Bad argument.")));
780   }
781
782   pid_t pid = args[0]->IntegerValue();
783
784   int sig = SIGTERM;
785
786   if (args.Length() >= 2) {
787     if (args[1]->IsNumber()) {
788       sig = args[1]->Int32Value();
789     } else if (args[1]->IsString()) {
790       Local<String> signame = args[1]->ToString();
791
792       Local<Value> sig_v = process->Get(signame);
793       if (!sig_v->IsNumber()) {
794         return ThrowException(Exception::Error(String::New("Unknown signal")));
795       }
796       sig = sig_v->Int32Value();
797     }
798   }
799
800   int r = kill(pid, sig);
801
802   if (r != 0) {
803     return ThrowException(Exception::Error(String::New(strerror(errno))));
804   }
805
806   return Undefined();
807 }
808
809 typedef void (*extInit)(Handle<Object> exports);
810
811 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
812 // objects.
813 Handle<Value> DLOpen(const v8::Arguments& args) {
814   HandleScope scope;
815
816   if (args.Length() < 2) return Undefined();
817
818   String::Utf8Value filename(args[0]->ToString()); // Cast
819   Local<Object> target = args[1]->ToObject(); // Cast
820
821   // Actually call dlopen().
822   // FIXME: This is a blocking function and should be called asynchronously!
823   // This function should be moved to file.cc and use libeio to make this
824   // system call.
825   void *handle = dlopen(*filename, RTLD_LAZY);
826
827   // Handle errors.
828   if (handle == NULL) {
829     Local<Value> exception = Exception::Error(String::New(dlerror()));
830     return ThrowException(exception);
831   }
832
833   // Get the init() function from the dynamically shared object.
834   void *init_handle = dlsym(handle, "init");
835   // Error out if not found.
836   if (init_handle == NULL) {
837     Local<Value> exception =
838       Exception::Error(String::New("No 'init' symbol found in module."));
839     return ThrowException(exception);
840   }
841   extInit init = (extInit)(init_handle); // Cast
842
843   // Execute the C++ module
844   init(target);
845
846   return Undefined();
847 }
848
849 // evalcx(code, sandbox={})
850 // Executes code in a new context
851 Handle<Value> EvalCX(const Arguments& args) {
852   HandleScope scope;
853
854   Local<String> code = args[0]->ToString();
855   Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
856                                             : Object::New();
857   // Create the new context
858   Persistent<Context> context = Context::New();
859
860   // Copy objects from global context, to our brand new context
861   Handle<Array> keys = sandbox->GetPropertyNames();
862
863   int i;
864   for (i = 0; i < keys->Length(); i++) {
865     Handle<String> key = keys->Get(Integer::New(i))->ToString();
866     Handle<Value> value = sandbox->Get(key);
867     context->Global()->Set(key, value->ToObject()->Clone());
868   }
869
870   // Enter and compile script
871   context->Enter();
872
873   // Catch errors
874   TryCatch try_catch;
875
876   Local<Script> script = Script::Compile(code, String::New("evalcx"));
877   Handle<Value> result;
878
879   if (script.IsEmpty()) {
880     result = ThrowException(try_catch.Exception());
881   } else {
882     result = script->Run();
883     if (result.IsEmpty()) {
884       result = ThrowException(try_catch.Exception());
885     }
886   }
887
888   // Clean up, clean up, everybody everywhere!
889   context->DetachGlobal();
890   context->Exit();
891   context.Dispose();
892
893   return scope.Close(result);
894 }
895
896 Handle<Value> Compile(const Arguments& args) {
897   HandleScope scope;
898
899   if (args.Length() < 2) {
900     return ThrowException(Exception::TypeError(
901           String::New("needs two arguments.")));
902   }
903
904   Local<String> source = args[0]->ToString();
905   Local<String> filename = args[1]->ToString();
906
907   TryCatch try_catch;
908
909   Local<Script> script = Script::Compile(source, filename);
910   if (try_catch.HasCaught()) {
911     // Hack because I can't get a proper stacktrace on SyntaxError
912     ReportException(try_catch, true);
913     exit(1);
914   }
915
916   Local<Value> result = script->Run();
917   if (try_catch.HasCaught()) return try_catch.ReThrow();
918
919   return scope.Close(result);
920 }
921
922 static void OnFatalError(const char* location, const char* message) {
923   if (location) {
924     fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
925   } else {
926     fprintf(stderr, "FATAL ERROR: %s\n", message);
927   }
928   exit(1);
929 }
930
931 static int uncaught_exception_counter = 0;
932
933 void FatalException(TryCatch &try_catch) {
934   HandleScope scope;
935
936   // Check if uncaught_exception_counter indicates a recursion
937   if (uncaught_exception_counter > 0) {
938     ReportException(try_catch);
939     exit(1);
940   }
941
942   if (listeners_symbol.IsEmpty()) {
943     listeners_symbol = NODE_PSYMBOL("listeners");
944     uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
945     emit_symbol = NODE_PSYMBOL("emit");
946   }
947
948   Local<Value> listeners_v = process->Get(listeners_symbol);
949   assert(listeners_v->IsFunction());
950
951   Local<Function> listeners = Local<Function>::Cast(listeners_v);
952
953   Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
954   Local<Value> argv[1] = { uncaught_exception_symbol_l  };
955   Local<Value> ret = listeners->Call(process, 1, argv);
956
957   assert(ret->IsArray());
958
959   Local<Array> listener_array = Local<Array>::Cast(ret);
960
961   uint32_t length = listener_array->Length();
962   // Report and exit if process has no "uncaughtException" listener
963   if (length == 0) {
964     ReportException(try_catch);
965     exit(1);
966   }
967
968   // Otherwise fire the process "uncaughtException" event
969   Local<Value> emit_v = process->Get(emit_symbol);
970   assert(emit_v->IsFunction());
971
972   Local<Function> emit = Local<Function>::Cast(emit_v);
973
974   Local<Value> error = try_catch.Exception();
975   Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
976
977   uncaught_exception_counter++;
978   emit->Call(process, 2, event_argv);
979   // Decrement so we know if the next exception is a recursion or not
980   uncaught_exception_counter--;
981 }
982
983
984 static ev_async debug_watcher;
985 volatile static bool debugger_msg_pending = false;
986
987 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
988   HandleScope scope;
989   assert(watcher == &debug_watcher);
990   assert(revents == EV_ASYNC);
991   Debug::ProcessDebugMessages();
992 }
993
994 static void DebugMessageDispatch(void) {
995   // This function is called from V8's debug thread when a debug TCP client
996   // has sent a message.
997
998   // Send a signal to our main thread saying that it should enter V8 to
999   // handle the message.
1000   debugger_msg_pending = true;
1001   ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1002 }
1003
1004 static Handle<Value> CheckBreak(const Arguments& args) {
1005   HandleScope scope;
1006
1007   // TODO FIXME This function is a hack to wait until V8 is ready to accept
1008   // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1009   // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1010   // get it to halt until Eclipse connects.
1011
1012   if (!debug_wait_connect)
1013     return Undefined();
1014
1015   printf("Waiting for remote debugger connection...\n");
1016
1017   const int halfSecond = 50;
1018   const int tenMs=10000;
1019   debugger_msg_pending = false;
1020   for (;;) {
1021     if (debugger_msg_pending) {
1022       Debug::DebugBreak();
1023       Debug::ProcessDebugMessages();
1024       debugger_msg_pending = false;
1025
1026       // wait for 500 msec of silence from remote debugger
1027       int cnt = halfSecond;
1028         while (cnt --) {
1029         debugger_msg_pending = false;
1030         usleep(tenMs);
1031         if (debugger_msg_pending) {
1032           debugger_msg_pending = false;
1033           cnt = halfSecond;
1034         }
1035       }
1036       break;
1037     }
1038     usleep(tenMs);
1039   }
1040   return Undefined();
1041 }
1042
1043
1044 static void Load(int argc, char *argv[]) {
1045   HandleScope scope;
1046
1047   Local<FunctionTemplate> process_template = FunctionTemplate::New();
1048   node::EventEmitter::Initialize(process_template);
1049
1050   process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1051
1052   // Add a reference to the global object
1053   Local<Object> global = Context::GetCurrent()->Global();
1054   process->Set(String::NewSymbol("global"), global);
1055
1056   // process.version
1057   process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1058   // process.installPrefix
1059   process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1060
1061   // process.platform
1062 #define xstr(s) str(s)
1063 #define str(s) #s
1064   process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1065
1066   // process.argv
1067   int i, j;
1068   Local<Array> arguments = Array::New(argc - option_end_index + 1);
1069   arguments->Set(Integer::New(0), String::New(argv[0]));
1070   for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1071     Local<String> arg = String::New(argv[i]);
1072     arguments->Set(Integer::New(j), arg);
1073   }
1074   // assign it
1075   process->Set(String::NewSymbol("ARGV"), arguments);
1076   process->Set(String::NewSymbol("argv"), arguments);
1077
1078   // create process.env
1079   Local<Object> env = Object::New();
1080   for (i = 0; environ[i]; i++) {
1081     // skip entries without a '=' character
1082     for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1083     // create the v8 objects
1084     Local<String> field = String::New(environ[i], j);
1085     Local<String> value = Local<String>();
1086     if (environ[i][j] == '=') {
1087       value = String::New(environ[i]+j+1);
1088     }
1089     // assign them
1090     env->Set(field, value);
1091   }
1092   // assign process.ENV
1093   process->Set(String::NewSymbol("ENV"), env);
1094   process->Set(String::NewSymbol("env"), env);
1095
1096   process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1097
1098   // define various internal methods
1099   NODE_SET_METHOD(process, "loop", Loop);
1100   NODE_SET_METHOD(process, "unloop", Unloop);
1101   NODE_SET_METHOD(process, "evalcx", EvalCX);
1102   NODE_SET_METHOD(process, "compile", Compile);
1103   NODE_SET_METHOD(process, "_byteLength", ByteLength);
1104   NODE_SET_METHOD(process, "reallyExit", Exit);
1105   NODE_SET_METHOD(process, "chdir", Chdir);
1106   NODE_SET_METHOD(process, "cwd", Cwd);
1107   NODE_SET_METHOD(process, "getuid", GetUid);
1108   NODE_SET_METHOD(process, "setuid", SetUid);
1109
1110   NODE_SET_METHOD(process, "setgid", SetGid);
1111   NODE_SET_METHOD(process, "getgid", GetGid);
1112
1113   NODE_SET_METHOD(process, "umask", Umask);
1114   NODE_SET_METHOD(process, "dlopen", DLOpen);
1115   NODE_SET_METHOD(process, "kill", Kill);
1116   NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1117   NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1118
1119   // Assign the EventEmitter. It was created in main().
1120   process->Set(String::NewSymbol("EventEmitter"),
1121                EventEmitter::constructor_template->GetFunction());
1122
1123   // Initialize the stats object
1124   Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1125   stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1126   process->Set(String::NewSymbol("Stats"),
1127       stats_constructor_template->GetFunction());
1128
1129
1130   // Initialize the C++ modules..................filename of module
1131   IdleWatcher::Initialize(process);            // idle_watcher.cc
1132   Stdio::Initialize(process);                  // stdio.cc
1133   Timer::Initialize(process);                  // timer.cc
1134   SignalHandler::Initialize(process);          // signal_handler.cc
1135   Stat::Initialize(process);                   // stat.cc
1136   ChildProcess::Initialize(process);           // child_process.cc
1137   DefineConstants(process);                    // constants.cc
1138   // Create node.dns
1139   Local<Object> dns = Object::New();
1140   process->Set(String::NewSymbol("dns"), dns);
1141   DNS::Initialize(dns);                         // dns.cc
1142   Local<Object> fs = Object::New();
1143   process->Set(String::NewSymbol("fs"), fs);
1144   File::Initialize(fs);                         // file.cc
1145   // Create node.tcp. Note this separate from lib/tcp.js which is the public
1146   // frontend.
1147   Local<Object> tcp = Object::New();
1148   process->Set(String::New("tcp"), tcp);
1149   Server::Initialize(tcp);                      // tcp.cc
1150   Connection::Initialize(tcp);                  // tcp.cc
1151   // Create node.http.  Note this separate from lib/http.js which is the
1152   // public frontend.
1153   Local<Object> http = Object::New();
1154   process->Set(String::New("http"), http);
1155   HTTPServer::Initialize(http);                 // http.cc
1156   HTTPConnection::Initialize(http);             // http.cc
1157
1158
1159
1160   // Compile, execute the src/node.js file. (Which was included as static C
1161   // string in node_natives.h. 'natve_node' is the string containing that
1162   // source code.)
1163
1164   // The node.js file returns a function 'f'
1165
1166 #ifndef NDEBUG
1167   TryCatch try_catch;
1168 #endif
1169
1170   Local<Value> f_value = ExecuteString(String::New(native_node),
1171                                        String::New("node.js"));
1172 #ifndef NDEBUG
1173   if (try_catch.HasCaught())  {
1174     ReportException(try_catch);
1175     exit(10);
1176   }
1177 #endif
1178   assert(f_value->IsFunction());
1179   Local<Function> f = Local<Function>::Cast(f_value);
1180
1181   // Now we call 'f' with the 'process' variable that we've built up with
1182   // all our bindings. Inside node.js we'll take care of assigning things to
1183   // their places.
1184
1185   // We start the process this way in order to be more modular. Developers
1186   // who do not like how 'src/node.js' setups the module system but do like
1187   // Node's I/O bindings may want to replace 'f' with their own function.
1188
1189   Local<Value> args[1] = { Local<Value>::New(process) };
1190
1191   f->Call(global, 1, args);
1192
1193 #ifndef NDEBUG
1194   if (try_catch.HasCaught())  {
1195     ReportException(try_catch);
1196     exit(11);
1197   }
1198 #endif
1199 }
1200
1201 static void PrintHelp();
1202
1203 static void ParseDebugOpt(const char* arg) {
1204   const char *p = 0;
1205
1206   use_debug_agent = true;
1207   if (!strcmp (arg, "--debug-brk")) {
1208     debug_wait_connect = true;
1209     return;
1210   } else if (!strcmp(arg, "--debug")) {
1211     return;
1212   } else if (strstr(arg, "--debug-brk=") == arg) {
1213     debug_wait_connect = true;
1214     p = 1 + strchr(arg, '=');
1215     debug_port = atoi(p);
1216   } else if (strstr(arg, "--debug=") == arg) {
1217     p = 1 + strchr(arg, '=');
1218     debug_port = atoi(p);
1219   }
1220   if (p && debug_port > 1024 && debug_port <  65536)
1221       return;
1222
1223   fprintf(stderr, "Bad debug option.\n");
1224   if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1225
1226   PrintHelp();
1227   exit(1);
1228 }
1229
1230 static void PrintHelp() {
1231   printf("Usage: node [options] script.js [arguments] \n"
1232          "Options:\n"
1233          "  -v, --version      print node's version\n"
1234          "  --debug[=port]     enable remote debugging via given TCP port\n"
1235          "                     without stopping the execution\n"
1236          "  --debug-brk[=port] as above, but break in script.js and\n"
1237          "                     wait for remote debugger to connect\n"
1238          "  --v8-options       print v8 command line options\n"
1239          "  --vars             print various compiled-in variables\n"
1240          "\n"
1241          "Enviromental variables:\n"
1242          "NODE_PATH            ':'-separated list of directories\n"
1243          "                     prefixed to the module search path,\n"
1244          "                     require.paths.\n"
1245          "NODE_DEBUG           Print additional debugging output.\n"
1246          "\n"
1247          "Documentation can be found at http://nodejs.org/api.html"
1248          " or with 'man node'\n");
1249 }
1250
1251 // Parse node command line arguments.
1252 static void ParseArgs(int *argc, char **argv) {
1253   // TODO use parse opts
1254   for (int i = 1; i < *argc; i++) {
1255     const char *arg = argv[i];
1256     if (strstr(arg, "--debug") == arg) {
1257       ParseDebugOpt(arg);
1258       argv[i] = const_cast<char*>("");
1259       option_end_index = i;
1260     } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1261       printf("%s\n", NODE_VERSION);
1262       exit(0);
1263     } else if (strcmp(arg, "--vars") == 0) {
1264       printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1265       printf("NODE_LIBRARIES_PREFIX: %s/%s\n", NODE_PREFIX, "lib/node/libraries");
1266       printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1267       exit(0);
1268     } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1269       PrintHelp();
1270       exit(0);
1271     } else if (strcmp(arg, "--v8-options") == 0) {
1272       argv[i] = const_cast<char*>("--help");
1273       option_end_index = i+1;
1274     } else if (argv[i][0] != '-') {
1275       option_end_index = i-1;
1276       break;
1277     }
1278   }
1279 }
1280
1281 }  // namespace node
1282
1283
1284 int main(int argc, char *argv[]) {
1285   // Parse a few arguments which are specific to Node.
1286   node::ParseArgs(&argc, argv);
1287   // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1288   // in the command line))
1289   V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1290
1291   // Error out if we don't have a script argument.
1292   if (argc < 2) {
1293     fprintf(stderr, "No script was specified.\n");
1294     node::PrintHelp();
1295     return 1;
1296   }
1297
1298   // Ignore the SIGPIPE
1299   evcom_ignore_sigpipe();
1300
1301   // Initialize the default ev loop.
1302 #ifdef __sun
1303   // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1304   // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1305   ev_default_loop(EVBACKEND_SELECT);
1306 #else
1307   ev_default_loop(EVFLAG_AUTO);
1308 #endif
1309
1310
1311   ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1312   // Set the gc_timer to max priority so that it runs before all other
1313   // watchers. In this way it can check if the 'tick' has other pending
1314   // watchers by using ev_pending_count() - if it ran with lower priority
1315   // then the other watchers might run before it - not giving us good idea
1316   // of loop idleness.
1317   ev_set_priority(&node::gc_timer, EV_MAXPRI);
1318   ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1319   ev_unref(EV_DEFAULT_UC);
1320
1321
1322   // Setup the EIO thread pool
1323   { // It requires 3, yes 3, watchers.
1324     ev_idle_init(&node::eio_poller, node::DoPoll);
1325
1326     ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1327     ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1328     ev_unref(EV_DEFAULT_UC);
1329
1330     ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1331     ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1332     ev_unref(EV_DEFAULT_UC);
1333
1334     eio_init(node::EIOWantPoll, node::EIODonePoll);
1335     // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1336     // race conditions. See test/mjsunit/test-eio-race.js
1337     eio_set_max_poll_reqs(10);
1338   }
1339
1340   V8::Initialize();
1341   HandleScope handle_scope;
1342
1343   V8::SetFatalErrorHandler(node::OnFatalError);
1344
1345   // If the --debug flag was specified then initialize the debug thread.
1346   if (node::use_debug_agent) {
1347     // Initialize the async watcher for receiving messages from the debug
1348     // thread and marshal it into the main thread. DebugMessageCallback()
1349     // is called from the main thread to execute a random bit of javascript
1350     // - which will give V8 control so it can handle whatever new message
1351     // had been received on the debug thread.
1352     ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1353     ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1354     // Set the callback DebugMessageDispatch which is called from the debug
1355     // thread.
1356     Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1357     // Start the async watcher.
1358     ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1359     // unref it so that we exit the event loop despite it being active.
1360     ev_unref(EV_DEFAULT_UC);
1361
1362     // Start the debug thread and it's associated TCP server on port 5858.
1363     bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1364
1365     // Crappy check that everything went well. FIXME
1366     assert(r);
1367     // Print out some information.
1368     printf("debugger listening on port %d\n", node::debug_port);
1369   }
1370
1371   // Create the one and only Context.
1372   Persistent<Context> context = Context::New();
1373   Context::Scope context_scope(context);
1374
1375   // Create all the objects, load modules, do everything.
1376   // so your next reading stop should be node::Load()!
1377   node::Load(argc, argv);
1378
1379   node::Stdio::Flush();
1380
1381 #ifndef NDEBUG
1382   // Clean up.
1383   context.Dispose();
1384   V8::Dispose();
1385 #endif  // NDEBUG
1386   return 0;
1387 }
1388