[V8] Generalize external object resources
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / api.cc
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #include "v8.h"
29
30 #include "api.h"
31
32 #include "arguments.h"
33 #include "bootstrapper.h"
34 #include "compiler.h"
35 #include "debug.h"
36 #include "deoptimizer.h"
37 #include "execution.h"
38 #include "flags.h"
39 #include "global-handles.h"
40 #include "heap-profiler.h"
41 #include "messages.h"
42 #include "natives.h"
43 #include "parser.h"
44 #include "platform.h"
45 #include "profile-generator-inl.h"
46 #include "runtime-profiler.h"
47 #include "scanner-character-streams.h"
48 #include "serialize.h"
49 #include "snapshot.h"
50 #include "v8threads.h"
51 #include "version.h"
52 #include "vm-state-inl.h"
53
54 #include "../include/v8-profiler.h"
55 #include "../include/v8-testing.h"
56
57 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
58
59 #define ENTER_V8(isolate)                                        \
60   ASSERT((isolate)->IsInitialized());                           \
61   i::VMState __state__((isolate), i::OTHER)
62 #define LEAVE_V8(isolate) \
63   i::VMState __state__((isolate), i::EXTERNAL)
64
65 namespace v8 {
66
67 #define ON_BAILOUT(isolate, location, code)                        \
68   if (IsDeadCheck(isolate, location) ||                            \
69       IsExecutionTerminatingCheck(isolate)) {                      \
70     code;                                                          \
71     UNREACHABLE();                                                 \
72   }
73
74
75 #define EXCEPTION_PREAMBLE(isolate)                                         \
76   (isolate)->handle_scope_implementer()->IncrementCallDepth();              \
77   ASSERT(!(isolate)->external_caught_exception());                          \
78   bool has_pending_exception = false
79
80
81 #define EXCEPTION_BAILOUT_CHECK(isolate, value)                                \
82   do {                                                                         \
83     i::HandleScopeImplementer* handle_scope_implementer =                      \
84         (isolate)->handle_scope_implementer();                                 \
85     handle_scope_implementer->DecrementCallDepth();                            \
86     if (has_pending_exception) {                                               \
87       if (handle_scope_implementer->CallDepthIsZero() &&                       \
88           (isolate)->is_out_of_memory()) {                                     \
89         if (!(isolate)->ignore_out_of_memory())                                \
90           i::V8::FatalProcessOutOfMemory(NULL);                                \
91       }                                                                        \
92       bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero();   \
93       (isolate)->OptionalRescheduleException(call_depth_is_zero);              \
94       return value;                                                            \
95     }                                                                          \
96   } while (false)
97
98
99 #define API_ENTRY_CHECK(isolate, msg)                                          \
100   do {                                                                         \
101     if (v8::Locker::IsActive()) {                                              \
102       ApiCheck(isolate->thread_manager()->IsLockedByCurrentThread(),           \
103                msg,                                                            \
104                "Entering the V8 API without proper locking in place");         \
105     }                                                                          \
106   } while (false)
107
108
109 // --- E x c e p t i o n   B e h a v i o r ---
110
111
112 static void DefaultFatalErrorHandler(const char* location,
113                                      const char* message) {
114   i::VMState __state__(i::Isolate::Current(), i::OTHER);
115   API_Fatal(location, message);
116 }
117
118
119 static FatalErrorCallback GetFatalErrorHandler() {
120   i::Isolate* isolate = i::Isolate::Current();
121   if (isolate->exception_behavior() == NULL) {
122     isolate->set_exception_behavior(DefaultFatalErrorHandler);
123   }
124   return isolate->exception_behavior();
125 }
126
127
128 void i::FatalProcessOutOfMemory(const char* location) {
129   i::V8::FatalProcessOutOfMemory(location, false);
130 }
131
132
133 // When V8 cannot allocated memory FatalProcessOutOfMemory is called.
134 // The default fatal error handler is called and execution is stopped.
135 void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
136   i::HeapStats heap_stats;
137   int start_marker;
138   heap_stats.start_marker = &start_marker;
139   int new_space_size;
140   heap_stats.new_space_size = &new_space_size;
141   int new_space_capacity;
142   heap_stats.new_space_capacity = &new_space_capacity;
143   intptr_t old_pointer_space_size;
144   heap_stats.old_pointer_space_size = &old_pointer_space_size;
145   intptr_t old_pointer_space_capacity;
146   heap_stats.old_pointer_space_capacity = &old_pointer_space_capacity;
147   intptr_t old_data_space_size;
148   heap_stats.old_data_space_size = &old_data_space_size;
149   intptr_t old_data_space_capacity;
150   heap_stats.old_data_space_capacity = &old_data_space_capacity;
151   intptr_t code_space_size;
152   heap_stats.code_space_size = &code_space_size;
153   intptr_t code_space_capacity;
154   heap_stats.code_space_capacity = &code_space_capacity;
155   intptr_t map_space_size;
156   heap_stats.map_space_size = &map_space_size;
157   intptr_t map_space_capacity;
158   heap_stats.map_space_capacity = &map_space_capacity;
159   intptr_t cell_space_size;
160   heap_stats.cell_space_size = &cell_space_size;
161   intptr_t cell_space_capacity;
162   heap_stats.cell_space_capacity = &cell_space_capacity;
163   intptr_t lo_space_size;
164   heap_stats.lo_space_size = &lo_space_size;
165   int global_handle_count;
166   heap_stats.global_handle_count = &global_handle_count;
167   int weak_global_handle_count;
168   heap_stats.weak_global_handle_count = &weak_global_handle_count;
169   int pending_global_handle_count;
170   heap_stats.pending_global_handle_count = &pending_global_handle_count;
171   int near_death_global_handle_count;
172   heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
173   int free_global_handle_count;
174   heap_stats.free_global_handle_count = &free_global_handle_count;
175   intptr_t memory_allocator_size;
176   heap_stats.memory_allocator_size = &memory_allocator_size;
177   intptr_t memory_allocator_capacity;
178   heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
179   int objects_per_type[LAST_TYPE + 1] = {0};
180   heap_stats.objects_per_type = objects_per_type;
181   int size_per_type[LAST_TYPE + 1] = {0};
182   heap_stats.size_per_type = size_per_type;
183   int os_error;
184   heap_stats.os_error = &os_error;
185   int end_marker;
186   heap_stats.end_marker = &end_marker;
187   i::Isolate* isolate = i::Isolate::Current();
188   // BUG(1718):
189   // Don't use the take_snapshot since we don't support HeapIterator here
190   // without doing a special GC.
191   isolate->heap()->RecordStats(&heap_stats, false);
192   i::V8::SetFatalError();
193   FatalErrorCallback callback = GetFatalErrorHandler();
194   {
195     LEAVE_V8(isolate);
196     callback(location, "Allocation failed - process out of memory");
197   }
198   // If the callback returns, we stop execution.
199   UNREACHABLE();
200 }
201
202
203 bool Utils::ReportApiFailure(const char* location, const char* message) {
204   FatalErrorCallback callback = GetFatalErrorHandler();
205   callback(location, message);
206   i::V8::SetFatalError();
207   return false;
208 }
209
210
211 bool V8::IsDead() {
212   return i::V8::IsDead();
213 }
214
215
216 static inline bool ApiCheck(bool condition,
217                             const char* location,
218                             const char* message) {
219   return condition ? true : Utils::ReportApiFailure(location, message);
220 }
221
222
223 static bool ReportV8Dead(const char* location) {
224   FatalErrorCallback callback = GetFatalErrorHandler();
225   callback(location, "V8 is no longer usable");
226   return true;
227 }
228
229
230 static bool ReportEmptyHandle(const char* location) {
231   FatalErrorCallback callback = GetFatalErrorHandler();
232   callback(location, "Reading from empty handle");
233   return true;
234 }
235
236
237 /**
238  * IsDeadCheck checks that the vm is usable.  If, for instance, the vm has been
239  * out of memory at some point this check will fail.  It should be called on
240  * entry to all methods that touch anything in the heap, except destructors
241  * which you sometimes can't avoid calling after the vm has crashed.  Functions
242  * that call EnsureInitialized or ON_BAILOUT don't have to also call
243  * IsDeadCheck.  ON_BAILOUT has the advantage over EnsureInitialized that you
244  * can arrange to return if the VM is dead.  This is needed to ensure that no VM
245  * heap allocations are attempted on a dead VM.  EnsureInitialized has the
246  * advantage over ON_BAILOUT that it actually initializes the VM if this has not
247  * yet been done.
248  */
249 static inline bool IsDeadCheck(i::Isolate* isolate, const char* location) {
250   return !isolate->IsInitialized()
251       && i::V8::IsDead() ? ReportV8Dead(location) : false;
252 }
253
254
255 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
256   if (!isolate->IsInitialized()) return false;
257   if (isolate->has_scheduled_exception()) {
258     return isolate->scheduled_exception() ==
259         isolate->heap()->termination_exception();
260   }
261   return false;
262 }
263
264
265 static inline bool EmptyCheck(const char* location, v8::Handle<v8::Data> obj) {
266   return obj.IsEmpty() ? ReportEmptyHandle(location) : false;
267 }
268
269
270 static inline bool EmptyCheck(const char* location, const v8::Data* obj) {
271   return (obj == 0) ? ReportEmptyHandle(location) : false;
272 }
273
274 // --- S t a t i c s ---
275
276
277 static bool InitializeHelper() {
278   if (i::Snapshot::Initialize()) return true;
279   return i::V8::Initialize(NULL);
280 }
281
282
283 static inline bool EnsureInitializedForIsolate(i::Isolate* isolate,
284                                                const char* location) {
285   if (IsDeadCheck(isolate, location)) return false;
286   if (isolate != NULL) {
287     if (isolate->IsInitialized()) return true;
288   }
289   ASSERT(isolate == i::Isolate::Current());
290   return ApiCheck(InitializeHelper(), location, "Error initializing V8");
291 }
292
293 // Some initializing API functions are called early and may be
294 // called on a thread different from static initializer thread.
295 // If Isolate API is used, Isolate::Enter() will initialize TLS so
296 // Isolate::Current() works. If it's a legacy case, then the thread
297 // may not have TLS initialized yet. However, in initializing APIs it
298 // may be too early to call EnsureInitialized() - some pre-init
299 // parameters still have to be configured.
300 static inline i::Isolate* EnterIsolateIfNeeded() {
301   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
302   if (isolate != NULL)
303     return isolate;
304
305   i::Isolate::EnterDefaultIsolate();
306   isolate = i::Isolate::Current();
307   return isolate;
308 }
309
310
311 StartupDataDecompressor::StartupDataDecompressor()
312     : raw_data(i::NewArray<char*>(V8::GetCompressedStartupDataCount())) {
313   for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
314     raw_data[i] = NULL;
315   }
316 }
317
318
319 StartupDataDecompressor::~StartupDataDecompressor() {
320   for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
321     i::DeleteArray(raw_data[i]);
322   }
323   i::DeleteArray(raw_data);
324 }
325
326
327 int StartupDataDecompressor::Decompress() {
328   int compressed_data_count = V8::GetCompressedStartupDataCount();
329   StartupData* compressed_data =
330       i::NewArray<StartupData>(compressed_data_count);
331   V8::GetCompressedStartupData(compressed_data);
332   for (int i = 0; i < compressed_data_count; ++i) {
333     char* decompressed = raw_data[i] =
334         i::NewArray<char>(compressed_data[i].raw_size);
335     if (compressed_data[i].compressed_size != 0) {
336       int result = DecompressData(decompressed,
337                                   &compressed_data[i].raw_size,
338                                   compressed_data[i].data,
339                                   compressed_data[i].compressed_size);
340       if (result != 0) return result;
341     } else {
342       ASSERT_EQ(0, compressed_data[i].raw_size);
343     }
344     compressed_data[i].data = decompressed;
345   }
346   V8::SetDecompressedStartupData(compressed_data);
347   return 0;
348 }
349
350
351 StartupData::CompressionAlgorithm V8::GetCompressedStartupDataAlgorithm() {
352 #ifdef COMPRESS_STARTUP_DATA_BZ2
353   return StartupData::kBZip2;
354 #else
355   return StartupData::kUncompressed;
356 #endif
357 }
358
359
360 enum CompressedStartupDataItems {
361   kSnapshot = 0,
362   kSnapshotContext,
363   kLibraries,
364   kExperimentalLibraries,
365   kCompressedStartupDataCount
366 };
367
368 int V8::GetCompressedStartupDataCount() {
369 #ifdef COMPRESS_STARTUP_DATA_BZ2
370   return kCompressedStartupDataCount;
371 #else
372   return 0;
373 #endif
374 }
375
376
377 void V8::GetCompressedStartupData(StartupData* compressed_data) {
378 #ifdef COMPRESS_STARTUP_DATA_BZ2
379   compressed_data[kSnapshot].data =
380       reinterpret_cast<const char*>(i::Snapshot::data());
381   compressed_data[kSnapshot].compressed_size = i::Snapshot::size();
382   compressed_data[kSnapshot].raw_size = i::Snapshot::raw_size();
383
384   compressed_data[kSnapshotContext].data =
385       reinterpret_cast<const char*>(i::Snapshot::context_data());
386   compressed_data[kSnapshotContext].compressed_size =
387       i::Snapshot::context_size();
388   compressed_data[kSnapshotContext].raw_size = i::Snapshot::context_raw_size();
389
390   i::Vector<const i::byte> libraries_source = i::Natives::GetScriptsSource();
391   compressed_data[kLibraries].data =
392       reinterpret_cast<const char*>(libraries_source.start());
393   compressed_data[kLibraries].compressed_size = libraries_source.length();
394   compressed_data[kLibraries].raw_size = i::Natives::GetRawScriptsSize();
395
396   i::Vector<const i::byte> exp_libraries_source =
397       i::ExperimentalNatives::GetScriptsSource();
398   compressed_data[kExperimentalLibraries].data =
399       reinterpret_cast<const char*>(exp_libraries_source.start());
400   compressed_data[kExperimentalLibraries].compressed_size =
401       exp_libraries_source.length();
402   compressed_data[kExperimentalLibraries].raw_size =
403       i::ExperimentalNatives::GetRawScriptsSize();
404 #endif
405 }
406
407
408 void V8::SetDecompressedStartupData(StartupData* decompressed_data) {
409 #ifdef COMPRESS_STARTUP_DATA_BZ2
410   ASSERT_EQ(i::Snapshot::raw_size(), decompressed_data[kSnapshot].raw_size);
411   i::Snapshot::set_raw_data(
412       reinterpret_cast<const i::byte*>(decompressed_data[kSnapshot].data));
413
414   ASSERT_EQ(i::Snapshot::context_raw_size(),
415             decompressed_data[kSnapshotContext].raw_size);
416   i::Snapshot::set_context_raw_data(
417       reinterpret_cast<const i::byte*>(
418           decompressed_data[kSnapshotContext].data));
419
420   ASSERT_EQ(i::Natives::GetRawScriptsSize(),
421             decompressed_data[kLibraries].raw_size);
422   i::Vector<const char> libraries_source(
423       decompressed_data[kLibraries].data,
424       decompressed_data[kLibraries].raw_size);
425   i::Natives::SetRawScriptsSource(libraries_source);
426
427   ASSERT_EQ(i::ExperimentalNatives::GetRawScriptsSize(),
428             decompressed_data[kExperimentalLibraries].raw_size);
429   i::Vector<const char> exp_libraries_source(
430       decompressed_data[kExperimentalLibraries].data,
431       decompressed_data[kExperimentalLibraries].raw_size);
432   i::ExperimentalNatives::SetRawScriptsSource(exp_libraries_source);
433 #endif
434 }
435
436
437 void V8::SetFatalErrorHandler(FatalErrorCallback that) {
438   i::Isolate* isolate = EnterIsolateIfNeeded();
439   isolate->set_exception_behavior(that);
440 }
441
442
443 void V8::SetAllowCodeGenerationFromStringsCallback(
444     AllowCodeGenerationFromStringsCallback callback) {
445   i::Isolate* isolate = EnterIsolateIfNeeded();
446   isolate->set_allow_code_gen_callback(callback);
447 }
448
449
450 #ifdef DEBUG
451 void ImplementationUtilities::ZapHandleRange(i::Object** begin,
452                                              i::Object** end) {
453   i::HandleScope::ZapRange(begin, end);
454 }
455 #endif
456
457
458 void V8::SetFlagsFromString(const char* str, int length) {
459   i::FlagList::SetFlagsFromString(str, length);
460 }
461
462
463 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
464   i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
465 }
466
467
468 v8::Handle<Value> ThrowException(v8::Handle<v8::Value> value) {
469   i::Isolate* isolate = i::Isolate::Current();
470   if (IsDeadCheck(isolate, "v8::ThrowException()")) {
471     return v8::Handle<Value>();
472   }
473   ENTER_V8(isolate);
474   // If we're passed an empty handle, we throw an undefined exception
475   // to deal more gracefully with out of memory situations.
476   if (value.IsEmpty()) {
477     isolate->ScheduleThrow(isolate->heap()->undefined_value());
478   } else {
479     isolate->ScheduleThrow(*Utils::OpenHandle(*value));
480   }
481   return v8::Undefined();
482 }
483
484
485 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
486
487
488 RegisteredExtension::RegisteredExtension(Extension* extension)
489     : extension_(extension), state_(UNVISITED) { }
490
491
492 void RegisteredExtension::Register(RegisteredExtension* that) {
493   that->next_ = first_extension_;
494   first_extension_ = that;
495 }
496
497
498 void RegisterExtension(Extension* that) {
499   RegisteredExtension* extension = new RegisteredExtension(that);
500   RegisteredExtension::Register(extension);
501 }
502
503
504 Extension::Extension(const char* name,
505                      const char* source,
506                      int dep_count,
507                      const char** deps,
508                      int source_length)
509     : name_(name),
510       source_length_(source_length >= 0 ?
511                   source_length : (source ? strlen(source) : 0)),
512       source_(source, source_length_),
513       dep_count_(dep_count),
514       deps_(deps),
515       auto_enable_(false) { }
516
517
518 v8::Handle<Primitive> Undefined() {
519   i::Isolate* isolate = i::Isolate::Current();
520   if (!EnsureInitializedForIsolate(isolate, "v8::Undefined()")) {
521     return v8::Handle<v8::Primitive>();
522   }
523   return v8::Handle<Primitive>(ToApi<Primitive>(
524       isolate->factory()->undefined_value()));
525 }
526
527
528 v8::Handle<Primitive> Null() {
529   i::Isolate* isolate = i::Isolate::Current();
530   if (!EnsureInitializedForIsolate(isolate, "v8::Null()")) {
531     return v8::Handle<v8::Primitive>();
532   }
533   return v8::Handle<Primitive>(
534       ToApi<Primitive>(isolate->factory()->null_value()));
535 }
536
537
538 v8::Handle<Boolean> True() {
539   i::Isolate* isolate = i::Isolate::Current();
540   if (!EnsureInitializedForIsolate(isolate, "v8::True()")) {
541     return v8::Handle<Boolean>();
542   }
543   return v8::Handle<Boolean>(
544       ToApi<Boolean>(isolate->factory()->true_value()));
545 }
546
547
548 v8::Handle<Boolean> False() {
549   i::Isolate* isolate = i::Isolate::Current();
550   if (!EnsureInitializedForIsolate(isolate, "v8::False()")) {
551     return v8::Handle<Boolean>();
552   }
553   return v8::Handle<Boolean>(
554       ToApi<Boolean>(isolate->factory()->false_value()));
555 }
556
557
558 ResourceConstraints::ResourceConstraints()
559   : max_young_space_size_(0),
560     max_old_space_size_(0),
561     max_executable_size_(0),
562     stack_limit_(NULL) { }
563
564
565 bool SetResourceConstraints(ResourceConstraints* constraints) {
566   i::Isolate* isolate = EnterIsolateIfNeeded();
567
568   int young_space_size = constraints->max_young_space_size();
569   int old_gen_size = constraints->max_old_space_size();
570   int max_executable_size = constraints->max_executable_size();
571   if (young_space_size != 0 || old_gen_size != 0 || max_executable_size != 0) {
572     // After initialization it's too late to change Heap constraints.
573     ASSERT(!isolate->IsInitialized());
574     bool result = isolate->heap()->ConfigureHeap(young_space_size / 2,
575                                                  old_gen_size,
576                                                  max_executable_size);
577     if (!result) return false;
578   }
579   if (constraints->stack_limit() != NULL) {
580     uintptr_t limit = reinterpret_cast<uintptr_t>(constraints->stack_limit());
581     isolate->stack_guard()->SetStackLimit(limit);
582   }
583   return true;
584 }
585
586
587 i::Object** V8::GlobalizeReference(i::Object** obj) {
588   i::Isolate* isolate = i::Isolate::Current();
589   if (IsDeadCheck(isolate, "V8::Persistent::New")) return NULL;
590   LOG_API(isolate, "Persistent::New");
591   i::Handle<i::Object> result =
592       isolate->global_handles()->Create(*obj);
593   return result.location();
594 }
595
596
597 void V8::MakeWeak(i::Object** object, void* parameters,
598                   WeakReferenceCallback callback) {
599   i::Isolate* isolate = i::Isolate::Current();
600   LOG_API(isolate, "MakeWeak");
601   isolate->global_handles()->MakeWeak(object, parameters,
602                                                     callback);
603 }
604
605
606 void V8::ClearWeak(i::Object** obj) {
607   i::Isolate* isolate = i::Isolate::Current();
608   LOG_API(isolate, "ClearWeak");
609   isolate->global_handles()->ClearWeakness(obj);
610 }
611
612
613 void V8::MarkIndependent(i::Object** object) {
614   i::Isolate* isolate = i::Isolate::Current();
615   LOG_API(isolate, "MakeIndependent");
616   isolate->global_handles()->MarkIndependent(object);
617 }
618
619
620 bool V8::IsGlobalNearDeath(i::Object** obj) {
621   i::Isolate* isolate = i::Isolate::Current();
622   LOG_API(isolate, "IsGlobalNearDeath");
623   if (!isolate->IsInitialized()) return false;
624   return i::GlobalHandles::IsNearDeath(obj);
625 }
626
627
628 bool V8::IsGlobalWeak(i::Object** obj) {
629   i::Isolate* isolate = i::Isolate::Current();
630   LOG_API(isolate, "IsGlobalWeak");
631   if (!isolate->IsInitialized()) return false;
632   return i::GlobalHandles::IsWeak(obj);
633 }
634
635
636 void V8::DisposeGlobal(i::Object** obj) {
637   i::Isolate* isolate = i::Isolate::Current();
638   LOG_API(isolate, "DisposeGlobal");
639   if (!isolate->IsInitialized()) return;
640   isolate->global_handles()->Destroy(obj);
641 }
642
643 // --- H a n d l e s ---
644
645
646 HandleScope::HandleScope() {
647   i::Isolate* isolate = i::Isolate::Current();
648   API_ENTRY_CHECK(isolate, "HandleScope::HandleScope");
649   v8::ImplementationUtilities::HandleScopeData* current =
650       isolate->handle_scope_data();
651   isolate_ = isolate;
652   prev_next_ = current->next;
653   prev_limit_ = current->limit;
654   is_closed_ = false;
655   current->level++;
656 }
657
658
659 HandleScope::~HandleScope() {
660   if (!is_closed_) {
661     Leave();
662   }
663 }
664
665
666 void HandleScope::Leave() {
667   ASSERT(isolate_ == i::Isolate::Current());
668   v8::ImplementationUtilities::HandleScopeData* current =
669       isolate_->handle_scope_data();
670   current->level--;
671   ASSERT(current->level >= 0);
672   current->next = prev_next_;
673   if (current->limit != prev_limit_) {
674     current->limit = prev_limit_;
675     i::HandleScope::DeleteExtensions(isolate_);
676   }
677
678 #ifdef DEBUG
679   i::HandleScope::ZapRange(prev_next_, prev_limit_);
680 #endif
681 }
682
683
684 int HandleScope::NumberOfHandles() {
685   EnsureInitializedForIsolate(
686       i::Isolate::Current(), "HandleScope::NumberOfHandles");
687   return i::HandleScope::NumberOfHandles();
688 }
689
690
691 i::Object** HandleScope::CreateHandle(i::Object* value) {
692   return i::HandleScope::CreateHandle(value, i::Isolate::Current());
693 }
694
695
696 i::Object** HandleScope::CreateHandle(i::HeapObject* value) {
697   ASSERT(value->IsHeapObject());
698   return reinterpret_cast<i::Object**>(
699       i::HandleScope::CreateHandle(value, value->GetIsolate()));
700 }
701
702
703 void Context::Enter() {
704   i::Handle<i::Context> env = Utils::OpenHandle(this);
705   i::Isolate* isolate = env->GetIsolate();
706   if (IsDeadCheck(isolate, "v8::Context::Enter()")) return;
707   ENTER_V8(isolate);
708
709   isolate->handle_scope_implementer()->EnterContext(env);
710
711   isolate->handle_scope_implementer()->SaveContext(isolate->context());
712   isolate->set_context(*env);
713 }
714
715
716 void Context::Exit() {
717   // Exit is essentially a static function and doesn't use the
718   // receiver, so we have to get the current isolate from the thread
719   // local.
720   i::Isolate* isolate = i::Isolate::Current();
721   if (!isolate->IsInitialized()) return;
722
723   if (!ApiCheck(isolate->handle_scope_implementer()->LeaveLastContext(),
724                 "v8::Context::Exit()",
725                 "Cannot exit non-entered context")) {
726     return;
727   }
728
729   // Content of 'last_context' could be NULL.
730   i::Context* last_context =
731       isolate->handle_scope_implementer()->RestoreContext();
732   isolate->set_context(last_context);
733 }
734
735
736 void Context::SetData(v8::Handle<String> data) {
737   i::Handle<i::Context> env = Utils::OpenHandle(this);
738   i::Isolate* isolate = env->GetIsolate();
739   if (IsDeadCheck(isolate, "v8::Context::SetData()")) return;
740   i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
741   ASSERT(env->IsGlobalContext());
742   if (env->IsGlobalContext()) {
743     env->set_data(*raw_data);
744   }
745 }
746
747
748 v8::Local<v8::Value> Context::GetData() {
749   i::Handle<i::Context> env = Utils::OpenHandle(this);
750   i::Isolate* isolate = env->GetIsolate();
751   if (IsDeadCheck(isolate, "v8::Context::GetData()")) {
752     return v8::Local<Value>();
753   }
754   i::Object* raw_result = NULL;
755   ASSERT(env->IsGlobalContext());
756   if (env->IsGlobalContext()) {
757     raw_result = env->data();
758   } else {
759     return Local<Value>();
760   }
761   i::Handle<i::Object> result(raw_result, isolate);
762   return Utils::ToLocal(result);
763 }
764
765
766 i::Object** v8::HandleScope::RawClose(i::Object** value) {
767   if (!ApiCheck(!is_closed_,
768                 "v8::HandleScope::Close()",
769                 "Local scope has already been closed")) {
770     return 0;
771   }
772   LOG_API(isolate_, "CloseHandleScope");
773
774   // Read the result before popping the handle block.
775   i::Object* result = NULL;
776   if (value != NULL) {
777     result = *value;
778   }
779   is_closed_ = true;
780   Leave();
781
782   if (value == NULL) {
783     return NULL;
784   }
785
786   // Allocate a new handle on the previous handle block.
787   i::Handle<i::Object> handle(result);
788   return handle.location();
789 }
790
791
792 // --- N e a n d e r ---
793
794
795 // A constructor cannot easily return an error value, therefore it is necessary
796 // to check for a dead VM with ON_BAILOUT before constructing any Neander
797 // objects.  To remind you about this there is no HandleScope in the
798 // NeanderObject constructor.  When you add one to the site calling the
799 // constructor you should check that you ensured the VM was not dead first.
800 NeanderObject::NeanderObject(int size) {
801   i::Isolate* isolate = i::Isolate::Current();
802   EnsureInitializedForIsolate(isolate, "v8::Nowhere");
803   ENTER_V8(isolate);
804   value_ = isolate->factory()->NewNeanderObject();
805   i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
806   value_->set_elements(*elements);
807 }
808
809
810 int NeanderObject::size() {
811   return i::FixedArray::cast(value_->elements())->length();
812 }
813
814
815 NeanderArray::NeanderArray() : obj_(2) {
816   obj_.set(0, i::Smi::FromInt(0));
817 }
818
819
820 int NeanderArray::length() {
821   return i::Smi::cast(obj_.get(0))->value();
822 }
823
824
825 i::Object* NeanderArray::get(int offset) {
826   ASSERT(0 <= offset);
827   ASSERT(offset < length());
828   return obj_.get(offset + 1);
829 }
830
831
832 // This method cannot easily return an error value, therefore it is necessary
833 // to check for a dead VM with ON_BAILOUT before calling it.  To remind you
834 // about this there is no HandleScope in this method.  When you add one to the
835 // site calling this method you should check that you ensured the VM was not
836 // dead first.
837 void NeanderArray::add(i::Handle<i::Object> value) {
838   int length = this->length();
839   int size = obj_.size();
840   if (length == size - 1) {
841     i::Handle<i::FixedArray> new_elms = FACTORY->NewFixedArray(2 * size);
842     for (int i = 0; i < length; i++)
843       new_elms->set(i + 1, get(i));
844     obj_.value()->set_elements(*new_elms);
845   }
846   obj_.set(length + 1, *value);
847   obj_.set(0, i::Smi::FromInt(length + 1));
848 }
849
850
851 void NeanderArray::set(int index, i::Object* value) {
852   if (index < 0 || index >= this->length()) return;
853   obj_.set(index + 1, value);
854 }
855
856
857 // --- T e m p l a t e ---
858
859
860 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
861   that->set_tag(i::Smi::FromInt(type));
862 }
863
864
865 void Template::Set(v8::Handle<String> name, v8::Handle<Data> value,
866                    v8::PropertyAttribute attribute) {
867   i::Isolate* isolate = i::Isolate::Current();
868   if (IsDeadCheck(isolate, "v8::Template::Set()")) return;
869   ENTER_V8(isolate);
870   i::HandleScope scope(isolate);
871   i::Handle<i::Object> list(Utils::OpenHandle(this)->property_list());
872   if (list->IsUndefined()) {
873     list = NeanderArray().value();
874     Utils::OpenHandle(this)->set_property_list(*list);
875   }
876   NeanderArray array(list);
877   array.add(Utils::OpenHandle(*name));
878   array.add(Utils::OpenHandle(*value));
879   array.add(Utils::OpenHandle(*v8::Integer::New(attribute)));
880 }
881
882
883 // --- F u n c t i o n   T e m p l a t e ---
884 static void InitializeFunctionTemplate(
885       i::Handle<i::FunctionTemplateInfo> info) {
886   info->set_tag(i::Smi::FromInt(Consts::FUNCTION_TEMPLATE));
887   info->set_flag(0);
888 }
889
890
891 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
892   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
893   if (IsDeadCheck(isolate, "v8::FunctionTemplate::PrototypeTemplate()")) {
894     return Local<ObjectTemplate>();
895   }
896   ENTER_V8(isolate);
897   i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template());
898   if (result->IsUndefined()) {
899     result = Utils::OpenHandle(*ObjectTemplate::New());
900     Utils::OpenHandle(this)->set_prototype_template(*result);
901   }
902   return Local<ObjectTemplate>(ToApi<ObjectTemplate>(result));
903 }
904
905
906 void FunctionTemplate::Inherit(v8::Handle<FunctionTemplate> value) {
907   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
908   if (IsDeadCheck(isolate, "v8::FunctionTemplate::Inherit()")) return;
909   ENTER_V8(isolate);
910   Utils::OpenHandle(this)->set_parent_template(*Utils::OpenHandle(*value));
911 }
912
913
914 Local<FunctionTemplate> FunctionTemplate::New(InvocationCallback callback,
915     v8::Handle<Value> data, v8::Handle<Signature> signature) {
916   i::Isolate* isolate = i::Isolate::Current();
917   EnsureInitializedForIsolate(isolate, "v8::FunctionTemplate::New()");
918   LOG_API(isolate, "FunctionTemplate::New");
919   ENTER_V8(isolate);
920   i::Handle<i::Struct> struct_obj =
921       isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
922   i::Handle<i::FunctionTemplateInfo> obj =
923       i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
924   InitializeFunctionTemplate(obj);
925   int next_serial_number = isolate->next_serial_number();
926   isolate->set_next_serial_number(next_serial_number + 1);
927   obj->set_serial_number(i::Smi::FromInt(next_serial_number));
928   if (callback != 0) {
929     if (data.IsEmpty()) data = v8::Undefined();
930     Utils::ToLocal(obj)->SetCallHandler(callback, data);
931   }
932   obj->set_undetectable(false);
933   obj->set_needs_access_check(false);
934
935   if (!signature.IsEmpty())
936     obj->set_signature(*Utils::OpenHandle(*signature));
937   return Utils::ToLocal(obj);
938 }
939
940
941 Local<Signature> Signature::New(Handle<FunctionTemplate> receiver,
942       int argc, Handle<FunctionTemplate> argv[]) {
943   i::Isolate* isolate = i::Isolate::Current();
944   EnsureInitializedForIsolate(isolate, "v8::Signature::New()");
945   LOG_API(isolate, "Signature::New");
946   ENTER_V8(isolate);
947   i::Handle<i::Struct> struct_obj =
948       isolate->factory()->NewStruct(i::SIGNATURE_INFO_TYPE);
949   i::Handle<i::SignatureInfo> obj =
950       i::Handle<i::SignatureInfo>::cast(struct_obj);
951   if (!receiver.IsEmpty()) obj->set_receiver(*Utils::OpenHandle(*receiver));
952   if (argc > 0) {
953     i::Handle<i::FixedArray> args = isolate->factory()->NewFixedArray(argc);
954     for (int i = 0; i < argc; i++) {
955       if (!argv[i].IsEmpty())
956         args->set(i, *Utils::OpenHandle(*argv[i]));
957     }
958     obj->set_args(*args);
959   }
960   return Utils::ToLocal(obj);
961 }
962
963
964 Local<TypeSwitch> TypeSwitch::New(Handle<FunctionTemplate> type) {
965   Handle<FunctionTemplate> types[1] = { type };
966   return TypeSwitch::New(1, types);
967 }
968
969
970 Local<TypeSwitch> TypeSwitch::New(int argc, Handle<FunctionTemplate> types[]) {
971   i::Isolate* isolate = i::Isolate::Current();
972   EnsureInitializedForIsolate(isolate, "v8::TypeSwitch::New()");
973   LOG_API(isolate, "TypeSwitch::New");
974   ENTER_V8(isolate);
975   i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
976   for (int i = 0; i < argc; i++)
977     vector->set(i, *Utils::OpenHandle(*types[i]));
978   i::Handle<i::Struct> struct_obj =
979       isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
980   i::Handle<i::TypeSwitchInfo> obj =
981       i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
982   obj->set_types(*vector);
983   return Utils::ToLocal(obj);
984 }
985
986
987 int TypeSwitch::match(v8::Handle<Value> value) {
988   i::Isolate* isolate = i::Isolate::Current();
989   LOG_API(isolate, "TypeSwitch::match");
990   USE(isolate);
991   i::Handle<i::Object> obj = Utils::OpenHandle(*value);
992   i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
993   i::FixedArray* types = i::FixedArray::cast(info->types());
994   for (int i = 0; i < types->length(); i++) {
995     if (obj->IsInstanceOf(i::FunctionTemplateInfo::cast(types->get(i))))
996       return i + 1;
997   }
998   return 0;
999 }
1000
1001
1002 #define SET_FIELD_WRAPPED(obj, setter, cdata) do {    \
1003     i::Handle<i::Object> foreign = FromCData(cdata);  \
1004     (obj)->setter(*foreign);                          \
1005   } while (false)
1006
1007
1008 void FunctionTemplate::SetCallHandler(InvocationCallback callback,
1009                                       v8::Handle<Value> data) {
1010   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1011   if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetCallHandler()")) return;
1012   ENTER_V8(isolate);
1013   i::HandleScope scope(isolate);
1014   i::Handle<i::Struct> struct_obj =
1015       isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1016   i::Handle<i::CallHandlerInfo> obj =
1017       i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1018   SET_FIELD_WRAPPED(obj, set_callback, callback);
1019   if (data.IsEmpty()) data = v8::Undefined();
1020   obj->set_data(*Utils::OpenHandle(*data));
1021   Utils::OpenHandle(this)->set_call_code(*obj);
1022 }
1023
1024
1025 static i::Handle<i::AccessorInfo> MakeAccessorInfo(
1026       v8::Handle<String> name,
1027       AccessorGetter getter,
1028       AccessorSetter setter,
1029       v8::Handle<Value> data,
1030       v8::AccessControl settings,
1031       v8::PropertyAttribute attributes) {
1032   i::Handle<i::AccessorInfo> obj = FACTORY->NewAccessorInfo();
1033   ASSERT(getter != NULL);
1034   SET_FIELD_WRAPPED(obj, set_getter, getter);
1035   SET_FIELD_WRAPPED(obj, set_setter, setter);
1036   if (data.IsEmpty()) data = v8::Undefined();
1037   obj->set_data(*Utils::OpenHandle(*data));
1038   obj->set_name(*Utils::OpenHandle(*name));
1039   if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1040   if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1041   if (settings & PROHIBITS_OVERWRITING) obj->set_prohibits_overwriting(true);
1042   obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
1043   return obj;
1044 }
1045
1046
1047 void FunctionTemplate::AddInstancePropertyAccessor(
1048       v8::Handle<String> name,
1049       AccessorGetter getter,
1050       AccessorSetter setter,
1051       v8::Handle<Value> data,
1052       v8::AccessControl settings,
1053       v8::PropertyAttribute attributes) {
1054   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1055   if (IsDeadCheck(isolate,
1056                   "v8::FunctionTemplate::AddInstancePropertyAccessor()")) {
1057     return;
1058   }
1059   ENTER_V8(isolate);
1060   i::HandleScope scope(isolate);
1061
1062   i::Handle<i::AccessorInfo> obj = MakeAccessorInfo(name,
1063                                                     getter, setter, data,
1064                                                     settings, attributes);
1065   i::Handle<i::Object> list(Utils::OpenHandle(this)->property_accessors());
1066   if (list->IsUndefined()) {
1067     list = NeanderArray().value();
1068     Utils::OpenHandle(this)->set_property_accessors(*list);
1069   }
1070   NeanderArray array(list);
1071   array.add(obj);
1072 }
1073
1074
1075 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
1076   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1077   if (IsDeadCheck(isolate, "v8::FunctionTemplate::InstanceTemplate()")
1078       || EmptyCheck("v8::FunctionTemplate::InstanceTemplate()", this))
1079     return Local<ObjectTemplate>();
1080   ENTER_V8(isolate);
1081   if (Utils::OpenHandle(this)->instance_template()->IsUndefined()) {
1082     Local<ObjectTemplate> templ =
1083         ObjectTemplate::New(v8::Handle<FunctionTemplate>(this));
1084     Utils::OpenHandle(this)->set_instance_template(*Utils::OpenHandle(*templ));
1085   }
1086   i::Handle<i::ObjectTemplateInfo> result(i::ObjectTemplateInfo::cast(
1087         Utils::OpenHandle(this)->instance_template()));
1088   return Utils::ToLocal(result);
1089 }
1090
1091
1092 void FunctionTemplate::SetClassName(Handle<String> name) {
1093   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1094   if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetClassName()")) return;
1095   ENTER_V8(isolate);
1096   Utils::OpenHandle(this)->set_class_name(*Utils::OpenHandle(*name));
1097 }
1098
1099
1100 void FunctionTemplate::SetHiddenPrototype(bool value) {
1101   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1102   if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetHiddenPrototype()")) {
1103     return;
1104   }
1105   ENTER_V8(isolate);
1106   Utils::OpenHandle(this)->set_hidden_prototype(value);
1107 }
1108
1109
1110 void FunctionTemplate::ReadOnlyPrototype() {
1111   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1112   if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetPrototypeAttributes()")) {
1113     return;
1114   }
1115   ENTER_V8(isolate);
1116   Utils::OpenHandle(this)->set_read_only_prototype(true);
1117 }
1118
1119
1120 void FunctionTemplate::SetNamedInstancePropertyHandler(
1121       NamedPropertyGetter getter,
1122       NamedPropertySetter setter,
1123       NamedPropertyQuery query,
1124       NamedPropertyDeleter remover,
1125       NamedPropertyEnumerator enumerator,
1126       bool is_fallback,
1127       Handle<Value> data) {
1128   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1129   if (IsDeadCheck(isolate,
1130                   "v8::FunctionTemplate::SetNamedInstancePropertyHandler()")) {
1131     return;
1132   }
1133   ENTER_V8(isolate);
1134   i::HandleScope scope(isolate);
1135   i::Handle<i::Struct> struct_obj =
1136       isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE);
1137   i::Handle<i::InterceptorInfo> obj =
1138       i::Handle<i::InterceptorInfo>::cast(struct_obj);
1139
1140   if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1141   if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1142   if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1143   if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1144   if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1145   obj->set_is_fallback(i::Smi::FromInt(is_fallback));
1146
1147   if (data.IsEmpty()) data = v8::Undefined();
1148   obj->set_data(*Utils::OpenHandle(*data));
1149   Utils::OpenHandle(this)->set_named_property_handler(*obj);
1150 }
1151
1152
1153 void FunctionTemplate::SetIndexedInstancePropertyHandler(
1154       IndexedPropertyGetter getter,
1155       IndexedPropertySetter setter,
1156       IndexedPropertyQuery query,
1157       IndexedPropertyDeleter remover,
1158       IndexedPropertyEnumerator enumerator,
1159       Handle<Value> data) {
1160   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1161   if (IsDeadCheck(isolate,
1162         "v8::FunctionTemplate::SetIndexedInstancePropertyHandler()")) {
1163     return;
1164   }
1165   ENTER_V8(isolate);
1166   i::HandleScope scope(isolate);
1167   i::Handle<i::Struct> struct_obj =
1168       isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE);
1169   i::Handle<i::InterceptorInfo> obj =
1170       i::Handle<i::InterceptorInfo>::cast(struct_obj);
1171
1172   if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1173   if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1174   if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1175   if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1176   if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1177
1178   if (data.IsEmpty()) data = v8::Undefined();
1179   obj->set_data(*Utils::OpenHandle(*data));
1180   Utils::OpenHandle(this)->set_indexed_property_handler(*obj);
1181 }
1182
1183
1184 void FunctionTemplate::SetInstanceCallAsFunctionHandler(
1185       InvocationCallback callback,
1186       Handle<Value> data) {
1187   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1188   if (IsDeadCheck(isolate,
1189                   "v8::FunctionTemplate::SetInstanceCallAsFunctionHandler()")) {
1190     return;
1191   }
1192   ENTER_V8(isolate);
1193   i::HandleScope scope(isolate);
1194   i::Handle<i::Struct> struct_obj =
1195       isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1196   i::Handle<i::CallHandlerInfo> obj =
1197       i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1198   SET_FIELD_WRAPPED(obj, set_callback, callback);
1199   if (data.IsEmpty()) data = v8::Undefined();
1200   obj->set_data(*Utils::OpenHandle(*data));
1201   Utils::OpenHandle(this)->set_instance_call_handler(*obj);
1202 }
1203
1204
1205 // --- O b j e c t T e m p l a t e ---
1206
1207
1208 Local<ObjectTemplate> ObjectTemplate::New() {
1209   return New(Local<FunctionTemplate>());
1210 }
1211
1212
1213 Local<ObjectTemplate> ObjectTemplate::New(
1214       v8::Handle<FunctionTemplate> constructor) {
1215   i::Isolate* isolate = i::Isolate::Current();
1216   if (IsDeadCheck(isolate, "v8::ObjectTemplate::New()")) {
1217     return Local<ObjectTemplate>();
1218   }
1219   EnsureInitializedForIsolate(isolate, "v8::ObjectTemplate::New()");
1220   LOG_API(isolate, "ObjectTemplate::New");
1221   ENTER_V8(isolate);
1222   i::Handle<i::Struct> struct_obj =
1223       isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
1224   i::Handle<i::ObjectTemplateInfo> obj =
1225       i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
1226   InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1227   if (!constructor.IsEmpty())
1228     obj->set_constructor(*Utils::OpenHandle(*constructor));
1229   obj->set_internal_field_count(i::Smi::FromInt(0));
1230   return Utils::ToLocal(obj);
1231 }
1232
1233
1234 // Ensure that the object template has a constructor.  If no
1235 // constructor is available we create one.
1236 static void EnsureConstructor(ObjectTemplate* object_template) {
1237   if (Utils::OpenHandle(object_template)->constructor()->IsUndefined()) {
1238     Local<FunctionTemplate> templ = FunctionTemplate::New();
1239     i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1240     constructor->set_instance_template(*Utils::OpenHandle(object_template));
1241     Utils::OpenHandle(object_template)->set_constructor(*constructor);
1242   }
1243 }
1244
1245
1246 void ObjectTemplate::SetAccessor(v8::Handle<String> name,
1247                                  AccessorGetter getter,
1248                                  AccessorSetter setter,
1249                                  v8::Handle<Value> data,
1250                                  AccessControl settings,
1251                                  PropertyAttribute attribute) {
1252   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1253   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetAccessor()")) return;
1254   ENTER_V8(isolate);
1255   i::HandleScope scope(isolate);
1256   EnsureConstructor(this);
1257   i::FunctionTemplateInfo* constructor =
1258       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1259   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1260   Utils::ToLocal(cons)->AddInstancePropertyAccessor(name,
1261                                                     getter,
1262                                                     setter,
1263                                                     data,
1264                                                     settings,
1265                                                     attribute);
1266 }
1267
1268
1269 void ObjectTemplate::SetNamedPropertyHandler(NamedPropertyGetter getter,
1270                                              NamedPropertySetter setter,
1271                                              NamedPropertyQuery query,
1272                                              NamedPropertyDeleter remover,
1273                                              NamedPropertyEnumerator enumerator,
1274                                              Handle<Value> data) {
1275   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1276   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetNamedPropertyHandler()")) {
1277     return;
1278   }
1279   ENTER_V8(isolate);
1280   i::HandleScope scope(isolate);
1281   EnsureConstructor(this);
1282   i::FunctionTemplateInfo* constructor =
1283       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1284   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1285   Utils::ToLocal(cons)->SetNamedInstancePropertyHandler(getter,
1286                                                         setter,
1287                                                         query,
1288                                                         remover,
1289                                                         enumerator,
1290                                                         false,
1291                                                         data);
1292 }
1293
1294
1295 void ObjectTemplate::SetFallbackPropertyHandler(NamedPropertyGetter getter,
1296                                                 NamedPropertySetter setter,
1297                                                 NamedPropertyQuery query,
1298                                                 NamedPropertyDeleter remover,
1299                                                 NamedPropertyEnumerator enumerator,
1300                                                 Handle<Value> data) {
1301   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1302   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetNamedPropertyHandler()")) {
1303     return;
1304   }
1305   ENTER_V8(isolate);
1306   i::HandleScope scope(isolate);
1307   EnsureConstructor(this);
1308   i::FunctionTemplateInfo* constructor =
1309       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1310   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1311   Utils::ToLocal(cons)->SetNamedInstancePropertyHandler(getter,
1312                                                         setter,
1313                                                         query,
1314                                                         remover,
1315                                                         enumerator,
1316                                                         true,
1317                                                         data);
1318 }
1319
1320
1321 void ObjectTemplate::MarkAsUndetectable() {
1322   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1323   if (IsDeadCheck(isolate, "v8::ObjectTemplate::MarkAsUndetectable()")) return;
1324   ENTER_V8(isolate);
1325   i::HandleScope scope(isolate);
1326   EnsureConstructor(this);
1327   i::FunctionTemplateInfo* constructor =
1328       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1329   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1330   cons->set_undetectable(true);
1331 }
1332
1333
1334 void ObjectTemplate::SetAccessCheckCallbacks(
1335       NamedSecurityCallback named_callback,
1336       IndexedSecurityCallback indexed_callback,
1337       Handle<Value> data,
1338       bool turned_on_by_default) {
1339   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1340   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetAccessCheckCallbacks()")) {
1341     return;
1342   }
1343   ENTER_V8(isolate);
1344   i::HandleScope scope(isolate);
1345   EnsureConstructor(this);
1346
1347   i::Handle<i::Struct> struct_info =
1348       isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE);
1349   i::Handle<i::AccessCheckInfo> info =
1350       i::Handle<i::AccessCheckInfo>::cast(struct_info);
1351
1352   SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
1353   SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
1354
1355   if (data.IsEmpty()) data = v8::Undefined();
1356   info->set_data(*Utils::OpenHandle(*data));
1357
1358   i::FunctionTemplateInfo* constructor =
1359       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1360   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1361   cons->set_access_check_info(*info);
1362   cons->set_needs_access_check(turned_on_by_default);
1363 }
1364
1365
1366 void ObjectTemplate::SetIndexedPropertyHandler(
1367       IndexedPropertyGetter getter,
1368       IndexedPropertySetter setter,
1369       IndexedPropertyQuery query,
1370       IndexedPropertyDeleter remover,
1371       IndexedPropertyEnumerator enumerator,
1372       Handle<Value> data) {
1373   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1374   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetIndexedPropertyHandler()")) {
1375     return;
1376   }
1377   ENTER_V8(isolate);
1378   i::HandleScope scope(isolate);
1379   EnsureConstructor(this);
1380   i::FunctionTemplateInfo* constructor =
1381       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1382   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1383   Utils::ToLocal(cons)->SetIndexedInstancePropertyHandler(getter,
1384                                                           setter,
1385                                                           query,
1386                                                           remover,
1387                                                           enumerator,
1388                                                           data);
1389 }
1390
1391
1392 void ObjectTemplate::SetCallAsFunctionHandler(InvocationCallback callback,
1393                                               Handle<Value> data) {
1394   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1395   if (IsDeadCheck(isolate,
1396                   "v8::ObjectTemplate::SetCallAsFunctionHandler()")) {
1397     return;
1398   }
1399   ENTER_V8(isolate);
1400   i::HandleScope scope(isolate);
1401   EnsureConstructor(this);
1402   i::FunctionTemplateInfo* constructor =
1403       i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1404   i::Handle<i::FunctionTemplateInfo> cons(constructor);
1405   Utils::ToLocal(cons)->SetInstanceCallAsFunctionHandler(callback, data);
1406 }
1407
1408
1409 int ObjectTemplate::InternalFieldCount() {
1410   if (IsDeadCheck(Utils::OpenHandle(this)->GetIsolate(),
1411                   "v8::ObjectTemplate::InternalFieldCount()")) {
1412     return 0;
1413   }
1414   return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1415 }
1416
1417
1418 void ObjectTemplate::SetInternalFieldCount(int value) {
1419   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1420   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetInternalFieldCount()")) {
1421     return;
1422   }
1423   if (!ApiCheck(i::Smi::IsValid(value),
1424                 "v8::ObjectTemplate::SetInternalFieldCount()",
1425                 "Invalid internal field count")) {
1426     return;
1427   }
1428   ENTER_V8(isolate);
1429   if (value > 0) {
1430     // The internal field count is set by the constructor function's
1431     // construct code, so we ensure that there is a constructor
1432     // function to do the setting.
1433     EnsureConstructor(this);
1434   }
1435   Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1436 }
1437
1438
1439 bool ObjectTemplate::HasExternalResource()
1440 {
1441   if (IsDeadCheck(Utils::OpenHandle(this)->GetIsolate(),
1442                   "v8::ObjectTemplate::HasExternalResource()")) {
1443     return 0;
1444   }
1445   return !Utils::OpenHandle(this)->has_external_resource()->IsUndefined();
1446 }
1447
1448
1449 void ObjectTemplate::SetHasExternalResource(bool value)
1450 {
1451   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1452   if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetHasExternalResource()")) {
1453     return;
1454   }
1455   ENTER_V8(isolate);
1456   if (value) {
1457     EnsureConstructor(this);
1458   }
1459   if (value) {
1460       Utils::OpenHandle(this)->set_has_external_resource(i::Smi::FromInt(1));
1461   } else {
1462       Utils::OpenHandle(this)->set_has_external_resource(Utils::OpenHandle(this)->GetHeap()->undefined_value());
1463   }
1464 }
1465
1466
1467 // --- S c r i p t D a t a ---
1468
1469
1470 ScriptData* ScriptData::PreCompile(const char* input, int length) {
1471   i::Utf8ToUC16CharacterStream stream(
1472       reinterpret_cast<const unsigned char*>(input), length);
1473   return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1474 }
1475
1476
1477 ScriptData* ScriptData::PreCompile(v8::Handle<String> source) {
1478   i::Handle<i::String> str = Utils::OpenHandle(*source);
1479   if (str->IsExternalTwoByteString()) {
1480     i::ExternalTwoByteStringUC16CharacterStream stream(
1481       i::Handle<i::ExternalTwoByteString>::cast(str), 0, str->length());
1482     return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1483   } else {
1484     i::GenericStringUC16CharacterStream stream(str, 0, str->length());
1485     return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1486   }
1487 }
1488
1489
1490 ScriptData* ScriptData::New(const char* data, int length) {
1491   // Return an empty ScriptData if the length is obviously invalid.
1492   if (length % sizeof(unsigned) != 0) {
1493     return new i::ScriptDataImpl();
1494   }
1495
1496   // Copy the data to ensure it is properly aligned.
1497   int deserialized_data_length = length / sizeof(unsigned);
1498   // If aligned, don't create a copy of the data.
1499   if (reinterpret_cast<intptr_t>(data) % sizeof(unsigned) == 0) {
1500     return new i::ScriptDataImpl(data, length);
1501   }
1502   // Copy the data to align it.
1503   unsigned* deserialized_data = i::NewArray<unsigned>(deserialized_data_length);
1504   i::OS::MemCopy(deserialized_data, data, length);
1505
1506   return new i::ScriptDataImpl(
1507       i::Vector<unsigned>(deserialized_data, deserialized_data_length));
1508 }
1509
1510
1511 // --- S c r i p t ---
1512
1513
1514 Local<Script> Script::New(v8::Handle<String> source,
1515                           v8::ScriptOrigin* origin,
1516                           v8::ScriptData* pre_data,
1517                           v8::Handle<String> script_data) {
1518   i::Isolate* isolate = i::Isolate::Current();
1519   ON_BAILOUT(isolate, "v8::Script::New()", return Local<Script>());
1520   LOG_API(isolate, "Script::New");
1521   ENTER_V8(isolate);
1522   i::Handle<i::String> str = Utils::OpenHandle(*source);
1523   i::Handle<i::Object> name_obj;
1524   int line_offset = 0;
1525   int column_offset = 0;
1526   if (origin != NULL) {
1527     if (!origin->ResourceName().IsEmpty()) {
1528       name_obj = Utils::OpenHandle(*origin->ResourceName());
1529     }
1530     if (!origin->ResourceLineOffset().IsEmpty()) {
1531       line_offset = static_cast<int>(origin->ResourceLineOffset()->Value());
1532     }
1533     if (!origin->ResourceColumnOffset().IsEmpty()) {
1534       column_offset = static_cast<int>(origin->ResourceColumnOffset()->Value());
1535     }
1536   }
1537   EXCEPTION_PREAMBLE(isolate);
1538   i::ScriptDataImpl* pre_data_impl = static_cast<i::ScriptDataImpl*>(pre_data);
1539   // We assert that the pre-data is sane, even though we can actually
1540   // handle it if it turns out not to be in release mode.
1541   ASSERT(pre_data_impl == NULL || pre_data_impl->SanityCheck());
1542   // If the pre-data isn't sane we simply ignore it
1543   if (pre_data_impl != NULL && !pre_data_impl->SanityCheck()) {
1544     pre_data_impl = NULL;
1545   }
1546   i::Handle<i::SharedFunctionInfo> result =
1547       i::Compiler::Compile(str,
1548                            name_obj,
1549                            line_offset,
1550                            column_offset,
1551                            NULL,
1552                            pre_data_impl,
1553                            Utils::OpenHandle(*script_data),
1554                            i::NOT_NATIVES_CODE);
1555   has_pending_exception = result.is_null();
1556   EXCEPTION_BAILOUT_CHECK(isolate, Local<Script>());
1557   return Local<Script>(ToApi<Script>(result));
1558 }
1559
1560
1561 Local<Script> Script::New(v8::Handle<String> source,
1562                           v8::Handle<Value> file_name) {
1563   ScriptOrigin origin(file_name);
1564   return New(source, &origin);
1565 }
1566
1567
1568 Local<Script> Script::Compile(v8::Handle<String> source,
1569                               v8::ScriptOrigin* origin,
1570                               v8::ScriptData* pre_data,
1571                               v8::Handle<String> script_data) {
1572   i::Isolate* isolate = i::Isolate::Current();
1573   ON_BAILOUT(isolate, "v8::Script::Compile()", return Local<Script>());
1574   LOG_API(isolate, "Script::Compile");
1575   ENTER_V8(isolate);
1576   Local<Script> generic = New(source, origin, pre_data, script_data);
1577   if (generic.IsEmpty())
1578     return generic;
1579   i::Handle<i::Object> obj = Utils::OpenHandle(*generic);
1580   i::Handle<i::SharedFunctionInfo> function =
1581       i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1582   i::Handle<i::JSFunction> result =
1583       isolate->factory()->NewFunctionFromSharedFunctionInfo(
1584           function,
1585           isolate->global_context());
1586   return Local<Script>(ToApi<Script>(result));
1587 }
1588
1589
1590 Local<Script> Script::Compile(v8::Handle<String> source,
1591                               v8::Handle<Value> file_name,
1592                               v8::Handle<String> script_data) {
1593   ScriptOrigin origin(file_name);
1594   return Compile(source, &origin, 0, script_data);
1595 }
1596
1597
1598 Local<Value> Script::Run() {
1599   i::Isolate* isolate = i::Isolate::Current();
1600   ON_BAILOUT(isolate, "v8::Script::Run()", return Local<Value>());
1601   LOG_API(isolate, "Script::Run");
1602   ENTER_V8(isolate);
1603   i::Object* raw_result = NULL;
1604   {
1605     i::HandleScope scope(isolate);
1606     i::Handle<i::Object> obj = Utils::OpenHandle(this);
1607     i::Handle<i::JSFunction> fun;
1608     if (obj->IsSharedFunctionInfo()) {
1609       i::Handle<i::SharedFunctionInfo>
1610           function_info(i::SharedFunctionInfo::cast(*obj), isolate);
1611       fun = isolate->factory()->NewFunctionFromSharedFunctionInfo(
1612           function_info, isolate->global_context());
1613     } else {
1614       fun = i::Handle<i::JSFunction>(i::JSFunction::cast(*obj), isolate);
1615     }
1616     EXCEPTION_PREAMBLE(isolate);
1617     i::Handle<i::Object> receiver(
1618         isolate->context()->global_proxy(), isolate);
1619     i::Handle<i::Object> result =
1620         i::Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1621     EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
1622     raw_result = *result;
1623   }
1624   i::Handle<i::Object> result(raw_result, isolate);
1625   return Utils::ToLocal(result);
1626 }
1627
1628
1629 static i::Handle<i::SharedFunctionInfo> OpenScript(Script* script) {
1630   i::Handle<i::Object> obj = Utils::OpenHandle(script);
1631   i::Handle<i::SharedFunctionInfo> result;
1632   if (obj->IsSharedFunctionInfo()) {
1633     result =
1634         i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1635   } else {
1636     result =
1637         i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared());
1638   }
1639   return result;
1640 }
1641
1642
1643 Local<Value> Script::Id() {
1644   i::Isolate* isolate = i::Isolate::Current();
1645   ON_BAILOUT(isolate, "v8::Script::Id()", return Local<Value>());
1646   LOG_API(isolate, "Script::Id");
1647   i::Object* raw_id = NULL;
1648   {
1649     i::HandleScope scope(isolate);
1650     i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1651     i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1652     i::Handle<i::Object> id(script->id());
1653     raw_id = *id;
1654   }
1655   i::Handle<i::Object> id(raw_id);
1656   return Utils::ToLocal(id);
1657 }
1658
1659
1660 void Script::SetData(v8::Handle<String> data) {
1661   i::Isolate* isolate = i::Isolate::Current();
1662   ON_BAILOUT(isolate, "v8::Script::SetData()", return);
1663   LOG_API(isolate, "Script::SetData");
1664   {
1665     i::HandleScope scope(isolate);
1666     i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1667     i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
1668     i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1669     script->set_data(*raw_data);
1670   }
1671 }
1672
1673
1674 // --- E x c e p t i o n s ---
1675
1676
1677 v8::TryCatch::TryCatch()
1678     : isolate_(i::Isolate::Current()),
1679       next_(isolate_->try_catch_handler_address()),
1680       exception_(isolate_->heap()->the_hole_value()),
1681       message_(i::Smi::FromInt(0)),
1682       is_verbose_(false),
1683       can_continue_(true),
1684       capture_message_(true),
1685       rethrow_(false) {
1686   isolate_->RegisterTryCatchHandler(this);
1687 }
1688
1689
1690 v8::TryCatch::~TryCatch() {
1691   ASSERT(isolate_ == i::Isolate::Current());
1692   if (rethrow_) {
1693     v8::HandleScope scope;
1694     v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(Exception());
1695     isolate_->UnregisterTryCatchHandler(this);
1696     v8::ThrowException(exc);
1697   } else {
1698     isolate_->UnregisterTryCatchHandler(this);
1699   }
1700 }
1701
1702
1703 bool v8::TryCatch::HasCaught() const {
1704   return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
1705 }
1706
1707
1708 bool v8::TryCatch::CanContinue() const {
1709   return can_continue_;
1710 }
1711
1712
1713 v8::Handle<v8::Value> v8::TryCatch::ReThrow() {
1714   if (!HasCaught()) return v8::Local<v8::Value>();
1715   rethrow_ = true;
1716   return v8::Undefined();
1717 }
1718
1719
1720 v8::Local<Value> v8::TryCatch::Exception() const {
1721   ASSERT(isolate_ == i::Isolate::Current());
1722   if (HasCaught()) {
1723     // Check for out of memory exception.
1724     i::Object* exception = reinterpret_cast<i::Object*>(exception_);
1725     return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
1726   } else {
1727     return v8::Local<Value>();
1728   }
1729 }
1730
1731
1732 v8::Local<Value> v8::TryCatch::StackTrace() const {
1733   ASSERT(isolate_ == i::Isolate::Current());
1734   if (HasCaught()) {
1735     i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
1736     if (!raw_obj->IsJSObject()) return v8::Local<Value>();
1737     i::HandleScope scope(isolate_);
1738     i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
1739     i::Handle<i::String> name = isolate_->factory()->LookupAsciiSymbol("stack");
1740     if (!obj->HasProperty(*name)) return v8::Local<Value>();
1741     i::Handle<i::Object> value = i::GetProperty(obj, name);
1742     if (value.is_null()) return v8::Local<Value>();
1743     return v8::Utils::ToLocal(scope.CloseAndEscape(value));
1744   } else {
1745     return v8::Local<Value>();
1746   }
1747 }
1748
1749
1750 v8::Local<v8::Message> v8::TryCatch::Message() const {
1751   ASSERT(isolate_ == i::Isolate::Current());
1752   if (HasCaught() && message_ != i::Smi::FromInt(0)) {
1753     i::Object* message = reinterpret_cast<i::Object*>(message_);
1754     return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
1755   } else {
1756     return v8::Local<v8::Message>();
1757   }
1758 }
1759
1760
1761 void v8::TryCatch::Reset() {
1762   ASSERT(isolate_ == i::Isolate::Current());
1763   exception_ = isolate_->heap()->the_hole_value();
1764   message_ = i::Smi::FromInt(0);
1765 }
1766
1767
1768 void v8::TryCatch::SetVerbose(bool value) {
1769   is_verbose_ = value;
1770 }
1771
1772
1773 void v8::TryCatch::SetCaptureMessage(bool value) {
1774   capture_message_ = value;
1775 }
1776
1777
1778 // --- M e s s a g e ---
1779
1780
1781 Local<String> Message::Get() const {
1782   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1783   ON_BAILOUT(isolate, "v8::Message::Get()", return Local<String>());
1784   ENTER_V8(isolate);
1785   HandleScope scope;
1786   i::Handle<i::Object> obj = Utils::OpenHandle(this);
1787   i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(obj);
1788   Local<String> result = Utils::ToLocal(raw_result);
1789   return scope.Close(result);
1790 }
1791
1792
1793 v8::Handle<Value> Message::GetScriptResourceName() const {
1794   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1795   if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceName()")) {
1796     return Local<String>();
1797   }
1798   ENTER_V8(isolate);
1799   HandleScope scope;
1800   i::Handle<i::JSMessageObject> message =
1801       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1802   // Return this.script.name.
1803   i::Handle<i::JSValue> script =
1804       i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1805   i::Handle<i::Object> resource_name(i::Script::cast(script->value())->name());
1806   return scope.Close(Utils::ToLocal(resource_name));
1807 }
1808
1809
1810 v8::Handle<Value> Message::GetScriptData() const {
1811   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1812   if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceData()")) {
1813     return Local<Value>();
1814   }
1815   ENTER_V8(isolate);
1816   HandleScope scope;
1817   i::Handle<i::JSMessageObject> message =
1818       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1819   // Return this.script.data.
1820   i::Handle<i::JSValue> script =
1821       i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1822   i::Handle<i::Object> data(i::Script::cast(script->value())->data());
1823   return scope.Close(Utils::ToLocal(data));
1824 }
1825
1826
1827 v8::Handle<v8::StackTrace> Message::GetStackTrace() const {
1828   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1829   if (IsDeadCheck(isolate, "v8::Message::GetStackTrace()")) {
1830     return Local<v8::StackTrace>();
1831   }
1832   ENTER_V8(isolate);
1833   HandleScope scope;
1834   i::Handle<i::JSMessageObject> message =
1835       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1836   i::Handle<i::Object> stackFramesObj(message->stack_frames());
1837   if (!stackFramesObj->IsJSArray()) return v8::Handle<v8::StackTrace>();
1838   i::Handle<i::JSArray> stackTrace =
1839       i::Handle<i::JSArray>::cast(stackFramesObj);
1840   return scope.Close(Utils::StackTraceToLocal(stackTrace));
1841 }
1842
1843
1844 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1845                                                i::Handle<i::Object> recv,
1846                                                int argc,
1847                                                i::Handle<i::Object> argv[],
1848                                                bool* has_pending_exception) {
1849   i::Isolate* isolate = i::Isolate::Current();
1850   i::Handle<i::String> fmt_str = isolate->factory()->LookupAsciiSymbol(name);
1851   i::Object* object_fun =
1852       isolate->js_builtins_object()->GetPropertyNoExceptionThrown(*fmt_str);
1853   i::Handle<i::JSFunction> fun =
1854       i::Handle<i::JSFunction>(i::JSFunction::cast(object_fun));
1855   i::Handle<i::Object> value =
1856       i::Execution::Call(fun, recv, argc, argv, has_pending_exception);
1857   return value;
1858 }
1859
1860
1861 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1862                                                i::Handle<i::Object> data,
1863                                                bool* has_pending_exception) {
1864   i::Handle<i::Object> argv[] = { data };
1865   return CallV8HeapFunction(name,
1866                             i::Isolate::Current()->js_builtins_object(),
1867                             ARRAY_SIZE(argv),
1868                             argv,
1869                             has_pending_exception);
1870 }
1871
1872
1873 int Message::GetLineNumber() const {
1874   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1875   ON_BAILOUT(isolate, "v8::Message::GetLineNumber()", return kNoLineNumberInfo);
1876   ENTER_V8(isolate);
1877   i::HandleScope scope(isolate);
1878
1879   EXCEPTION_PREAMBLE(isolate);
1880   i::Handle<i::Object> result = CallV8HeapFunction("GetLineNumber",
1881                                                    Utils::OpenHandle(this),
1882                                                    &has_pending_exception);
1883   EXCEPTION_BAILOUT_CHECK(isolate, 0);
1884   return static_cast<int>(result->Number());
1885 }
1886
1887
1888 int Message::GetStartPosition() const {
1889   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1890   if (IsDeadCheck(isolate, "v8::Message::GetStartPosition()")) return 0;
1891   ENTER_V8(isolate);
1892   i::HandleScope scope(isolate);
1893   i::Handle<i::JSMessageObject> message =
1894       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1895   return message->start_position();
1896 }
1897
1898
1899 int Message::GetEndPosition() const {
1900   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1901   if (IsDeadCheck(isolate, "v8::Message::GetEndPosition()")) return 0;
1902   ENTER_V8(isolate);
1903   i::HandleScope scope(isolate);
1904   i::Handle<i::JSMessageObject> message =
1905       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1906   return message->end_position();
1907 }
1908
1909
1910 int Message::GetStartColumn() const {
1911   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1912   if (IsDeadCheck(isolate, "v8::Message::GetStartColumn()")) {
1913     return kNoColumnInfo;
1914   }
1915   ENTER_V8(isolate);
1916   i::HandleScope scope(isolate);
1917   i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1918   EXCEPTION_PREAMBLE(isolate);
1919   i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1920       "GetPositionInLine",
1921       data_obj,
1922       &has_pending_exception);
1923   EXCEPTION_BAILOUT_CHECK(isolate, 0);
1924   return static_cast<int>(start_col_obj->Number());
1925 }
1926
1927
1928 int Message::GetEndColumn() const {
1929   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1930   if (IsDeadCheck(isolate, "v8::Message::GetEndColumn()")) return kNoColumnInfo;
1931   ENTER_V8(isolate);
1932   i::HandleScope scope(isolate);
1933   i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1934   EXCEPTION_PREAMBLE(isolate);
1935   i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1936       "GetPositionInLine",
1937       data_obj,
1938       &has_pending_exception);
1939   EXCEPTION_BAILOUT_CHECK(isolate, 0);
1940   i::Handle<i::JSMessageObject> message =
1941       i::Handle<i::JSMessageObject>::cast(data_obj);
1942   int start = message->start_position();
1943   int end = message->end_position();
1944   return static_cast<int>(start_col_obj->Number()) + (end - start);
1945 }
1946
1947
1948 Local<String> Message::GetSourceLine() const {
1949   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1950   ON_BAILOUT(isolate, "v8::Message::GetSourceLine()", return Local<String>());
1951   ENTER_V8(isolate);
1952   HandleScope scope;
1953   EXCEPTION_PREAMBLE(isolate);
1954   i::Handle<i::Object> result = CallV8HeapFunction("GetSourceLine",
1955                                                    Utils::OpenHandle(this),
1956                                                    &has_pending_exception);
1957   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::String>());
1958   if (result->IsString()) {
1959     return scope.Close(Utils::ToLocal(i::Handle<i::String>::cast(result)));
1960   } else {
1961     return Local<String>();
1962   }
1963 }
1964
1965
1966 void Message::PrintCurrentStackTrace(FILE* out) {
1967   i::Isolate* isolate = i::Isolate::Current();
1968   if (IsDeadCheck(isolate, "v8::Message::PrintCurrentStackTrace()")) return;
1969   ENTER_V8(isolate);
1970   isolate->PrintCurrentStackTrace(out);
1971 }
1972
1973
1974 // --- S t a c k T r a c e ---
1975
1976 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
1977   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1978   if (IsDeadCheck(isolate, "v8::StackTrace::GetFrame()")) {
1979     return Local<StackFrame>();
1980   }
1981   ENTER_V8(isolate);
1982   HandleScope scope;
1983   i::Handle<i::JSArray> self = Utils::OpenHandle(this);
1984   i::Object* raw_object = self->GetElementNoExceptionThrown(index);
1985   i::Handle<i::JSObject> obj(i::JSObject::cast(raw_object));
1986   return scope.Close(Utils::StackFrameToLocal(obj));
1987 }
1988
1989
1990 int StackTrace::GetFrameCount() const {
1991   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1992   if (IsDeadCheck(isolate, "v8::StackTrace::GetFrameCount()")) return -1;
1993   ENTER_V8(isolate);
1994   return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
1995 }
1996
1997
1998 Local<Array> StackTrace::AsArray() {
1999   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2000   if (IsDeadCheck(isolate, "v8::StackTrace::AsArray()")) Local<Array>();
2001   ENTER_V8(isolate);
2002   return Utils::ToLocal(Utils::OpenHandle(this));
2003 }
2004
2005
2006 Local<StackTrace> StackTrace::CurrentStackTrace(int frame_limit,
2007     StackTraceOptions options) {
2008   i::Isolate* isolate = i::Isolate::Current();
2009   if (IsDeadCheck(isolate, "v8::StackTrace::CurrentStackTrace()")) {
2010     Local<StackTrace>();
2011   }
2012   ENTER_V8(isolate);
2013   i::Handle<i::JSArray> stackTrace =
2014       isolate->CaptureCurrentStackTrace(frame_limit, options);
2015   return Utils::StackTraceToLocal(stackTrace);
2016 }
2017
2018
2019 // --- S t a c k F r a m e ---
2020
2021 int StackFrame::GetLineNumber() const {
2022   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2023   if (IsDeadCheck(isolate, "v8::StackFrame::GetLineNumber()")) {
2024     return Message::kNoLineNumberInfo;
2025   }
2026   ENTER_V8(isolate);
2027   i::HandleScope scope(isolate);
2028   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2029   i::Handle<i::Object> line = GetProperty(self, "lineNumber");
2030   if (!line->IsSmi()) {
2031     return Message::kNoLineNumberInfo;
2032   }
2033   return i::Smi::cast(*line)->value();
2034 }
2035
2036
2037 int StackFrame::GetColumn() const {
2038   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2039   if (IsDeadCheck(isolate, "v8::StackFrame::GetColumn()")) {
2040     return Message::kNoColumnInfo;
2041   }
2042   ENTER_V8(isolate);
2043   i::HandleScope scope(isolate);
2044   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2045   i::Handle<i::Object> column = GetProperty(self, "column");
2046   if (!column->IsSmi()) {
2047     return Message::kNoColumnInfo;
2048   }
2049   return i::Smi::cast(*column)->value();
2050 }
2051
2052
2053 Local<String> StackFrame::GetScriptName() const {
2054   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2055   if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptName()")) {
2056     return Local<String>();
2057   }
2058   ENTER_V8(isolate);
2059   HandleScope scope;
2060   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2061   i::Handle<i::Object> name = GetProperty(self, "scriptName");
2062   if (!name->IsString()) {
2063     return Local<String>();
2064   }
2065   return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2066 }
2067
2068
2069 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2070   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2071   if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptNameOrSourceURL()")) {
2072     return Local<String>();
2073   }
2074   ENTER_V8(isolate);
2075   HandleScope scope;
2076   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2077   i::Handle<i::Object> name = GetProperty(self, "scriptNameOrSourceURL");
2078   if (!name->IsString()) {
2079     return Local<String>();
2080   }
2081   return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2082 }
2083
2084
2085 Local<String> StackFrame::GetFunctionName() const {
2086   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2087   if (IsDeadCheck(isolate, "v8::StackFrame::GetFunctionName()")) {
2088     return Local<String>();
2089   }
2090   ENTER_V8(isolate);
2091   HandleScope scope;
2092   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2093   i::Handle<i::Object> name = GetProperty(self, "functionName");
2094   if (!name->IsString()) {
2095     return Local<String>();
2096   }
2097   return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2098 }
2099
2100
2101 bool StackFrame::IsEval() const {
2102   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2103   if (IsDeadCheck(isolate, "v8::StackFrame::IsEval()")) return false;
2104   ENTER_V8(isolate);
2105   i::HandleScope scope(isolate);
2106   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2107   i::Handle<i::Object> is_eval = GetProperty(self, "isEval");
2108   return is_eval->IsTrue();
2109 }
2110
2111
2112 bool StackFrame::IsConstructor() const {
2113   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2114   if (IsDeadCheck(isolate, "v8::StackFrame::IsConstructor()")) return false;
2115   ENTER_V8(isolate);
2116   i::HandleScope scope(isolate);
2117   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2118   i::Handle<i::Object> is_constructor = GetProperty(self, "isConstructor");
2119   return is_constructor->IsTrue();
2120 }
2121
2122
2123 // --- D a t a ---
2124
2125 bool Value::IsUndefined() const {
2126   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUndefined()")) {
2127     return false;
2128   }
2129   return Utils::OpenHandle(this)->IsUndefined();
2130 }
2131
2132
2133 bool Value::IsNull() const {
2134   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNull()")) return false;
2135   return Utils::OpenHandle(this)->IsNull();
2136 }
2137
2138
2139 bool Value::IsTrue() const {
2140   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsTrue()")) return false;
2141   return Utils::OpenHandle(this)->IsTrue();
2142 }
2143
2144
2145 bool Value::IsFalse() const {
2146   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFalse()")) return false;
2147   return Utils::OpenHandle(this)->IsFalse();
2148 }
2149
2150
2151 bool Value::IsFunction() const {
2152   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFunction()")) {
2153     return false;
2154   }
2155   return Utils::OpenHandle(this)->IsJSFunction();
2156 }
2157
2158
2159 bool Value::FullIsString() const {
2160   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsString()")) return false;
2161   bool result = Utils::OpenHandle(this)->IsString();
2162   ASSERT_EQ(result, QuickIsString());
2163   return result;
2164 }
2165
2166
2167 bool Value::IsArray() const {
2168   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsArray()")) return false;
2169   return Utils::OpenHandle(this)->IsJSArray();
2170 }
2171
2172
2173 bool Value::IsObject() const {
2174   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsObject()")) return false;
2175   return Utils::OpenHandle(this)->IsJSObject();
2176 }
2177
2178
2179 bool Value::IsNumber() const {
2180   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNumber()")) return false;
2181   return Utils::OpenHandle(this)->IsNumber();
2182 }
2183
2184
2185 bool Value::IsBoolean() const {
2186   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsBoolean()")) {
2187     return false;
2188   }
2189   return Utils::OpenHandle(this)->IsBoolean();
2190 }
2191
2192
2193 bool Value::IsExternal() const {
2194   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsExternal()")) {
2195     return false;
2196   }
2197   return Utils::OpenHandle(this)->IsForeign();
2198 }
2199
2200
2201 bool Value::IsInt32() const {
2202   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsInt32()")) return false;
2203   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2204   if (obj->IsSmi()) return true;
2205   if (obj->IsNumber()) {
2206     double value = obj->Number();
2207     return i::FastI2D(i::FastD2I(value)) == value;
2208   }
2209   return false;
2210 }
2211
2212
2213 bool Value::IsUint32() const {
2214   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUint32()")) return false;
2215   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2216   if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2217   if (obj->IsNumber()) {
2218     double value = obj->Number();
2219     return i::FastUI2D(i::FastD2UI(value)) == value;
2220   }
2221   return false;
2222 }
2223
2224
2225 bool Value::IsDate() const {
2226   i::Isolate* isolate = i::Isolate::Current();
2227   if (IsDeadCheck(isolate, "v8::Value::IsDate()")) return false;
2228   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2229   return obj->HasSpecificClassOf(isolate->heap()->Date_symbol());
2230 }
2231
2232
2233 bool Value::IsStringObject() const {
2234   i::Isolate* isolate = i::Isolate::Current();
2235   if (IsDeadCheck(isolate, "v8::Value::IsStringObject()")) return false;
2236   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2237   return obj->HasSpecificClassOf(isolate->heap()->String_symbol());
2238 }
2239
2240
2241 bool Value::IsNumberObject() const {
2242   i::Isolate* isolate = i::Isolate::Current();
2243   if (IsDeadCheck(isolate, "v8::Value::IsNumberObject()")) return false;
2244   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2245   return obj->HasSpecificClassOf(isolate->heap()->Number_symbol());
2246 }
2247
2248
2249 static i::Object* LookupBuiltin(i::Isolate* isolate,
2250                                 const char* builtin_name) {
2251   i::Handle<i::String> symbol =
2252       isolate->factory()->LookupAsciiSymbol(builtin_name);
2253   i::Handle<i::JSBuiltinsObject> builtins = isolate->js_builtins_object();
2254   return builtins->GetPropertyNoExceptionThrown(*symbol);
2255 }
2256
2257
2258 static bool CheckConstructor(i::Isolate* isolate,
2259                              i::Handle<i::JSObject> obj,
2260                              const char* class_name) {
2261   return obj->map()->constructor() == LookupBuiltin(isolate, class_name);
2262 }
2263
2264
2265 bool Value::IsNativeError() const {
2266   i::Isolate* isolate = i::Isolate::Current();
2267   if (IsDeadCheck(isolate, "v8::Value::IsNativeError()")) return false;
2268   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2269   if (obj->IsJSObject()) {
2270     i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
2271     return CheckConstructor(isolate, js_obj, "$Error") ||
2272         CheckConstructor(isolate, js_obj, "$EvalError") ||
2273         CheckConstructor(isolate, js_obj, "$RangeError") ||
2274         CheckConstructor(isolate, js_obj, "$ReferenceError") ||
2275         CheckConstructor(isolate, js_obj, "$SyntaxError") ||
2276         CheckConstructor(isolate, js_obj, "$TypeError") ||
2277         CheckConstructor(isolate, js_obj, "$URIError");
2278   } else {
2279     return false;
2280   }
2281 }
2282
2283
2284 bool Value::IsBooleanObject() const {
2285   i::Isolate* isolate = i::Isolate::Current();
2286   if (IsDeadCheck(isolate, "v8::Value::IsBooleanObject()")) return false;
2287   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2288   return obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol());
2289 }
2290
2291
2292 bool Value::IsRegExp() const {
2293   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsRegExp()")) return false;
2294   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2295   return obj->IsJSRegExp();
2296 }
2297
2298
2299 Local<String> Value::ToString() const {
2300   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2301   i::Handle<i::Object> str;
2302   if (obj->IsString()) {
2303     str = obj;
2304   } else {
2305     i::Isolate* isolate = i::Isolate::Current();
2306     if (IsDeadCheck(isolate, "v8::Value::ToString()")) {
2307       return Local<String>();
2308     }
2309     LOG_API(isolate, "ToString");
2310     ENTER_V8(isolate);
2311     EXCEPTION_PREAMBLE(isolate);
2312     str = i::Execution::ToString(obj, &has_pending_exception);
2313     EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2314   }
2315   return Local<String>(ToApi<String>(str));
2316 }
2317
2318
2319 Local<String> Value::ToDetailString() const {
2320   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2321   i::Handle<i::Object> str;
2322   if (obj->IsString()) {
2323     str = obj;
2324   } else {
2325     i::Isolate* isolate = i::Isolate::Current();
2326     if (IsDeadCheck(isolate, "v8::Value::ToDetailString()")) {
2327       return Local<String>();
2328     }
2329     LOG_API(isolate, "ToDetailString");
2330     ENTER_V8(isolate);
2331     EXCEPTION_PREAMBLE(isolate);
2332     str = i::Execution::ToDetailString(obj, &has_pending_exception);
2333     EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2334   }
2335   return Local<String>(ToApi<String>(str));
2336 }
2337
2338
2339 Local<v8::Object> Value::ToObject() const {
2340   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2341   i::Handle<i::Object> val;
2342   if (obj->IsJSObject()) {
2343     val = obj;
2344   } else {
2345     i::Isolate* isolate = i::Isolate::Current();
2346     if (IsDeadCheck(isolate, "v8::Value::ToObject()")) {
2347       return Local<v8::Object>();
2348     }
2349     LOG_API(isolate, "ToObject");
2350     ENTER_V8(isolate);
2351     EXCEPTION_PREAMBLE(isolate);
2352     val = i::Execution::ToObject(obj, &has_pending_exception);
2353     EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
2354   }
2355   return Local<v8::Object>(ToApi<Object>(val));
2356 }
2357
2358
2359 Local<Boolean> Value::ToBoolean() const {
2360   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2361   if (obj->IsBoolean()) {
2362     return Local<Boolean>(ToApi<Boolean>(obj));
2363   } else {
2364     i::Isolate* isolate = i::Isolate::Current();
2365     if (IsDeadCheck(isolate, "v8::Value::ToBoolean()")) {
2366       return Local<Boolean>();
2367     }
2368     LOG_API(isolate, "ToBoolean");
2369     ENTER_V8(isolate);
2370     i::Handle<i::Object> val = i::Execution::ToBoolean(obj);
2371     return Local<Boolean>(ToApi<Boolean>(val));
2372   }
2373 }
2374
2375
2376 Local<Number> Value::ToNumber() const {
2377   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2378   i::Handle<i::Object> num;
2379   if (obj->IsNumber()) {
2380     num = obj;
2381   } else {
2382     i::Isolate* isolate = i::Isolate::Current();
2383     if (IsDeadCheck(isolate, "v8::Value::ToNumber()")) {
2384       return Local<Number>();
2385     }
2386     LOG_API(isolate, "ToNumber");
2387     ENTER_V8(isolate);
2388     EXCEPTION_PREAMBLE(isolate);
2389     num = i::Execution::ToNumber(obj, &has_pending_exception);
2390     EXCEPTION_BAILOUT_CHECK(isolate, Local<Number>());
2391   }
2392   return Local<Number>(ToApi<Number>(num));
2393 }
2394
2395
2396 Local<Integer> Value::ToInteger() const {
2397   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2398   i::Handle<i::Object> num;
2399   if (obj->IsSmi()) {
2400     num = obj;
2401   } else {
2402     i::Isolate* isolate = i::Isolate::Current();
2403     if (IsDeadCheck(isolate, "v8::Value::ToInteger()")) return Local<Integer>();
2404     LOG_API(isolate, "ToInteger");
2405     ENTER_V8(isolate);
2406     EXCEPTION_PREAMBLE(isolate);
2407     num = i::Execution::ToInteger(obj, &has_pending_exception);
2408     EXCEPTION_BAILOUT_CHECK(isolate, Local<Integer>());
2409   }
2410   return Local<Integer>(ToApi<Integer>(num));
2411 }
2412
2413
2414 void External::CheckCast(v8::Value* that) {
2415   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Cast()")) return;
2416   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2417   ApiCheck(obj->IsForeign(),
2418            "v8::External::Cast()",
2419            "Could not convert to external");
2420 }
2421
2422
2423 void v8::Object::CheckCast(Value* that) {
2424   if (IsDeadCheck(i::Isolate::Current(), "v8::Object::Cast()")) return;
2425   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2426   ApiCheck(obj->IsJSObject(),
2427            "v8::Object::Cast()",
2428            "Could not convert to object");
2429 }
2430
2431
2432 void v8::Function::CheckCast(Value* that) {
2433   if (IsDeadCheck(i::Isolate::Current(), "v8::Function::Cast()")) return;
2434   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2435   ApiCheck(obj->IsJSFunction(),
2436            "v8::Function::Cast()",
2437            "Could not convert to function");
2438 }
2439
2440
2441 void v8::String::CheckCast(v8::Value* that) {
2442   if (IsDeadCheck(i::Isolate::Current(), "v8::String::Cast()")) return;
2443   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2444   ApiCheck(obj->IsString(),
2445            "v8::String::Cast()",
2446            "Could not convert to string");
2447 }
2448
2449
2450 void v8::Number::CheckCast(v8::Value* that) {
2451   if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Cast()")) return;
2452   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2453   ApiCheck(obj->IsNumber(),
2454            "v8::Number::Cast()",
2455            "Could not convert to number");
2456 }
2457
2458
2459 void v8::Integer::CheckCast(v8::Value* that) {
2460   if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Cast()")) return;
2461   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2462   ApiCheck(obj->IsNumber(),
2463            "v8::Integer::Cast()",
2464            "Could not convert to number");
2465 }
2466
2467
2468 void v8::Array::CheckCast(Value* that) {
2469   if (IsDeadCheck(i::Isolate::Current(), "v8::Array::Cast()")) return;
2470   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2471   ApiCheck(obj->IsJSArray(),
2472            "v8::Array::Cast()",
2473            "Could not convert to array");
2474 }
2475
2476
2477 void v8::Date::CheckCast(v8::Value* that) {
2478   i::Isolate* isolate = i::Isolate::Current();
2479   if (IsDeadCheck(isolate, "v8::Date::Cast()")) return;
2480   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2481   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Date_symbol()),
2482            "v8::Date::Cast()",
2483            "Could not convert to date");
2484 }
2485
2486
2487 void v8::StringObject::CheckCast(v8::Value* that) {
2488   i::Isolate* isolate = i::Isolate::Current();
2489   if (IsDeadCheck(isolate, "v8::StringObject::Cast()")) return;
2490   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2491   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->String_symbol()),
2492            "v8::StringObject::Cast()",
2493            "Could not convert to StringObject");
2494 }
2495
2496
2497 void v8::NumberObject::CheckCast(v8::Value* that) {
2498   i::Isolate* isolate = i::Isolate::Current();
2499   if (IsDeadCheck(isolate, "v8::NumberObject::Cast()")) return;
2500   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2501   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Number_symbol()),
2502            "v8::NumberObject::Cast()",
2503            "Could not convert to NumberObject");
2504 }
2505
2506
2507 void v8::BooleanObject::CheckCast(v8::Value* that) {
2508   i::Isolate* isolate = i::Isolate::Current();
2509   if (IsDeadCheck(isolate, "v8::BooleanObject::Cast()")) return;
2510   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2511   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol()),
2512            "v8::BooleanObject::Cast()",
2513            "Could not convert to BooleanObject");
2514 }
2515
2516
2517 void v8::RegExp::CheckCast(v8::Value* that) {
2518   if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::Cast()")) return;
2519   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2520   ApiCheck(obj->IsJSRegExp(),
2521            "v8::RegExp::Cast()",
2522            "Could not convert to regular expression");
2523 }
2524
2525
2526 bool Value::BooleanValue() const {
2527   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2528   if (obj->IsBoolean()) {
2529     return obj->IsTrue();
2530   } else {
2531     i::Isolate* isolate = i::Isolate::Current();
2532     if (IsDeadCheck(isolate, "v8::Value::BooleanValue()")) return false;
2533     LOG_API(isolate, "BooleanValue");
2534     ENTER_V8(isolate);
2535     i::Handle<i::Object> value = i::Execution::ToBoolean(obj);
2536     return value->IsTrue();
2537   }
2538 }
2539
2540
2541 double Value::NumberValue() const {
2542   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2543   i::Handle<i::Object> num;
2544   if (obj->IsNumber()) {
2545     num = obj;
2546   } else {
2547     i::Isolate* isolate = i::Isolate::Current();
2548     if (IsDeadCheck(isolate, "v8::Value::NumberValue()")) {
2549       return i::OS::nan_value();
2550     }
2551     LOG_API(isolate, "NumberValue");
2552     ENTER_V8(isolate);
2553     EXCEPTION_PREAMBLE(isolate);
2554     num = i::Execution::ToNumber(obj, &has_pending_exception);
2555     EXCEPTION_BAILOUT_CHECK(isolate, i::OS::nan_value());
2556   }
2557   return num->Number();
2558 }
2559
2560
2561 int64_t Value::IntegerValue() const {
2562   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2563   i::Handle<i::Object> num;
2564   if (obj->IsNumber()) {
2565     num = obj;
2566   } else {
2567     i::Isolate* isolate = i::Isolate::Current();
2568     if (IsDeadCheck(isolate, "v8::Value::IntegerValue()")) return 0;
2569     LOG_API(isolate, "IntegerValue");
2570     ENTER_V8(isolate);
2571     EXCEPTION_PREAMBLE(isolate);
2572     num = i::Execution::ToInteger(obj, &has_pending_exception);
2573     EXCEPTION_BAILOUT_CHECK(isolate, 0);
2574   }
2575   if (num->IsSmi()) {
2576     return i::Smi::cast(*num)->value();
2577   } else {
2578     return static_cast<int64_t>(num->Number());
2579   }
2580 }
2581
2582
2583 Local<Int32> Value::ToInt32() const {
2584   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2585   i::Handle<i::Object> num;
2586   if (obj->IsSmi()) {
2587     num = obj;
2588   } else {
2589     i::Isolate* isolate = i::Isolate::Current();
2590     if (IsDeadCheck(isolate, "v8::Value::ToInt32()")) return Local<Int32>();
2591     LOG_API(isolate, "ToInt32");
2592     ENTER_V8(isolate);
2593     EXCEPTION_PREAMBLE(isolate);
2594     num = i::Execution::ToInt32(obj, &has_pending_exception);
2595     EXCEPTION_BAILOUT_CHECK(isolate, Local<Int32>());
2596   }
2597   return Local<Int32>(ToApi<Int32>(num));
2598 }
2599
2600
2601 Local<Uint32> Value::ToUint32() const {
2602   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2603   i::Handle<i::Object> num;
2604   if (obj->IsSmi()) {
2605     num = obj;
2606   } else {
2607     i::Isolate* isolate = i::Isolate::Current();
2608     if (IsDeadCheck(isolate, "v8::Value::ToUint32()")) return Local<Uint32>();
2609     LOG_API(isolate, "ToUInt32");
2610     ENTER_V8(isolate);
2611     EXCEPTION_PREAMBLE(isolate);
2612     num = i::Execution::ToUint32(obj, &has_pending_exception);
2613     EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2614   }
2615   return Local<Uint32>(ToApi<Uint32>(num));
2616 }
2617
2618
2619 Local<Uint32> Value::ToArrayIndex() const {
2620   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2621   if (obj->IsSmi()) {
2622     if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
2623     return Local<Uint32>();
2624   }
2625   i::Isolate* isolate = i::Isolate::Current();
2626   if (IsDeadCheck(isolate, "v8::Value::ToArrayIndex()")) return Local<Uint32>();
2627   LOG_API(isolate, "ToArrayIndex");
2628   ENTER_V8(isolate);
2629   EXCEPTION_PREAMBLE(isolate);
2630   i::Handle<i::Object> string_obj =
2631       i::Execution::ToString(obj, &has_pending_exception);
2632   EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2633   i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
2634   uint32_t index;
2635   if (str->AsArrayIndex(&index)) {
2636     i::Handle<i::Object> value;
2637     if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
2638       value = i::Handle<i::Object>(i::Smi::FromInt(index));
2639     } else {
2640       value = isolate->factory()->NewNumber(index);
2641     }
2642     return Utils::Uint32ToLocal(value);
2643   }
2644   return Local<Uint32>();
2645 }
2646
2647
2648 int32_t Value::Int32Value() const {
2649   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2650   if (obj->IsSmi()) {
2651     return i::Smi::cast(*obj)->value();
2652   } else {
2653     i::Isolate* isolate = i::Isolate::Current();
2654     if (IsDeadCheck(isolate, "v8::Value::Int32Value()")) return 0;
2655     LOG_API(isolate, "Int32Value (slow)");
2656     ENTER_V8(isolate);
2657     EXCEPTION_PREAMBLE(isolate);
2658     i::Handle<i::Object> num =
2659         i::Execution::ToInt32(obj, &has_pending_exception);
2660     EXCEPTION_BAILOUT_CHECK(isolate, 0);
2661     if (num->IsSmi()) {
2662       return i::Smi::cast(*num)->value();
2663     } else {
2664       return static_cast<int32_t>(num->Number());
2665     }
2666   }
2667 }
2668
2669
2670 bool Value::Equals(Handle<Value> that) const {
2671   i::Isolate* isolate = i::Isolate::Current();
2672   if (IsDeadCheck(isolate, "v8::Value::Equals()")
2673       || EmptyCheck("v8::Value::Equals()", this)
2674       || EmptyCheck("v8::Value::Equals()", that)) {
2675     return false;
2676   }
2677   LOG_API(isolate, "Equals");
2678   ENTER_V8(isolate);
2679   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2680   i::Handle<i::Object> other = Utils::OpenHandle(*that);
2681   // If both obj and other are JSObjects, we'd better compare by identity
2682   // immediately when going into JS builtin.  The reason is Invoke
2683   // would overwrite global object receiver with global proxy.
2684   if (obj->IsJSObject() && other->IsJSObject()) {
2685     return *obj == *other;
2686   }
2687   i::Handle<i::Object> args[] = { other };
2688   EXCEPTION_PREAMBLE(isolate);
2689   i::Handle<i::Object> result =
2690       CallV8HeapFunction("EQUALS", obj, ARRAY_SIZE(args), args,
2691                          &has_pending_exception);
2692   EXCEPTION_BAILOUT_CHECK(isolate, false);
2693   return *result == i::Smi::FromInt(i::EQUAL);
2694 }
2695
2696
2697 bool Value::StrictEquals(Handle<Value> that) const {
2698   i::Isolate* isolate = i::Isolate::Current();
2699   if (IsDeadCheck(isolate, "v8::Value::StrictEquals()")
2700       || EmptyCheck("v8::Value::StrictEquals()", this)
2701       || EmptyCheck("v8::Value::StrictEquals()", that)) {
2702     return false;
2703   }
2704   LOG_API(isolate, "StrictEquals");
2705   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2706   i::Handle<i::Object> other = Utils::OpenHandle(*that);
2707   // Must check HeapNumber first, since NaN !== NaN.
2708   if (obj->IsHeapNumber()) {
2709     if (!other->IsNumber()) return false;
2710     double x = obj->Number();
2711     double y = other->Number();
2712     // Must check explicitly for NaN:s on Windows, but -0 works fine.
2713     return x == y && !isnan(x) && !isnan(y);
2714   } else if (*obj == *other) {  // Also covers Booleans.
2715     return true;
2716   } else if (obj->IsSmi()) {
2717     return other->IsNumber() && obj->Number() == other->Number();
2718   } else if (obj->IsString()) {
2719     return other->IsString() &&
2720       i::String::cast(*obj)->Equals(i::String::cast(*other));
2721   } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
2722     return other->IsUndefined() || other->IsUndetectableObject();
2723   } else {
2724     return false;
2725   }
2726 }
2727
2728
2729 uint32_t Value::Uint32Value() const {
2730   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2731   if (obj->IsSmi()) {
2732     return i::Smi::cast(*obj)->value();
2733   } else {
2734     i::Isolate* isolate = i::Isolate::Current();
2735     if (IsDeadCheck(isolate, "v8::Value::Uint32Value()")) return 0;
2736     LOG_API(isolate, "Uint32Value");
2737     ENTER_V8(isolate);
2738     EXCEPTION_PREAMBLE(isolate);
2739     i::Handle<i::Object> num =
2740         i::Execution::ToUint32(obj, &has_pending_exception);
2741     EXCEPTION_BAILOUT_CHECK(isolate, 0);
2742     if (num->IsSmi()) {
2743       return i::Smi::cast(*num)->value();
2744     } else {
2745       return static_cast<uint32_t>(num->Number());
2746     }
2747   }
2748 }
2749
2750
2751 bool v8::Object::Set(v8::Handle<Value> key, v8::Handle<Value> value,
2752                      v8::PropertyAttribute attribs) {
2753   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2754   ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2755   ENTER_V8(isolate);
2756   i::HandleScope scope(isolate);
2757   i::Handle<i::Object> self = Utils::OpenHandle(this);
2758   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2759   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2760   EXCEPTION_PREAMBLE(isolate);
2761   i::Handle<i::Object> obj = i::SetProperty(
2762       self,
2763       key_obj,
2764       value_obj,
2765       static_cast<PropertyAttributes>(attribs),
2766       i::kNonStrictMode);
2767   has_pending_exception = obj.is_null();
2768   EXCEPTION_BAILOUT_CHECK(isolate, false);
2769   return true;
2770 }
2771
2772
2773 bool v8::Object::Set(uint32_t index, v8::Handle<Value> value) {
2774   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2775   ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2776   ENTER_V8(isolate);
2777   i::HandleScope scope(isolate);
2778   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2779   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2780   EXCEPTION_PREAMBLE(isolate);
2781   i::Handle<i::Object> obj = i::SetElement(
2782       self,
2783       index,
2784       value_obj,
2785       i::kNonStrictMode);
2786   has_pending_exception = obj.is_null();
2787   EXCEPTION_BAILOUT_CHECK(isolate, false);
2788   return true;
2789 }
2790
2791
2792 bool v8::Object::ForceSet(v8::Handle<Value> key,
2793                           v8::Handle<Value> value,
2794                           v8::PropertyAttribute attribs) {
2795   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2796   ON_BAILOUT(isolate, "v8::Object::ForceSet()", return false);
2797   ENTER_V8(isolate);
2798   i::HandleScope scope(isolate);
2799   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2800   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2801   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2802   EXCEPTION_PREAMBLE(isolate);
2803   i::Handle<i::Object> obj = i::ForceSetProperty(
2804       self,
2805       key_obj,
2806       value_obj,
2807       static_cast<PropertyAttributes>(attribs));
2808   has_pending_exception = obj.is_null();
2809   EXCEPTION_BAILOUT_CHECK(isolate, false);
2810   return true;
2811 }
2812
2813
2814 bool v8::Object::ForceDelete(v8::Handle<Value> key) {
2815   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2816   ON_BAILOUT(isolate, "v8::Object::ForceDelete()", return false);
2817   ENTER_V8(isolate);
2818   i::HandleScope scope(isolate);
2819   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2820   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2821
2822   // When turning on access checks for a global object deoptimize all functions
2823   // as optimized code does not always handle access checks.
2824   i::Deoptimizer::DeoptimizeGlobalObject(*self);
2825
2826   EXCEPTION_PREAMBLE(isolate);
2827   i::Handle<i::Object> obj = i::ForceDeleteProperty(self, key_obj);
2828   has_pending_exception = obj.is_null();
2829   EXCEPTION_BAILOUT_CHECK(isolate, false);
2830   return obj->IsTrue();
2831 }
2832
2833
2834 Local<Value> v8::Object::Get(v8::Handle<Value> key) {
2835   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2836   ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2837   ENTER_V8(isolate);
2838   i::Handle<i::Object> self = Utils::OpenHandle(this);
2839   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2840   EXCEPTION_PREAMBLE(isolate);
2841   i::Handle<i::Object> result = i::GetProperty(self, key_obj);
2842   has_pending_exception = result.is_null();
2843   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2844   return Utils::ToLocal(result);
2845 }
2846
2847
2848 Local<Value> v8::Object::Get(uint32_t index) {
2849   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2850   ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2851   ENTER_V8(isolate);
2852   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2853   EXCEPTION_PREAMBLE(isolate);
2854   i::Handle<i::Object> result = i::Object::GetElement(self, index);
2855   has_pending_exception = result.is_null();
2856   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2857   return Utils::ToLocal(result);
2858 }
2859
2860
2861 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Handle<Value> key) {
2862   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2863   ON_BAILOUT(isolate, "v8::Object::GetPropertyAttribute()",
2864              return static_cast<PropertyAttribute>(NONE));
2865   ENTER_V8(isolate);
2866   i::HandleScope scope(isolate);
2867   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2868   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2869   if (!key_obj->IsString()) {
2870     EXCEPTION_PREAMBLE(isolate);
2871     key_obj = i::Execution::ToString(key_obj, &has_pending_exception);
2872     EXCEPTION_BAILOUT_CHECK(isolate, static_cast<PropertyAttribute>(NONE));
2873   }
2874   i::Handle<i::String> key_string = i::Handle<i::String>::cast(key_obj);
2875   PropertyAttributes result = self->GetPropertyAttribute(*key_string);
2876   if (result == ABSENT) return static_cast<PropertyAttribute>(NONE);
2877   return static_cast<PropertyAttribute>(result);
2878 }
2879
2880
2881 Local<Value> v8::Object::GetPrototype() {
2882   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2883   ON_BAILOUT(isolate, "v8::Object::GetPrototype()",
2884              return Local<v8::Value>());
2885   ENTER_V8(isolate);
2886   i::Handle<i::Object> self = Utils::OpenHandle(this);
2887   i::Handle<i::Object> result = i::GetPrototype(self);
2888   return Utils::ToLocal(result);
2889 }
2890
2891
2892 bool v8::Object::SetPrototype(Handle<Value> value) {
2893   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2894   ON_BAILOUT(isolate, "v8::Object::SetPrototype()", return false);
2895   ENTER_V8(isolate);
2896   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2897   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2898   // We do not allow exceptions thrown while setting the prototype
2899   // to propagate outside.
2900   TryCatch try_catch;
2901   EXCEPTION_PREAMBLE(isolate);
2902   i::Handle<i::Object> result = i::SetPrototype(self, value_obj);
2903   has_pending_exception = result.is_null();
2904   EXCEPTION_BAILOUT_CHECK(isolate, false);
2905   return true;
2906 }
2907
2908
2909 Local<Object> v8::Object::FindInstanceInPrototypeChain(
2910     v8::Handle<FunctionTemplate> tmpl) {
2911   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2912   ON_BAILOUT(isolate,
2913              "v8::Object::FindInstanceInPrototypeChain()",
2914              return Local<v8::Object>());
2915   ENTER_V8(isolate);
2916   i::JSObject* object = *Utils::OpenHandle(this);
2917   i::FunctionTemplateInfo* tmpl_info = *Utils::OpenHandle(*tmpl);
2918   while (!object->IsInstanceOf(tmpl_info)) {
2919     i::Object* prototype = object->GetPrototype();
2920     if (!prototype->IsJSObject()) return Local<Object>();
2921     object = i::JSObject::cast(prototype);
2922   }
2923   return Utils::ToLocal(i::Handle<i::JSObject>(object));
2924 }
2925
2926
2927 Local<Array> v8::Object::GetPropertyNames() {
2928   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2929   ON_BAILOUT(isolate, "v8::Object::GetPropertyNames()",
2930              return Local<v8::Array>());
2931   ENTER_V8(isolate);
2932   i::HandleScope scope(isolate);
2933   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2934   bool threw = false;
2935   i::Handle<i::FixedArray> value =
2936       i::GetKeysInFixedArrayFor(self, i::INCLUDE_PROTOS, &threw);
2937   if (threw) return Local<v8::Array>();
2938   // Because we use caching to speed up enumeration it is important
2939   // to never change the result of the basic enumeration function so
2940   // we clone the result.
2941   i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2942   i::Handle<i::JSArray> result =
2943       isolate->factory()->NewJSArrayWithElements(elms);
2944   return Utils::ToLocal(scope.CloseAndEscape(result));
2945 }
2946
2947
2948 Local<Array> v8::Object::GetOwnPropertyNames() {
2949   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2950   ON_BAILOUT(isolate, "v8::Object::GetOwnPropertyNames()",
2951              return Local<v8::Array>());
2952   ENTER_V8(isolate);
2953   i::HandleScope scope(isolate);
2954   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2955   bool threw = false;
2956   i::Handle<i::FixedArray> value =
2957       i::GetKeysInFixedArrayFor(self, i::LOCAL_ONLY, &threw);
2958   if (threw) return Local<v8::Array>();
2959   // Because we use caching to speed up enumeration it is important
2960   // to never change the result of the basic enumeration function so
2961   // we clone the result.
2962   i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2963   i::Handle<i::JSArray> result =
2964       isolate->factory()->NewJSArrayWithElements(elms);
2965   return Utils::ToLocal(scope.CloseAndEscape(result));
2966 }
2967
2968
2969 Local<String> v8::Object::ObjectProtoToString() {
2970   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2971   ON_BAILOUT(isolate, "v8::Object::ObjectProtoToString()",
2972              return Local<v8::String>());
2973   ENTER_V8(isolate);
2974   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2975
2976   i::Handle<i::Object> name(self->class_name());
2977
2978   // Native implementation of Object.prototype.toString (v8natives.js):
2979   //   var c = %ClassOf(this);
2980   //   if (c === 'Arguments') c  = 'Object';
2981   //   return "[object " + c + "]";
2982
2983   if (!name->IsString()) {
2984     return v8::String::New("[object ]");
2985
2986   } else {
2987     i::Handle<i::String> class_name = i::Handle<i::String>::cast(name);
2988     if (class_name->IsEqualTo(i::CStrVector("Arguments"))) {
2989       return v8::String::New("[object Object]");
2990
2991     } else {
2992       const char* prefix = "[object ";
2993       Local<String> str = Utils::ToLocal(class_name);
2994       const char* postfix = "]";
2995
2996       int prefix_len = i::StrLength(prefix);
2997       int str_len = str->Length();
2998       int postfix_len = i::StrLength(postfix);
2999
3000       int buf_len = prefix_len + str_len + postfix_len;
3001       i::ScopedVector<char> buf(buf_len);
3002
3003       // Write prefix.
3004       char* ptr = buf.start();
3005       memcpy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3006       ptr += prefix_len;
3007
3008       // Write real content.
3009       str->WriteAscii(ptr, 0, str_len);
3010       ptr += str_len;
3011
3012       // Write postfix.
3013       memcpy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3014
3015       // Copy the buffer into a heap-allocated string and return it.
3016       Local<String> result = v8::String::New(buf.start(), buf_len);
3017       return result;
3018     }
3019   }
3020 }
3021
3022
3023 Local<String> v8::Object::GetConstructorName() {
3024   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3025   ON_BAILOUT(isolate, "v8::Object::GetConstructorName()",
3026              return Local<v8::String>());
3027   ENTER_V8(isolate);
3028   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3029   i::Handle<i::String> name(self->constructor_name());
3030   return Utils::ToLocal(name);
3031 }
3032
3033
3034 bool v8::Object::Delete(v8::Handle<String> key) {
3035   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3036   ON_BAILOUT(isolate, "v8::Object::Delete()", return false);
3037   ENTER_V8(isolate);
3038   i::HandleScope scope(isolate);
3039   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3040   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3041   return i::DeleteProperty(self, key_obj)->IsTrue();
3042 }
3043
3044
3045 bool v8::Object::Has(v8::Handle<String> key) {
3046   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3047   ON_BAILOUT(isolate, "v8::Object::Has()", return false);
3048   ENTER_V8(isolate);
3049   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3050   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3051   return self->HasProperty(*key_obj);
3052 }
3053
3054
3055 bool v8::Object::Delete(uint32_t index) {
3056   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3057   ON_BAILOUT(isolate, "v8::Object::DeleteProperty()",
3058              return false);
3059   ENTER_V8(isolate);
3060   HandleScope scope;
3061   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3062   return i::DeleteElement(self, index)->IsTrue();
3063 }
3064
3065
3066 bool v8::Object::Has(uint32_t index) {
3067   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3068   ON_BAILOUT(isolate, "v8::Object::HasProperty()", return false);
3069   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3070   return self->HasElement(index);
3071 }
3072
3073
3074 bool Object::SetAccessor(Handle<String> name,
3075                          AccessorGetter getter,
3076                          AccessorSetter setter,
3077                          v8::Handle<Value> data,
3078                          AccessControl settings,
3079                          PropertyAttribute attributes) {
3080   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3081   ON_BAILOUT(isolate, "v8::Object::SetAccessor()", return false);
3082   ENTER_V8(isolate);
3083   i::HandleScope scope(isolate);
3084   i::Handle<i::AccessorInfo> info = MakeAccessorInfo(name,
3085                                                      getter, setter, data,
3086                                                      settings, attributes);
3087   i::Handle<i::Object> result = i::SetAccessor(Utils::OpenHandle(this), info);
3088   return !result.is_null() && !result->IsUndefined();
3089 }
3090
3091
3092 bool v8::Object::HasOwnProperty(Handle<String> key) {
3093   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3094   ON_BAILOUT(isolate, "v8::Object::HasOwnProperty()",
3095              return false);
3096   return Utils::OpenHandle(this)->HasLocalProperty(
3097       *Utils::OpenHandle(*key));
3098 }
3099
3100
3101 bool v8::Object::HasRealNamedProperty(Handle<String> key) {
3102   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3103   ON_BAILOUT(isolate, "v8::Object::HasRealNamedProperty()",
3104              return false);
3105   return Utils::OpenHandle(this)->HasRealNamedProperty(
3106       *Utils::OpenHandle(*key));
3107 }
3108
3109
3110 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
3111   ON_BAILOUT(Utils::OpenHandle(this)->GetIsolate(),
3112              "v8::Object::HasRealIndexedProperty()",
3113              return false);
3114   return Utils::OpenHandle(this)->HasRealElementProperty(index);
3115 }
3116
3117
3118 bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
3119   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3120   ON_BAILOUT(isolate,
3121              "v8::Object::HasRealNamedCallbackProperty()",
3122              return false);
3123   ENTER_V8(isolate);
3124   return Utils::OpenHandle(this)->HasRealNamedCallbackProperty(
3125       *Utils::OpenHandle(*key));
3126 }
3127
3128
3129 bool v8::Object::HasNamedLookupInterceptor() {
3130   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3131   ON_BAILOUT(isolate, "v8::Object::HasNamedLookupInterceptor()",
3132              return false);
3133   return Utils::OpenHandle(this)->HasNamedInterceptor();
3134 }
3135
3136
3137 bool v8::Object::HasIndexedLookupInterceptor() {
3138   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3139   ON_BAILOUT(isolate, "v8::Object::HasIndexedLookupInterceptor()",
3140              return false);
3141   return Utils::OpenHandle(this)->HasIndexedInterceptor();
3142 }
3143
3144
3145 static Local<Value> GetPropertyByLookup(i::Isolate* isolate,
3146                                         i::Handle<i::JSObject> receiver,
3147                                         i::Handle<i::String> name,
3148                                         i::LookupResult* lookup) {
3149   if (!lookup->IsProperty()) {
3150     // No real property was found.
3151     return Local<Value>();
3152   }
3153
3154   // If the property being looked up is a callback, it can throw
3155   // an exception.
3156   EXCEPTION_PREAMBLE(isolate);
3157   PropertyAttributes ignored;
3158   i::Handle<i::Object> result =
3159       i::Object::GetProperty(receiver, receiver, lookup, name,
3160                              &ignored);
3161   has_pending_exception = result.is_null();
3162   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3163
3164   return Utils::ToLocal(result);
3165 }
3166
3167
3168 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
3169       Handle<String> key) {
3170   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3171   ON_BAILOUT(isolate,
3172              "v8::Object::GetRealNamedPropertyInPrototypeChain()",
3173              return Local<Value>());
3174   ENTER_V8(isolate);
3175   i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3176   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3177   i::LookupResult lookup(isolate);
3178   self_obj->LookupRealNamedPropertyInPrototypes(*key_obj, &lookup);
3179   return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3180 }
3181
3182
3183 Local<Value> v8::Object::GetRealNamedProperty(Handle<String> key) {
3184   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3185   ON_BAILOUT(isolate, "v8::Object::GetRealNamedProperty()",
3186              return Local<Value>());
3187   ENTER_V8(isolate);
3188   i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3189   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3190   i::LookupResult lookup(isolate);
3191   self_obj->LookupRealNamedProperty(*key_obj, &lookup);
3192   return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3193 }
3194
3195
3196 // Turns on access checks by copying the map and setting the check flag.
3197 // Because the object gets a new map, existing inline cache caching
3198 // the old map of this object will fail.
3199 void v8::Object::TurnOnAccessCheck() {
3200   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3201   ON_BAILOUT(isolate, "v8::Object::TurnOnAccessCheck()", return);
3202   ENTER_V8(isolate);
3203   i::HandleScope scope(isolate);
3204   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3205
3206   // When turning on access checks for a global object deoptimize all functions
3207   // as optimized code does not always handle access checks.
3208   i::Deoptimizer::DeoptimizeGlobalObject(*obj);
3209
3210   i::Handle<i::Map> new_map =
3211       isolate->factory()->CopyMapDropTransitions(i::Handle<i::Map>(obj->map()));
3212   new_map->set_is_access_check_needed(true);
3213   obj->set_map(*new_map);
3214 }
3215
3216
3217 bool v8::Object::IsDirty() {
3218   return Utils::OpenHandle(this)->IsDirty();
3219 }
3220
3221
3222 Local<v8::Object> v8::Object::Clone() {
3223   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3224   ON_BAILOUT(isolate, "v8::Object::Clone()", return Local<Object>());
3225   ENTER_V8(isolate);
3226   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3227   EXCEPTION_PREAMBLE(isolate);
3228   i::Handle<i::JSObject> result = i::Copy(self);
3229   has_pending_exception = result.is_null();
3230   EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3231   return Utils::ToLocal(result);
3232 }
3233
3234
3235 static i::Context* GetCreationContext(i::JSObject* object) {
3236   i::Object* constructor = object->map()->constructor();
3237   i::JSFunction* function;
3238   if (!constructor->IsJSFunction()) {
3239     // Functions have null as a constructor,
3240     // but any JSFunction knows its context immediately.
3241     ASSERT(object->IsJSFunction());
3242     function = i::JSFunction::cast(object);
3243   } else {
3244     function = i::JSFunction::cast(constructor);
3245   }
3246   return function->context()->global_context();
3247 }
3248
3249
3250 Local<v8::Context> v8::Object::CreationContext() {
3251   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3252   ON_BAILOUT(isolate,
3253              "v8::Object::CreationContext()", return Local<v8::Context>());
3254   ENTER_V8(isolate);
3255   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3256   i::Context* context = GetCreationContext(*self);
3257   return Utils::ToLocal(i::Handle<i::Context>(context));
3258 }
3259
3260
3261 int v8::Object::GetIdentityHash() {
3262   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3263   ON_BAILOUT(isolate, "v8::Object::GetIdentityHash()", return 0);
3264   ENTER_V8(isolate);
3265   i::HandleScope scope(isolate);
3266   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3267   return i::GetIdentityHash(self);
3268 }
3269
3270
3271 bool v8::Object::SetHiddenValue(v8::Handle<v8::String> key,
3272                                 v8::Handle<v8::Value> value) {
3273   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3274   ON_BAILOUT(isolate, "v8::Object::SetHiddenValue()", return false);
3275   ENTER_V8(isolate);
3276   i::HandleScope scope(isolate);
3277   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3278   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3279   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3280   i::Handle<i::Object> result = i::SetHiddenProperty(self, key_obj, value_obj);
3281   return *result == *self;
3282 }
3283
3284
3285 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Handle<v8::String> key) {
3286   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3287   ON_BAILOUT(isolate, "v8::Object::GetHiddenValue()",
3288              return Local<v8::Value>());
3289   ENTER_V8(isolate);
3290   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3291   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3292   i::Handle<i::Object> result(self->GetHiddenProperty(*key_obj));
3293   if (result->IsUndefined()) return v8::Local<v8::Value>();
3294   return Utils::ToLocal(result);
3295 }
3296
3297
3298 bool v8::Object::DeleteHiddenValue(v8::Handle<v8::String> key) {
3299   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3300   ON_BAILOUT(isolate, "v8::DeleteHiddenValue()", return false);
3301   ENTER_V8(isolate);
3302   i::HandleScope scope(isolate);
3303   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3304   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3305   self->DeleteHiddenProperty(*key_obj);
3306   return true;
3307 }
3308
3309
3310 namespace {
3311
3312 static i::ElementsKind GetElementsKindFromExternalArrayType(
3313     ExternalArrayType array_type) {
3314   switch (array_type) {
3315     case kExternalByteArray:
3316       return i::EXTERNAL_BYTE_ELEMENTS;
3317       break;
3318     case kExternalUnsignedByteArray:
3319       return i::EXTERNAL_UNSIGNED_BYTE_ELEMENTS;
3320       break;
3321     case kExternalShortArray:
3322       return i::EXTERNAL_SHORT_ELEMENTS;
3323       break;
3324     case kExternalUnsignedShortArray:
3325       return i::EXTERNAL_UNSIGNED_SHORT_ELEMENTS;
3326       break;
3327     case kExternalIntArray:
3328       return i::EXTERNAL_INT_ELEMENTS;
3329       break;
3330     case kExternalUnsignedIntArray:
3331       return i::EXTERNAL_UNSIGNED_INT_ELEMENTS;
3332       break;
3333     case kExternalFloatArray:
3334       return i::EXTERNAL_FLOAT_ELEMENTS;
3335       break;
3336     case kExternalDoubleArray:
3337       return i::EXTERNAL_DOUBLE_ELEMENTS;
3338       break;
3339     case kExternalPixelArray:
3340       return i::EXTERNAL_PIXEL_ELEMENTS;
3341       break;
3342   }
3343   UNREACHABLE();
3344   return i::DICTIONARY_ELEMENTS;
3345 }
3346
3347
3348 void PrepareExternalArrayElements(i::Handle<i::JSObject> object,
3349                                   void* data,
3350                                   ExternalArrayType array_type,
3351                                   int length) {
3352   i::Isolate* isolate = object->GetIsolate();
3353   i::Handle<i::ExternalArray> array =
3354       isolate->factory()->NewExternalArray(length, array_type, data);
3355
3356   i::Handle<i::Map> external_array_map =
3357       isolate->factory()->GetElementsTransitionMap(
3358           object,
3359           GetElementsKindFromExternalArrayType(array_type));
3360
3361   object->set_map(*external_array_map);
3362   object->set_elements(*array);
3363 }
3364
3365 }  // namespace
3366
3367
3368 void v8::Object::SetIndexedPropertiesToPixelData(uint8_t* data, int length) {
3369   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3370   ON_BAILOUT(isolate, "v8::SetElementsToPixelData()", return);
3371   ENTER_V8(isolate);
3372   i::HandleScope scope(isolate);
3373   if (!ApiCheck(length <= i::ExternalPixelArray::kMaxLength,
3374                 "v8::Object::SetIndexedPropertiesToPixelData()",
3375                 "length exceeds max acceptable value")) {
3376     return;
3377   }
3378   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3379   if (!ApiCheck(!self->IsJSArray(),
3380                 "v8::Object::SetIndexedPropertiesToPixelData()",
3381                 "JSArray is not supported")) {
3382     return;
3383   }
3384   PrepareExternalArrayElements(self, data, kExternalPixelArray, length);
3385 }
3386
3387
3388 bool v8::Object::HasIndexedPropertiesInPixelData() {
3389   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3390   ON_BAILOUT(self->GetIsolate(), "v8::HasIndexedPropertiesInPixelData()",
3391              return false);
3392   return self->HasExternalPixelElements();
3393 }
3394
3395
3396 uint8_t* v8::Object::GetIndexedPropertiesPixelData() {
3397   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3398   ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelData()",
3399              return NULL);
3400   if (self->HasExternalPixelElements()) {
3401     return i::ExternalPixelArray::cast(self->elements())->
3402         external_pixel_pointer();
3403   } else {
3404     return NULL;
3405   }
3406 }
3407
3408
3409 int v8::Object::GetIndexedPropertiesPixelDataLength() {
3410   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3411   ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelDataLength()",
3412              return -1);
3413   if (self->HasExternalPixelElements()) {
3414     return i::ExternalPixelArray::cast(self->elements())->length();
3415   } else {
3416     return -1;
3417   }
3418 }
3419
3420
3421 void v8::Object::SetIndexedPropertiesToExternalArrayData(
3422     void* data,
3423     ExternalArrayType array_type,
3424     int length) {
3425   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3426   ON_BAILOUT(isolate, "v8::SetIndexedPropertiesToExternalArrayData()", return);
3427   ENTER_V8(isolate);
3428   i::HandleScope scope(isolate);
3429   if (!ApiCheck(length <= i::ExternalArray::kMaxLength,
3430                 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3431                 "length exceeds max acceptable value")) {
3432     return;
3433   }
3434   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3435   if (!ApiCheck(!self->IsJSArray(),
3436                 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3437                 "JSArray is not supported")) {
3438     return;
3439   }
3440   PrepareExternalArrayElements(self, data, array_type, length);
3441 }
3442
3443
3444 bool v8::Object::HasIndexedPropertiesInExternalArrayData() {
3445   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3446   ON_BAILOUT(self->GetIsolate(),
3447              "v8::HasIndexedPropertiesInExternalArrayData()",
3448              return false);
3449   return self->HasExternalArrayElements();
3450 }
3451
3452
3453 void* v8::Object::GetIndexedPropertiesExternalArrayData() {
3454   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3455   ON_BAILOUT(self->GetIsolate(),
3456              "v8::GetIndexedPropertiesExternalArrayData()",
3457              return NULL);
3458   if (self->HasExternalArrayElements()) {
3459     return i::ExternalArray::cast(self->elements())->external_pointer();
3460   } else {
3461     return NULL;
3462   }
3463 }
3464
3465
3466 ExternalArrayType v8::Object::GetIndexedPropertiesExternalArrayDataType() {
3467   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3468   ON_BAILOUT(self->GetIsolate(),
3469              "v8::GetIndexedPropertiesExternalArrayDataType()",
3470              return static_cast<ExternalArrayType>(-1));
3471   switch (self->elements()->map()->instance_type()) {
3472     case i::EXTERNAL_BYTE_ARRAY_TYPE:
3473       return kExternalByteArray;
3474     case i::EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
3475       return kExternalUnsignedByteArray;
3476     case i::EXTERNAL_SHORT_ARRAY_TYPE:
3477       return kExternalShortArray;
3478     case i::EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
3479       return kExternalUnsignedShortArray;
3480     case i::EXTERNAL_INT_ARRAY_TYPE:
3481       return kExternalIntArray;
3482     case i::EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
3483       return kExternalUnsignedIntArray;
3484     case i::EXTERNAL_FLOAT_ARRAY_TYPE:
3485       return kExternalFloatArray;
3486     case i::EXTERNAL_DOUBLE_ARRAY_TYPE:
3487       return kExternalDoubleArray;
3488     case i::EXTERNAL_PIXEL_ARRAY_TYPE:
3489       return kExternalPixelArray;
3490     default:
3491       return static_cast<ExternalArrayType>(-1);
3492   }
3493 }
3494
3495
3496 int v8::Object::GetIndexedPropertiesExternalArrayDataLength() {
3497   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3498   ON_BAILOUT(self->GetIsolate(),
3499              "v8::GetIndexedPropertiesExternalArrayDataLength()",
3500              return 0);
3501   if (self->HasExternalArrayElements()) {
3502     return i::ExternalArray::cast(self->elements())->length();
3503   } else {
3504     return -1;
3505   }
3506 }
3507
3508
3509 bool v8::Object::IsCallable() {
3510   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3511   ON_BAILOUT(isolate, "v8::Object::IsCallable()", return false);
3512   ENTER_V8(isolate);
3513   i::HandleScope scope(isolate);
3514   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3515   if (obj->IsJSFunction()) return true;
3516   return i::Execution::GetFunctionDelegate(obj)->IsJSFunction();
3517 }
3518
3519
3520 Local<v8::Value> Object::CallAsFunction(v8::Handle<v8::Object> recv,
3521                                         int argc,
3522                                         v8::Handle<v8::Value> argv[]) {
3523   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3524   ON_BAILOUT(isolate, "v8::Object::CallAsFunction()",
3525              return Local<v8::Value>());
3526   LOG_API(isolate, "Object::CallAsFunction");
3527   ENTER_V8(isolate);
3528   i::HandleScope scope(isolate);
3529   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3530   i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3531   STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3532   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3533   i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>();
3534   if (obj->IsJSFunction()) {
3535     fun = i::Handle<i::JSFunction>::cast(obj);
3536   } else {
3537     EXCEPTION_PREAMBLE(isolate);
3538     i::Handle<i::Object> delegate =
3539         i::Execution::TryGetFunctionDelegate(obj, &has_pending_exception);
3540     EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3541     fun = i::Handle<i::JSFunction>::cast(delegate);
3542     recv_obj = obj;
3543   }
3544   EXCEPTION_PREAMBLE(isolate);
3545   i::Handle<i::Object> returned =
3546       i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3547   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3548   return Utils::ToLocal(scope.CloseAndEscape(returned));
3549 }
3550
3551
3552 Local<v8::Value> Object::CallAsConstructor(int argc,
3553                                            v8::Handle<v8::Value> argv[]) {
3554   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3555   ON_BAILOUT(isolate, "v8::Object::CallAsConstructor()",
3556              return Local<v8::Object>());
3557   LOG_API(isolate, "Object::CallAsConstructor");
3558   ENTER_V8(isolate);
3559   i::HandleScope scope(isolate);
3560   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3561   STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3562   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3563   if (obj->IsJSFunction()) {
3564     i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(obj);
3565     EXCEPTION_PREAMBLE(isolate);
3566     i::Handle<i::Object> returned =
3567         i::Execution::New(fun, argc, args, &has_pending_exception);
3568     EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3569     return Utils::ToLocal(scope.CloseAndEscape(
3570         i::Handle<i::JSObject>::cast(returned)));
3571   }
3572   EXCEPTION_PREAMBLE(isolate);
3573   i::Handle<i::Object> delegate =
3574       i::Execution::TryGetConstructorDelegate(obj, &has_pending_exception);
3575   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3576   if (!delegate->IsUndefined()) {
3577     i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(delegate);
3578     EXCEPTION_PREAMBLE(isolate);
3579     i::Handle<i::Object> returned =
3580         i::Execution::Call(fun, obj, argc, args, &has_pending_exception);
3581     EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3582     ASSERT(!delegate->IsUndefined());
3583     return Utils::ToLocal(scope.CloseAndEscape(returned));
3584   }
3585   return Local<v8::Object>();
3586 }
3587
3588
3589 Local<v8::Object> Function::NewInstance() const {
3590   return NewInstance(0, NULL);
3591 }
3592
3593
3594 Local<v8::Object> Function::NewInstance(int argc,
3595                                         v8::Handle<v8::Value> argv[]) const {
3596   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3597   ON_BAILOUT(isolate, "v8::Function::NewInstance()",
3598              return Local<v8::Object>());
3599   LOG_API(isolate, "Function::NewInstance");
3600   ENTER_V8(isolate);
3601   HandleScope scope;
3602   i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
3603   STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3604   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3605   EXCEPTION_PREAMBLE(isolate);
3606   i::Handle<i::Object> returned =
3607       i::Execution::New(function, argc, args, &has_pending_exception);
3608   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3609   return scope.Close(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
3610 }
3611
3612
3613 Local<v8::Value> Function::Call(v8::Handle<v8::Object> recv, int argc,
3614                                 v8::Handle<v8::Value> argv[]) {
3615   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3616   ON_BAILOUT(isolate, "v8::Function::Call()", return Local<v8::Value>());
3617   LOG_API(isolate, "Function::Call");
3618   ENTER_V8(isolate);
3619   i::Object* raw_result = NULL;
3620   {
3621     i::HandleScope scope(isolate);
3622     i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
3623     i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3624     STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3625     i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3626     EXCEPTION_PREAMBLE(isolate);
3627     i::Handle<i::Object> returned =
3628         i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3629     EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3630     raw_result = *returned;
3631   }
3632   i::Handle<i::Object> result(raw_result);
3633   return Utils::ToLocal(result);
3634 }
3635
3636
3637 void Function::SetName(v8::Handle<v8::String> name) {
3638   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3639   ENTER_V8(isolate);
3640   USE(isolate);
3641   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3642   func->shared()->set_name(*Utils::OpenHandle(*name));
3643 }
3644
3645
3646 Handle<Value> Function::GetName() const {
3647   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3648   return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name()));
3649 }
3650
3651
3652 ScriptOrigin Function::GetScriptOrigin() const {
3653   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3654   if (func->shared()->script()->IsScript()) {
3655     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
3656     v8::ScriptOrigin origin(
3657       Utils::ToLocal(i::Handle<i::Object>(script->name())),
3658       v8::Integer::New(script->line_offset()->value()),
3659       v8::Integer::New(script->column_offset()->value()));
3660     return origin;
3661   }
3662   return v8::ScriptOrigin(Handle<Value>());
3663 }
3664
3665
3666 const int Function::kLineOffsetNotFound = -1;
3667
3668
3669 int Function::GetScriptLineNumber() const {
3670   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3671   if (func->shared()->script()->IsScript()) {
3672     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
3673     return i::GetScriptLineNumber(script, func->shared()->start_position());
3674   }
3675   return kLineOffsetNotFound;
3676 }
3677
3678
3679 int String::Length() const {
3680   i::Handle<i::String> str = Utils::OpenHandle(this);
3681   if (IsDeadCheck(str->GetIsolate(), "v8::String::Length()")) return 0;
3682   return str->length();
3683 }
3684
3685
3686 int String::Utf8Length() const {
3687   i::Handle<i::String> str = Utils::OpenHandle(this);
3688   if (IsDeadCheck(str->GetIsolate(), "v8::String::Utf8Length()")) return 0;
3689   return str->Utf8Length();
3690 }
3691
3692
3693 uint32_t String::Hash() const {
3694   i::Handle<i::String> str = Utils::OpenHandle(this);
3695   if (IsDeadCheck(str->GetIsolate(), "v8::String::Hash()")) return 0;
3696   return str->Hash();
3697 }
3698
3699
3700 String::CompleteHashData String::CompleteHash() const {
3701   i::Handle<i::String> str = Utils::OpenHandle(this);
3702   if (IsDeadCheck(str->GetIsolate(), "v8::String::CompleteHash()")) return CompleteHashData();
3703   CompleteHashData result;
3704   result.length = str->length();
3705   result.hash = str->Hash();
3706   if (str->IsSeqString())
3707       result.symbol_id = i::SeqString::cast(*str)->symbol_id();
3708   return result;
3709 }
3710
3711
3712 uint32_t String::ComputeHash(uint16_t *string, int length) {
3713   return i::HashSequentialString<i::uc16>(string, length) >> i::String::kHashShift;
3714 }
3715
3716
3717 uint32_t String::ComputeHash(char *string, int length) {
3718   return i::HashSequentialString<char>(string, length) >> i::String::kHashShift;
3719 }
3720
3721
3722 uint16_t String::GetCharacter(int index)
3723 {
3724   i::Handle<i::String> str = Utils::OpenHandle(this);
3725   return str->Get(index);
3726 }
3727
3728
3729 bool String::Equals(uint16_t *string, int length) {
3730   i::Handle<i::String> str = Utils::OpenHandle(this);
3731   if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3732   return str->SlowEqualsExternal(string, length);
3733 }
3734
3735
3736 bool String::Equals(char *string, int length)
3737 {
3738   i::Handle<i::String> str = Utils::OpenHandle(this);
3739   if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3740   return str->SlowEqualsExternal(string, length);
3741 }
3742
3743
3744 int String::WriteUtf8(char* buffer,
3745                       int capacity,
3746                       int* nchars_ref,
3747                       int options) const {
3748   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3749   if (IsDeadCheck(isolate, "v8::String::WriteUtf8()")) return 0;
3750   LOG_API(isolate, "String::WriteUtf8");
3751   ENTER_V8(isolate);
3752   i::Handle<i::String> str = Utils::OpenHandle(this);
3753   if (str->IsAsciiRepresentation()) {
3754     int len;
3755     if (capacity == -1) {
3756       capacity = str->length() + 1;
3757       len = str->length();
3758     } else {
3759       len = i::Min(capacity, str->length());
3760     }
3761     i::String::WriteToFlat(*str, buffer, 0, len);
3762     if (nchars_ref != NULL) *nchars_ref = len;
3763     if (!(options & NO_NULL_TERMINATION) && capacity > len) {
3764       buffer[len] = '\0';
3765       return len + 1;
3766     }
3767     return len;
3768   }
3769
3770   i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3771   isolate->string_tracker()->RecordWrite(str);
3772   if (options & HINT_MANY_WRITES_EXPECTED) {
3773     // Flatten the string for efficiency.  This applies whether we are
3774     // using StringInputBuffer or Get(i) to access the characters.
3775     FlattenString(str);
3776   }
3777   write_input_buffer.Reset(0, *str);
3778   int len = str->length();
3779   // Encode the first K - 3 bytes directly into the buffer since we
3780   // know there's room for them.  If no capacity is given we copy all
3781   // of them here.
3782   int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
3783   int i;
3784   int pos = 0;
3785   int nchars = 0;
3786   for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
3787     i::uc32 c = write_input_buffer.GetNext();
3788     int written = unibrow::Utf8::Encode(buffer + pos, c);
3789     pos += written;
3790     nchars++;
3791   }
3792   if (i < len) {
3793     // For the last characters we need to check the length for each one
3794     // because they may be longer than the remaining space in the
3795     // buffer.
3796     char intermediate[unibrow::Utf8::kMaxEncodedSize];
3797     for (; i < len && pos < capacity; i++) {
3798       i::uc32 c = write_input_buffer.GetNext();
3799       int written = unibrow::Utf8::Encode(intermediate, c);
3800       if (pos + written <= capacity) {
3801         for (int j = 0; j < written; j++)
3802           buffer[pos + j] = intermediate[j];
3803         pos += written;
3804         nchars++;
3805       } else {
3806         // We've reached the end of the buffer
3807         break;
3808       }
3809     }
3810   }
3811   if (nchars_ref != NULL) *nchars_ref = nchars;
3812   if (!(options & NO_NULL_TERMINATION) &&
3813       (i == len && (capacity == -1 || pos < capacity)))
3814     buffer[pos++] = '\0';
3815   return pos;
3816 }
3817
3818
3819 int String::WriteAscii(char* buffer,
3820                        int start,
3821                        int length,
3822                        int options) const {
3823   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3824   if (IsDeadCheck(isolate, "v8::String::WriteAscii()")) return 0;
3825   LOG_API(isolate, "String::WriteAscii");
3826   ENTER_V8(isolate);
3827   i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3828   ASSERT(start >= 0 && length >= -1);
3829   i::Handle<i::String> str = Utils::OpenHandle(this);
3830   isolate->string_tracker()->RecordWrite(str);
3831   if (options & HINT_MANY_WRITES_EXPECTED) {
3832     // Flatten the string for efficiency.  This applies whether we are
3833     // using StringInputBuffer or Get(i) to access the characters.
3834     str->TryFlatten();
3835   }
3836   int end = length;
3837   if ( (length == -1) || (length > str->length() - start) )
3838     end = str->length() - start;
3839   if (end < 0) return 0;
3840   write_input_buffer.Reset(start, *str);
3841   int i;
3842   for (i = 0; i < end; i++) {
3843     char c = static_cast<char>(write_input_buffer.GetNext());
3844     if (c == '\0') c = ' ';
3845     buffer[i] = c;
3846   }
3847   if (!(options & NO_NULL_TERMINATION) && (length == -1 || i < length))
3848     buffer[i] = '\0';
3849   return i;
3850 }
3851
3852
3853 int String::Write(uint16_t* buffer,
3854                   int start,
3855                   int length,
3856                   int options) const {
3857   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3858   if (IsDeadCheck(isolate, "v8::String::Write()")) return 0;
3859   LOG_API(isolate, "String::Write");
3860   ENTER_V8(isolate);
3861   ASSERT(start >= 0 && length >= -1);
3862   i::Handle<i::String> str = Utils::OpenHandle(this);
3863   isolate->string_tracker()->RecordWrite(str);
3864   if (options & HINT_MANY_WRITES_EXPECTED) {
3865     // Flatten the string for efficiency.  This applies whether we are
3866     // using StringInputBuffer or Get(i) to access the characters.
3867     str->TryFlatten();
3868   }
3869   int end = start + length;
3870   if ((length == -1) || (length > str->length() - start) )
3871     end = str->length();
3872   if (end < 0) return 0;
3873   i::String::WriteToFlat(*str, buffer, start, end);
3874   if (!(options & NO_NULL_TERMINATION) &&
3875       (length == -1 || end - start < length)) {
3876     buffer[end - start] = '\0';
3877   }
3878   return end - start;
3879 }
3880
3881
3882 bool v8::String::IsExternal() const {
3883   i::Handle<i::String> str = Utils::OpenHandle(this);
3884   if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternal()")) {
3885     return false;
3886   }
3887   EnsureInitializedForIsolate(str->GetIsolate(), "v8::String::IsExternal()");
3888   return i::StringShape(*str).IsExternalTwoByte();
3889 }
3890
3891
3892 bool v8::String::IsExternalAscii() const {
3893   i::Handle<i::String> str = Utils::OpenHandle(this);
3894   if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternalAscii()")) {
3895     return false;
3896   }
3897   return i::StringShape(*str).IsExternalAscii();
3898 }
3899
3900
3901 void v8::String::VerifyExternalStringResource(
3902     v8::String::ExternalStringResource* value) const {
3903   i::Handle<i::String> str = Utils::OpenHandle(this);
3904   const v8::String::ExternalStringResource* expected;
3905   if (i::StringShape(*str).IsExternalTwoByte()) {
3906     const void* resource =
3907         i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
3908     expected = reinterpret_cast<const ExternalStringResource*>(resource);
3909   } else {
3910     expected = NULL;
3911   }
3912   CHECK_EQ(expected, value);
3913 }
3914
3915
3916 const v8::String::ExternalAsciiStringResource*
3917       v8::String::GetExternalAsciiStringResource() const {
3918   i::Handle<i::String> str = Utils::OpenHandle(this);
3919   if (IsDeadCheck(str->GetIsolate(),
3920                   "v8::String::GetExternalAsciiStringResource()")) {
3921     return NULL;
3922   }
3923   if (i::StringShape(*str).IsExternalAscii()) {
3924     const void* resource =
3925         i::Handle<i::ExternalAsciiString>::cast(str)->resource();
3926     return reinterpret_cast<const ExternalAsciiStringResource*>(resource);
3927   } else {
3928     return NULL;
3929   }
3930 }
3931
3932
3933 double Number::Value() const {
3934   if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Value()")) return 0;
3935   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3936   return obj->Number();
3937 }
3938
3939
3940 bool Boolean::Value() const {
3941   if (IsDeadCheck(i::Isolate::Current(), "v8::Boolean::Value()")) return false;
3942   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3943   return obj->IsTrue();
3944 }
3945
3946
3947 int64_t Integer::Value() const {
3948   if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Value()")) return 0;
3949   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3950   if (obj->IsSmi()) {
3951     return i::Smi::cast(*obj)->value();
3952   } else {
3953     return static_cast<int64_t>(obj->Number());
3954   }
3955 }
3956
3957
3958 int32_t Int32::Value() const {
3959   if (IsDeadCheck(i::Isolate::Current(), "v8::Int32::Value()")) return 0;
3960   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3961   if (obj->IsSmi()) {
3962     return i::Smi::cast(*obj)->value();
3963   } else {
3964     return static_cast<int32_t>(obj->Number());
3965   }
3966 }
3967
3968
3969 uint32_t Uint32::Value() const {
3970   if (IsDeadCheck(i::Isolate::Current(), "v8::Uint32::Value()")) return 0;
3971   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3972   if (obj->IsSmi()) {
3973     return i::Smi::cast(*obj)->value();
3974   } else {
3975     return static_cast<uint32_t>(obj->Number());
3976   }
3977 }
3978
3979
3980 int v8::Object::InternalFieldCount() {
3981   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3982   if (IsDeadCheck(obj->GetIsolate(), "v8::Object::InternalFieldCount()")) {
3983     return 0;
3984   }
3985   return obj->GetInternalFieldCount();
3986 }
3987
3988
3989 Local<Value> v8::Object::CheckedGetInternalField(int index) {
3990   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3991   if (IsDeadCheck(obj->GetIsolate(), "v8::Object::GetInternalField()")) {
3992     return Local<Value>();
3993   }
3994   if (!ApiCheck(index < obj->GetInternalFieldCount(),
3995                 "v8::Object::GetInternalField()",
3996                 "Reading internal field out of bounds")) {
3997     return Local<Value>();
3998   }
3999   i::Handle<i::Object> value(obj->GetInternalField(index));
4000   Local<Value> result = Utils::ToLocal(value);
4001 #ifdef DEBUG
4002   Local<Value> unchecked = UncheckedGetInternalField(index);
4003   ASSERT(unchecked.IsEmpty() || (unchecked == result));
4004 #endif
4005   return result;
4006 }
4007
4008
4009 void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
4010   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4011   i::Isolate* isolate = obj->GetIsolate();
4012   if (IsDeadCheck(isolate, "v8::Object::SetInternalField()")) {
4013     return;
4014   }
4015   if (!ApiCheck(index < obj->GetInternalFieldCount(),
4016                 "v8::Object::SetInternalField()",
4017                 "Writing internal field out of bounds")) {
4018     return;
4019   }
4020   ENTER_V8(isolate);
4021   i::Handle<i::Object> val = Utils::OpenHandle(*value);
4022   obj->SetInternalField(index, *val);
4023 }
4024
4025
4026 static bool CanBeEncodedAsSmi(void* ptr) {
4027   const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4028   return ((address & i::kEncodablePointerMask) == 0);
4029 }
4030
4031
4032 static i::Smi* EncodeAsSmi(void* ptr) {
4033   ASSERT(CanBeEncodedAsSmi(ptr));
4034   const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4035   i::Smi* result = reinterpret_cast<i::Smi*>(address << i::kPointerToSmiShift);
4036   ASSERT(i::Internals::HasSmiTag(result));
4037   ASSERT_EQ(result, i::Smi::FromInt(result->value()));
4038   ASSERT_EQ(ptr, i::Internals::GetExternalPointerFromSmi(result));
4039   return result;
4040 }
4041
4042
4043 void v8::Object::SetPointerInInternalField(int index, void* value) {
4044   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4045   ENTER_V8(isolate);
4046   if (CanBeEncodedAsSmi(value)) {
4047     Utils::OpenHandle(this)->SetInternalField(index, EncodeAsSmi(value));
4048   } else {
4049     HandleScope scope;
4050     i::Handle<i::Foreign> foreign =
4051         isolate->factory()->NewForeign(
4052             reinterpret_cast<i::Address>(value), i::TENURED);
4053     if (!foreign.is_null())
4054         Utils::OpenHandle(this)->SetInternalField(index, *foreign);
4055   }
4056   ASSERT_EQ(value, GetPointerFromInternalField(index));
4057 }
4058
4059
4060 void v8::Object::SetExternalResource(v8::Object::ExternalResource *resource) {
4061   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4062   ENTER_V8(isolate);
4063   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4064   if (CanBeEncodedAsSmi(resource)) {
4065     obj->SetExternalResourceObject(EncodeAsSmi(resource));
4066   } else {
4067     obj->SetExternalResourceObject(*isolate->factory()->NewForeign(static_cast<i::Address>((void *)resource)));
4068   }
4069   if (!obj->IsSymbol()) {
4070     isolate->heap()->external_string_table()->AddObject(*obj);
4071   }
4072 }
4073
4074
4075 v8::Object::ExternalResource *v8::Object::GetExternalResource() {
4076   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4077   i::Object* value = obj->GetExternalResourceObject();
4078   if (value->IsSmi()) {
4079     return reinterpret_cast<v8::Object::ExternalResource*>(i::Internals::GetExternalPointerFromSmi(value));
4080   } else if (value->IsForeign()) {
4081     return reinterpret_cast<v8::Object::ExternalResource*>(i::Foreign::cast(value)->address());
4082   } else {
4083     return NULL;
4084   }
4085 }
4086
4087
4088 // --- E n v i r o n m e n t ---
4089
4090
4091 bool v8::V8::Initialize() {
4092   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4093   if (isolate != NULL && isolate->IsInitialized()) {
4094     return true;
4095   }
4096   return InitializeHelper();
4097 }
4098
4099
4100 void v8::V8::SetEntropySource(EntropySource source) {
4101   i::V8::SetEntropySource(source);
4102 }
4103
4104
4105 bool v8::V8::Dispose() {
4106   i::Isolate* isolate = i::Isolate::Current();
4107   if (!ApiCheck(isolate != NULL && isolate->IsDefaultIsolate(),
4108                 "v8::V8::Dispose()",
4109                 "Use v8::Isolate::Dispose() for a non-default isolate.")) {
4110     return false;
4111   }
4112   i::V8::TearDown();
4113   return true;
4114 }
4115
4116
4117 HeapStatistics::HeapStatistics(): total_heap_size_(0),
4118                                   total_heap_size_executable_(0),
4119                                   used_heap_size_(0),
4120                                   heap_size_limit_(0) { }
4121
4122
4123 void v8::V8::GetHeapStatistics(HeapStatistics* heap_statistics) {
4124   if (!i::Isolate::Current()->IsInitialized()) {
4125     // Isolate is unitialized thus heap is not configured yet.
4126     heap_statistics->set_total_heap_size(0);
4127     heap_statistics->set_total_heap_size_executable(0);
4128     heap_statistics->set_used_heap_size(0);
4129     heap_statistics->set_heap_size_limit(0);
4130     return;
4131   }
4132
4133   i::Heap* heap = i::Isolate::Current()->heap();
4134   heap_statistics->set_total_heap_size(heap->CommittedMemory());
4135   heap_statistics->set_total_heap_size_executable(
4136       heap->CommittedMemoryExecutable());
4137   heap_statistics->set_used_heap_size(heap->SizeOfObjects());
4138   heap_statistics->set_heap_size_limit(heap->MaxReserved());
4139 }
4140
4141
4142 bool v8::V8::IdleNotification() {
4143   // Returning true tells the caller that it need not
4144   // continue to call IdleNotification.
4145   i::Isolate* isolate = i::Isolate::Current();
4146   if (isolate == NULL || !isolate->IsInitialized()) return true;
4147   return i::V8::IdleNotification();
4148 }
4149
4150
4151 void v8::V8::LowMemoryNotification() {
4152   i::Isolate* isolate = i::Isolate::Current();
4153   if (isolate == NULL || !isolate->IsInitialized()) return;
4154   isolate->heap()->CollectAllAvailableGarbage();
4155 }
4156
4157
4158 int v8::V8::ContextDisposedNotification() {
4159   i::Isolate* isolate = i::Isolate::Current();
4160   if (!isolate->IsInitialized()) return 0;
4161   return isolate->heap()->NotifyContextDisposed();
4162 }
4163
4164
4165 const char* v8::V8::GetVersion() {
4166   return i::Version::GetVersion();
4167 }
4168
4169
4170 static i::Handle<i::FunctionTemplateInfo>
4171     EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
4172   if (templ->constructor()->IsUndefined()) {
4173     Local<FunctionTemplate> constructor = FunctionTemplate::New();
4174     Utils::OpenHandle(*constructor)->set_instance_template(*templ);
4175     templ->set_constructor(*Utils::OpenHandle(*constructor));
4176   }
4177   return i::Handle<i::FunctionTemplateInfo>(
4178     i::FunctionTemplateInfo::cast(templ->constructor()));
4179 }
4180
4181
4182 Persistent<Context> v8::Context::New(
4183     v8::ExtensionConfiguration* extensions,
4184     v8::Handle<ObjectTemplate> global_template,
4185     v8::Handle<Value> global_object) {
4186   i::Isolate* isolate = i::Isolate::Current();
4187   EnsureInitializedForIsolate(isolate, "v8::Context::New()");
4188   LOG_API(isolate, "Context::New");
4189   ON_BAILOUT(isolate, "v8::Context::New()", return Persistent<Context>());
4190
4191   // Enter V8 via an ENTER_V8 scope.
4192   i::Handle<i::Context> env;
4193   {
4194     ENTER_V8(isolate);
4195     v8::Handle<ObjectTemplate> proxy_template = global_template;
4196     i::Handle<i::FunctionTemplateInfo> proxy_constructor;
4197     i::Handle<i::FunctionTemplateInfo> global_constructor;
4198
4199     if (!global_template.IsEmpty()) {
4200       // Make sure that the global_template has a constructor.
4201       global_constructor =
4202           EnsureConstructor(Utils::OpenHandle(*global_template));
4203
4204       // Create a fresh template for the global proxy object.
4205       proxy_template = ObjectTemplate::New();
4206       proxy_constructor =
4207           EnsureConstructor(Utils::OpenHandle(*proxy_template));
4208
4209       // Set the global template to be the prototype template of
4210       // global proxy template.
4211       proxy_constructor->set_prototype_template(
4212           *Utils::OpenHandle(*global_template));
4213
4214       // Migrate security handlers from global_template to
4215       // proxy_template.  Temporarily removing access check
4216       // information from the global template.
4217       if (!global_constructor->access_check_info()->IsUndefined()) {
4218         proxy_constructor->set_access_check_info(
4219             global_constructor->access_check_info());
4220         proxy_constructor->set_needs_access_check(
4221             global_constructor->needs_access_check());
4222         global_constructor->set_needs_access_check(false);
4223         global_constructor->set_access_check_info(
4224             isolate->heap()->undefined_value());
4225       }
4226     }
4227
4228     // Create the environment.
4229     env = isolate->bootstrapper()->CreateEnvironment(
4230         isolate,
4231         Utils::OpenHandle(*global_object),
4232         proxy_template,
4233         extensions);
4234
4235     // Restore the access check info on the global template.
4236     if (!global_template.IsEmpty()) {
4237       ASSERT(!global_constructor.is_null());
4238       ASSERT(!proxy_constructor.is_null());
4239       global_constructor->set_access_check_info(
4240           proxy_constructor->access_check_info());
4241       global_constructor->set_needs_access_check(
4242           proxy_constructor->needs_access_check());
4243     }
4244     isolate->runtime_profiler()->Reset();
4245   }
4246   // Leave V8.
4247
4248   if (env.is_null()) {
4249     return Persistent<Context>();
4250   }
4251   return Persistent<Context>(Utils::ToLocal(env));
4252 }
4253
4254
4255 void v8::Context::SetSecurityToken(Handle<Value> token) {
4256   i::Isolate* isolate = i::Isolate::Current();
4257   if (IsDeadCheck(isolate, "v8::Context::SetSecurityToken()")) {
4258     return;
4259   }
4260   ENTER_V8(isolate);
4261   i::Handle<i::Context> env = Utils::OpenHandle(this);
4262   i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
4263   env->set_security_token(*token_handle);
4264 }
4265
4266
4267 void v8::Context::UseDefaultSecurityToken() {
4268   i::Isolate* isolate = i::Isolate::Current();
4269   if (IsDeadCheck(isolate,
4270                   "v8::Context::UseDefaultSecurityToken()")) {
4271     return;
4272   }
4273   ENTER_V8(isolate);
4274   i::Handle<i::Context> env = Utils::OpenHandle(this);
4275   env->set_security_token(env->global());
4276 }
4277
4278
4279 Handle<Value> v8::Context::GetSecurityToken() {
4280   i::Isolate* isolate = i::Isolate::Current();
4281   if (IsDeadCheck(isolate, "v8::Context::GetSecurityToken()")) {
4282     return Handle<Value>();
4283   }
4284   i::Handle<i::Context> env = Utils::OpenHandle(this);
4285   i::Object* security_token = env->security_token();
4286   i::Handle<i::Object> token_handle(security_token);
4287   return Utils::ToLocal(token_handle);
4288 }
4289
4290
4291 bool Context::HasOutOfMemoryException() {
4292   i::Handle<i::Context> env = Utils::OpenHandle(this);
4293   return env->has_out_of_memory();
4294 }
4295
4296
4297 bool Context::InContext() {
4298   return i::Isolate::Current()->context() != NULL;
4299 }
4300
4301
4302 v8::Local<v8::Context> Context::GetEntered() {
4303   i::Isolate* isolate = i::Isolate::Current();
4304   if (!EnsureInitializedForIsolate(isolate, "v8::Context::GetEntered()")) {
4305     return Local<Context>();
4306   }
4307   i::Handle<i::Object> last =
4308       isolate->handle_scope_implementer()->LastEnteredContext();
4309   if (last.is_null()) return Local<Context>();
4310   i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
4311   return Utils::ToLocal(context);
4312 }
4313
4314
4315 v8::Local<v8::Context> Context::GetCurrent() {
4316   i::Isolate* isolate = i::Isolate::Current();
4317   if (IsDeadCheck(isolate, "v8::Context::GetCurrent()")) {
4318     return Local<Context>();
4319   }
4320   i::Handle<i::Object> current = isolate->global_context();
4321   if (current.is_null()) return Local<Context>();
4322   i::Handle<i::Context> context = i::Handle<i::Context>::cast(current);
4323   return Utils::ToLocal(context);
4324 }
4325
4326
4327 v8::Local<v8::Context> Context::GetCalling() {
4328   i::Isolate* isolate = i::Isolate::Current();
4329   if (IsDeadCheck(isolate, "v8::Context::GetCalling()")) {
4330     return Local<Context>();
4331   }
4332   i::Handle<i::Object> calling =
4333       isolate->GetCallingGlobalContext();
4334   if (calling.is_null()) return Local<Context>();
4335   i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
4336   return Utils::ToLocal(context);
4337 }
4338
4339
4340 v8::Local<v8::Object> Context::Global() {
4341   if (IsDeadCheck(i::Isolate::Current(), "v8::Context::Global()")) {
4342     return Local<v8::Object>();
4343   }
4344   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4345   i::Handle<i::Context> context =
4346       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4347   i::Handle<i::Object> global(context->global_proxy());
4348   return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
4349 }
4350
4351
4352 void Context::DetachGlobal() {
4353   i::Isolate* isolate = i::Isolate::Current();
4354   if (IsDeadCheck(isolate, "v8::Context::DetachGlobal()")) return;
4355   ENTER_V8(isolate);
4356   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4357   i::Handle<i::Context> context =
4358       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4359   isolate->bootstrapper()->DetachGlobal(context);
4360 }
4361
4362
4363 void Context::ReattachGlobal(Handle<Object> global_object) {
4364   i::Isolate* isolate = i::Isolate::Current();
4365   if (IsDeadCheck(isolate, "v8::Context::ReattachGlobal()")) return;
4366   ENTER_V8(isolate);
4367   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4368   i::Handle<i::Context> context =
4369       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4370   isolate->bootstrapper()->ReattachGlobal(
4371       context,
4372       Utils::OpenHandle(*global_object));
4373 }
4374
4375
4376 void Context::AllowCodeGenerationFromStrings(bool allow) {
4377   i::Isolate* isolate = i::Isolate::Current();
4378   if (IsDeadCheck(isolate, "v8::Context::AllowCodeGenerationFromStrings()")) {
4379     return;
4380   }
4381   ENTER_V8(isolate);
4382   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4383   i::Handle<i::Context> context =
4384       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4385   context->set_allow_code_gen_from_strings(
4386       allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
4387 }
4388
4389
4390 void V8::SetWrapperClassId(i::Object** global_handle, uint16_t class_id) {
4391   i::GlobalHandles::SetWrapperClassId(global_handle, class_id);
4392 }
4393
4394
4395 Local<v8::Object> ObjectTemplate::NewInstance() {
4396   i::Isolate* isolate = i::Isolate::Current();
4397   ON_BAILOUT(isolate, "v8::ObjectTemplate::NewInstance()",
4398              return Local<v8::Object>());
4399   LOG_API(isolate, "ObjectTemplate::NewInstance");
4400   ENTER_V8(isolate);
4401   EXCEPTION_PREAMBLE(isolate);
4402   i::Handle<i::Object> obj =
4403       i::Execution::InstantiateObject(Utils::OpenHandle(this),
4404                                       &has_pending_exception);
4405   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
4406   return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
4407 }
4408
4409
4410 Local<v8::Function> FunctionTemplate::GetFunction() {
4411   i::Isolate* isolate = i::Isolate::Current();
4412   ON_BAILOUT(isolate, "v8::FunctionTemplate::GetFunction()",
4413              return Local<v8::Function>());
4414   LOG_API(isolate, "FunctionTemplate::GetFunction");
4415   ENTER_V8(isolate);
4416   EXCEPTION_PREAMBLE(isolate);
4417   i::Handle<i::Object> obj =
4418       i::Execution::InstantiateFunction(Utils::OpenHandle(this),
4419                                         &has_pending_exception);
4420   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Function>());
4421   return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
4422 }
4423
4424
4425 bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
4426   ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
4427              return false);
4428   i::Object* obj = *Utils::OpenHandle(*value);
4429   return obj->IsInstanceOf(*Utils::OpenHandle(this));
4430 }
4431
4432
4433 static Local<External> ExternalNewImpl(void* data) {
4434   return Utils::ToLocal(FACTORY->NewForeign(static_cast<i::Address>(data)));
4435 }
4436
4437 static void* ExternalValueImpl(i::Handle<i::Object> obj) {
4438   return reinterpret_cast<void*>(i::Foreign::cast(*obj)->address());
4439 }
4440
4441
4442 Local<Value> v8::External::Wrap(void* data) {
4443   i::Isolate* isolate = i::Isolate::Current();
4444   STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4445   EnsureInitializedForIsolate(isolate, "v8::External::Wrap()");
4446   LOG_API(isolate, "External::Wrap");
4447   ENTER_V8(isolate);
4448
4449   v8::Local<v8::Value> result = CanBeEncodedAsSmi(data)
4450       ? Utils::ToLocal(i::Handle<i::Object>(EncodeAsSmi(data)))
4451       : v8::Local<v8::Value>(ExternalNewImpl(data));
4452
4453   ASSERT_EQ(data, Unwrap(result));
4454   return result;
4455 }
4456
4457
4458 void* v8::Object::SlowGetPointerFromInternalField(int index) {
4459   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4460   i::Object* value = obj->GetInternalField(index);
4461   if (value->IsSmi()) {
4462     return i::Internals::GetExternalPointerFromSmi(value);
4463   } else if (value->IsForeign()) {
4464     return reinterpret_cast<void*>(i::Foreign::cast(value)->address());
4465   } else {
4466     return NULL;
4467   }
4468 }
4469
4470
4471 void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
4472   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Unwrap()")) return 0;
4473   i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
4474   void* result;
4475   if (obj->IsSmi()) {
4476     result = i::Internals::GetExternalPointerFromSmi(*obj);
4477   } else if (obj->IsForeign()) {
4478     result = ExternalValueImpl(obj);
4479   } else {
4480     result = NULL;
4481   }
4482   ASSERT_EQ(result, QuickUnwrap(wrapper));
4483   return result;
4484 }
4485
4486
4487 Local<External> v8::External::New(void* data) {
4488   STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4489   i::Isolate* isolate = i::Isolate::Current();
4490   EnsureInitializedForIsolate(isolate, "v8::External::New()");
4491   LOG_API(isolate, "External::New");
4492   ENTER_V8(isolate);
4493   return ExternalNewImpl(data);
4494 }
4495
4496
4497 void* External::Value() const {
4498   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Value()")) return 0;
4499   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4500   return ExternalValueImpl(obj);
4501 }
4502
4503
4504 Local<String> v8::String::Empty() {
4505   i::Isolate* isolate = i::Isolate::Current();
4506   EnsureInitializedForIsolate(isolate, "v8::String::Empty()");
4507   LOG_API(isolate, "String::Empty()");
4508   return Utils::ToLocal(isolate->factory()->empty_symbol());
4509 }
4510
4511
4512 Local<String> v8::String::New(const char* data, int length) {
4513   i::Isolate* isolate = i::Isolate::Current();
4514   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4515   LOG_API(isolate, "String::New(char)");
4516   if (length == 0) return Empty();
4517   ENTER_V8(isolate);
4518   if (length == -1) length = i::StrLength(data);
4519   i::Handle<i::String> result =
4520       isolate->factory()->NewStringFromUtf8(
4521           i::Vector<const char>(data, length));
4522   return Utils::ToLocal(result);
4523 }
4524
4525
4526 Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
4527   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
4528   i::Isolate* isolate = left_string->GetIsolate();
4529   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4530   LOG_API(isolate, "String::New(char)");
4531   ENTER_V8(isolate);
4532   i::Handle<i::String> right_string = Utils::OpenHandle(*right);
4533   i::Handle<i::String> result = isolate->factory()->NewConsString(left_string,
4534                                                                   right_string);
4535   return Utils::ToLocal(result);
4536 }
4537
4538
4539 Local<String> v8::String::NewUndetectable(const char* data, int length) {
4540   i::Isolate* isolate = i::Isolate::Current();
4541   EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4542   LOG_API(isolate, "String::NewUndetectable(char)");
4543   ENTER_V8(isolate);
4544   if (length == -1) length = i::StrLength(data);
4545   i::Handle<i::String> result =
4546       isolate->factory()->NewStringFromUtf8(
4547           i::Vector<const char>(data, length));
4548   result->MarkAsUndetectable();
4549   return Utils::ToLocal(result);
4550 }
4551
4552
4553 static int TwoByteStringLength(const uint16_t* data) {
4554   int length = 0;
4555   while (data[length] != '\0') length++;
4556   return length;
4557 }
4558
4559
4560 Local<String> v8::String::New(const uint16_t* data, int length) {
4561   i::Isolate* isolate = i::Isolate::Current();
4562   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4563   LOG_API(isolate, "String::New(uint16_)");
4564   if (length == 0) return Empty();
4565   ENTER_V8(isolate);
4566   if (length == -1) length = TwoByteStringLength(data);
4567   i::Handle<i::String> result =
4568       isolate->factory()->NewStringFromTwoByte(
4569           i::Vector<const uint16_t>(data, length));
4570   return Utils::ToLocal(result);
4571 }
4572
4573
4574 Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
4575   i::Isolate* isolate = i::Isolate::Current();
4576   EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4577   LOG_API(isolate, "String::NewUndetectable(uint16_)");
4578   ENTER_V8(isolate);
4579   if (length == -1) length = TwoByteStringLength(data);
4580   i::Handle<i::String> result =
4581       isolate->factory()->NewStringFromTwoByte(
4582           i::Vector<const uint16_t>(data, length));
4583   result->MarkAsUndetectable();
4584   return Utils::ToLocal(result);
4585 }
4586
4587
4588 i::Handle<i::String> NewExternalStringHandle(i::Isolate* isolate,
4589       v8::String::ExternalStringResource* resource) {
4590   i::Handle<i::String> result =
4591       isolate->factory()->NewExternalStringFromTwoByte(resource);
4592   return result;
4593 }
4594
4595
4596 i::Handle<i::String> NewExternalAsciiStringHandle(i::Isolate* isolate,
4597       v8::String::ExternalAsciiStringResource* resource) {
4598   i::Handle<i::String> result =
4599       isolate->factory()->NewExternalStringFromAscii(resource);
4600   return result;
4601 }
4602
4603
4604 Local<String> v8::String::NewExternal(
4605       v8::String::ExternalStringResource* resource) {
4606   i::Isolate* isolate = i::Isolate::Current();
4607   EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4608   LOG_API(isolate, "String::NewExternal");
4609   ENTER_V8(isolate);
4610   i::Handle<i::String> result = NewExternalStringHandle(isolate, resource);
4611   isolate->heap()->external_string_table()->AddString(*result);
4612   return Utils::ToLocal(result);
4613 }
4614
4615
4616 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
4617   i::Handle<i::String> obj = Utils::OpenHandle(this);
4618   i::Isolate* isolate = obj->GetIsolate();
4619   if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4620   if (i::StringShape(*obj).IsExternalTwoByte()) {
4621     return false;  // Already an external string.
4622   }
4623   ENTER_V8(isolate);
4624   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4625     return false;
4626   }
4627   if (isolate->heap()->IsInGCPostProcessing()) {
4628     return false;
4629   }
4630   bool result = obj->MakeExternal(resource);
4631   if (result && !obj->IsSymbol()) {
4632     isolate->heap()->external_string_table()->AddString(*obj);
4633   }
4634   return result;
4635 }
4636
4637
4638 Local<String> v8::String::NewExternal(
4639       v8::String::ExternalAsciiStringResource* resource) {
4640   i::Isolate* isolate = i::Isolate::Current();
4641   EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4642   LOG_API(isolate, "String::NewExternal");
4643   ENTER_V8(isolate);
4644   i::Handle<i::String> result = NewExternalAsciiStringHandle(isolate, resource);
4645   isolate->heap()->external_string_table()->AddString(*result);
4646   return Utils::ToLocal(result);
4647 }
4648
4649
4650 bool v8::String::MakeExternal(
4651     v8::String::ExternalAsciiStringResource* resource) {
4652   i::Handle<i::String> obj = Utils::OpenHandle(this);
4653   i::Isolate* isolate = obj->GetIsolate();
4654   if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4655   if (i::StringShape(*obj).IsExternalTwoByte()) {
4656     return false;  // Already an external string.
4657   }
4658   ENTER_V8(isolate);
4659   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4660     return false;
4661   }
4662   if (isolate->heap()->IsInGCPostProcessing()) {
4663     return false;
4664   }
4665   bool result = obj->MakeExternal(resource);
4666   if (result && !obj->IsSymbol()) {
4667     isolate->heap()->external_string_table()->AddString(*obj);
4668   }
4669   return result;
4670 }
4671
4672
4673 bool v8::String::CanMakeExternal() {
4674   if (!internal::FLAG_clever_optimizations) return false;
4675   i::Handle<i::String> obj = Utils::OpenHandle(this);
4676   i::Isolate* isolate = obj->GetIsolate();
4677   if (IsDeadCheck(isolate, "v8::String::CanMakeExternal()")) return false;
4678   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4679     return false;
4680   }
4681   int size = obj->Size();  // Byte size of the original string.
4682   if (size < i::ExternalString::kSize)
4683     return false;
4684   i::StringShape shape(*obj);
4685   return !shape.IsExternal();
4686 }
4687
4688
4689 Local<v8::Object> v8::Object::New() {
4690   i::Isolate* isolate = i::Isolate::Current();
4691   EnsureInitializedForIsolate(isolate, "v8::Object::New()");
4692   LOG_API(isolate, "Object::New");
4693   ENTER_V8(isolate);
4694   i::Handle<i::JSObject> obj =
4695       isolate->factory()->NewJSObject(isolate->object_function());
4696   return Utils::ToLocal(obj);
4697 }
4698
4699
4700 Local<v8::Value> v8::NumberObject::New(double value) {
4701   i::Isolate* isolate = i::Isolate::Current();
4702   EnsureInitializedForIsolate(isolate, "v8::NumberObject::New()");
4703   LOG_API(isolate, "NumberObject::New");
4704   ENTER_V8(isolate);
4705   i::Handle<i::Object> number = isolate->factory()->NewNumber(value);
4706   i::Handle<i::Object> obj = isolate->factory()->ToObject(number);
4707   return Utils::ToLocal(obj);
4708 }
4709
4710
4711 double v8::NumberObject::NumberValue() const {
4712   i::Isolate* isolate = i::Isolate::Current();
4713   if (IsDeadCheck(isolate, "v8::NumberObject::NumberValue()")) return 0;
4714   LOG_API(isolate, "NumberObject::NumberValue");
4715   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4716   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4717   return jsvalue->value()->Number();
4718 }
4719
4720
4721 Local<v8::Value> v8::BooleanObject::New(bool value) {
4722   i::Isolate* isolate = i::Isolate::Current();
4723   EnsureInitializedForIsolate(isolate, "v8::BooleanObject::New()");
4724   LOG_API(isolate, "BooleanObject::New");
4725   ENTER_V8(isolate);
4726   i::Handle<i::Object> boolean(value ? isolate->heap()->true_value()
4727                                      : isolate->heap()->false_value());
4728   i::Handle<i::Object> obj = isolate->factory()->ToObject(boolean);
4729   return Utils::ToLocal(obj);
4730 }
4731
4732
4733 bool v8::BooleanObject::BooleanValue() const {
4734   i::Isolate* isolate = i::Isolate::Current();
4735   if (IsDeadCheck(isolate, "v8::BooleanObject::BooleanValue()")) return 0;
4736   LOG_API(isolate, "BooleanObject::BooleanValue");
4737   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4738   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4739   return jsvalue->value()->IsTrue();
4740 }
4741
4742
4743 Local<v8::Value> v8::StringObject::New(Handle<String> value) {
4744   i::Isolate* isolate = i::Isolate::Current();
4745   EnsureInitializedForIsolate(isolate, "v8::StringObject::New()");
4746   LOG_API(isolate, "StringObject::New");
4747   ENTER_V8(isolate);
4748   i::Handle<i::Object> obj =
4749       isolate->factory()->ToObject(Utils::OpenHandle(*value));
4750   return Utils::ToLocal(obj);
4751 }
4752
4753
4754 Local<v8::String> v8::StringObject::StringValue() const {
4755   i::Isolate* isolate = i::Isolate::Current();
4756   if (IsDeadCheck(isolate, "v8::StringObject::StringValue()")) {
4757     return Local<v8::String>();
4758   }
4759   LOG_API(isolate, "StringObject::StringValue");
4760   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4761   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4762   return Utils::ToLocal(
4763       i::Handle<i::String>(i::String::cast(jsvalue->value())));
4764 }
4765
4766
4767 Local<v8::Value> v8::Date::New(double time) {
4768   i::Isolate* isolate = i::Isolate::Current();
4769   EnsureInitializedForIsolate(isolate, "v8::Date::New()");
4770   LOG_API(isolate, "Date::New");
4771   if (isnan(time)) {
4772     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4773     time = i::OS::nan_value();
4774   }
4775   ENTER_V8(isolate);
4776   EXCEPTION_PREAMBLE(isolate);
4777   i::Handle<i::Object> obj =
4778       i::Execution::NewDate(time, &has_pending_exception);
4779   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Value>());
4780   return Utils::ToLocal(obj);
4781 }
4782
4783
4784 double v8::Date::NumberValue() const {
4785   i::Isolate* isolate = i::Isolate::Current();
4786   if (IsDeadCheck(isolate, "v8::Date::NumberValue()")) return 0;
4787   LOG_API(isolate, "Date::NumberValue");
4788   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4789   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4790   return jsvalue->value()->Number();
4791 }
4792
4793
4794 void v8::Date::DateTimeConfigurationChangeNotification() {
4795   i::Isolate* isolate = i::Isolate::Current();
4796   ON_BAILOUT(isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
4797              return);
4798   LOG_API(isolate, "Date::DateTimeConfigurationChangeNotification");
4799   ENTER_V8(isolate);
4800
4801   i::HandleScope scope(isolate);
4802   // Get the function ResetDateCache (defined in date-delay.js).
4803   i::Handle<i::String> func_name_str =
4804       isolate->factory()->LookupAsciiSymbol("ResetDateCache");
4805   i::MaybeObject* result =
4806       isolate->js_builtins_object()->GetProperty(*func_name_str);
4807   i::Object* object_func;
4808   if (!result->ToObject(&object_func)) {
4809     return;
4810   }
4811
4812   if (object_func->IsJSFunction()) {
4813     i::Handle<i::JSFunction> func =
4814         i::Handle<i::JSFunction>(i::JSFunction::cast(object_func));
4815
4816     // Call ResetDateCache(0 but expect no exceptions:
4817     bool caught_exception = false;
4818     i::Execution::TryCall(func,
4819                           isolate->js_builtins_object(),
4820                           0,
4821                           NULL,
4822                           &caught_exception);
4823   }
4824 }
4825
4826
4827 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
4828   char flags_buf[3];
4829   int num_flags = 0;
4830   if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
4831   if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
4832   if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
4833   ASSERT(num_flags <= static_cast<int>(ARRAY_SIZE(flags_buf)));
4834   return FACTORY->LookupSymbol(
4835       i::Vector<const char>(flags_buf, num_flags));
4836 }
4837
4838
4839 Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
4840                                   Flags flags) {
4841   i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
4842   EnsureInitializedForIsolate(isolate, "v8::RegExp::New()");
4843   LOG_API(isolate, "RegExp::New");
4844   ENTER_V8(isolate);
4845   EXCEPTION_PREAMBLE(isolate);
4846   i::Handle<i::JSRegExp> obj = i::Execution::NewJSRegExp(
4847       Utils::OpenHandle(*pattern),
4848       RegExpFlagsToString(flags),
4849       &has_pending_exception);
4850   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::RegExp>());
4851   return Utils::ToLocal(i::Handle<i::JSRegExp>::cast(obj));
4852 }
4853
4854
4855 Local<v8::String> v8::RegExp::GetSource() const {
4856   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4857   if (IsDeadCheck(isolate, "v8::RegExp::GetSource()")) {
4858     return Local<v8::String>();
4859   }
4860   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4861   return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
4862 }
4863
4864
4865 // Assert that the static flags cast in GetFlags is valid.
4866 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag)        \
4867   STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) ==     \
4868                 static_cast<int>(i::JSRegExp::internal_flag))
4869 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
4870 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
4871 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
4872 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
4873 #undef REGEXP_FLAG_ASSERT_EQ
4874
4875 v8::RegExp::Flags v8::RegExp::GetFlags() const {
4876   if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::GetFlags()")) {
4877     return v8::RegExp::kNone;
4878   }
4879   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4880   return static_cast<RegExp::Flags>(obj->GetFlags().value());
4881 }
4882
4883
4884 Local<v8::Array> v8::Array::New(int length) {
4885   i::Isolate* isolate = i::Isolate::Current();
4886   EnsureInitializedForIsolate(isolate, "v8::Array::New()");
4887   LOG_API(isolate, "Array::New");
4888   ENTER_V8(isolate);
4889   int real_length = length > 0 ? length : 0;
4890   i::Handle<i::JSArray> obj = isolate->factory()->NewJSArray(real_length);
4891   i::Handle<i::Object> length_obj =
4892       isolate->factory()->NewNumberFromInt(real_length);
4893   obj->set_length(*length_obj);
4894   return Utils::ToLocal(obj);
4895 }
4896
4897
4898 uint32_t v8::Array::Length() const {
4899   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4900   if (IsDeadCheck(isolate, "v8::Array::Length()")) return 0;
4901   i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
4902   i::Object* length = obj->length();
4903   if (length->IsSmi()) {
4904     return i::Smi::cast(length)->value();
4905   } else {
4906     return static_cast<uint32_t>(length->Number());
4907   }
4908 }
4909
4910
4911 Local<Object> Array::CloneElementAt(uint32_t index) {
4912   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4913   ON_BAILOUT(isolate, "v8::Array::CloneElementAt()", return Local<Object>());
4914   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4915   if (!self->HasFastElements()) {
4916     return Local<Object>();
4917   }
4918   i::FixedArray* elms = i::FixedArray::cast(self->elements());
4919   i::Object* paragon = elms->get(index);
4920   if (!paragon->IsJSObject()) {
4921     return Local<Object>();
4922   }
4923   i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
4924   EXCEPTION_PREAMBLE(isolate);
4925   ENTER_V8(isolate);
4926   i::Handle<i::JSObject> result = i::Copy(paragon_handle);
4927   has_pending_exception = result.is_null();
4928   EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
4929   return Utils::ToLocal(result);
4930 }
4931
4932
4933 Local<String> v8::String::NewSymbol(const char* data, int length) {
4934   i::Isolate* isolate = i::Isolate::Current();
4935   EnsureInitializedForIsolate(isolate, "v8::String::NewSymbol()");
4936   LOG_API(isolate, "String::NewSymbol(char)");
4937   ENTER_V8(isolate);
4938   if (length == -1) length = i::StrLength(data);
4939   i::Handle<i::String> result =
4940       isolate->factory()->LookupSymbol(i::Vector<const char>(data, length));
4941   return Utils::ToLocal(result);
4942 }
4943
4944
4945 Local<Number> v8::Number::New(double value) {
4946   i::Isolate* isolate = i::Isolate::Current();
4947   EnsureInitializedForIsolate(isolate, "v8::Number::New()");
4948   if (isnan(value)) {
4949     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4950     value = i::OS::nan_value();
4951   }
4952   ENTER_V8(isolate);
4953   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4954   return Utils::NumberToLocal(result);
4955 }
4956
4957
4958 Local<Integer> v8::Integer::New(int32_t value) {
4959   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4960   EnsureInitializedForIsolate(isolate, "v8::Integer::New()");
4961   if (i::Smi::IsValid(value)) {
4962     return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
4963                                                       isolate));
4964   }
4965   ENTER_V8(isolate);
4966   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4967   return Utils::IntegerToLocal(result);
4968 }
4969
4970
4971 Local<Integer> Integer::NewFromUnsigned(uint32_t value) {
4972   bool fits_into_int32_t = (value & (1 << 31)) == 0;
4973   if (fits_into_int32_t) {
4974     return Integer::New(static_cast<int32_t>(value));
4975   }
4976   i::Isolate* isolate = i::Isolate::Current();
4977   ENTER_V8(isolate);
4978   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4979   return Utils::IntegerToLocal(result);
4980 }
4981
4982
4983 void V8::IgnoreOutOfMemoryException() {
4984   EnterIsolateIfNeeded()->set_ignore_out_of_memory(true);
4985 }
4986
4987
4988 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
4989   i::Isolate* isolate = i::Isolate::Current();
4990   EnsureInitializedForIsolate(isolate, "v8::V8::AddMessageListener()");
4991   ON_BAILOUT(isolate, "v8::V8::AddMessageListener()", return false);
4992   ENTER_V8(isolate);
4993   i::HandleScope scope(isolate);
4994   NeanderArray listeners(isolate->factory()->message_listeners());
4995   NeanderObject obj(2);
4996   obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
4997   obj.set(1, data.IsEmpty() ?
4998              isolate->heap()->undefined_value() :
4999              *Utils::OpenHandle(*data));
5000   listeners.add(obj.value());
5001   return true;
5002 }
5003
5004
5005 void V8::RemoveMessageListeners(MessageCallback that) {
5006   i::Isolate* isolate = i::Isolate::Current();
5007   EnsureInitializedForIsolate(isolate, "v8::V8::RemoveMessageListener()");
5008   ON_BAILOUT(isolate, "v8::V8::RemoveMessageListeners()", return);
5009   ENTER_V8(isolate);
5010   i::HandleScope scope(isolate);
5011   NeanderArray listeners(isolate->factory()->message_listeners());
5012   for (int i = 0; i < listeners.length(); i++) {
5013     if (listeners.get(i)->IsUndefined()) continue;  // skip deleted ones
5014
5015     NeanderObject listener(i::JSObject::cast(listeners.get(i)));
5016     i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
5017     if (callback_obj->address() == FUNCTION_ADDR(that)) {
5018       listeners.set(i, isolate->heap()->undefined_value());
5019     }
5020   }
5021 }
5022
5023
5024 void V8::SetCaptureStackTraceForUncaughtExceptions(
5025       bool capture,
5026       int frame_limit,
5027       StackTrace::StackTraceOptions options) {
5028   i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
5029       capture,
5030       frame_limit,
5031       options);
5032 }
5033
5034
5035 void V8::SetCounterFunction(CounterLookupCallback callback) {
5036   i::Isolate* isolate = EnterIsolateIfNeeded();
5037   if (IsDeadCheck(isolate, "v8::V8::SetCounterFunction()")) return;
5038   isolate->stats_table()->SetCounterFunction(callback);
5039 }
5040
5041 void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
5042   i::Isolate* isolate = EnterIsolateIfNeeded();
5043   if (IsDeadCheck(isolate, "v8::V8::SetCreateHistogramFunction()")) return;
5044   isolate->stats_table()->SetCreateHistogramFunction(callback);
5045 }
5046
5047 void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
5048   i::Isolate* isolate = EnterIsolateIfNeeded();
5049   if (IsDeadCheck(isolate, "v8::V8::SetAddHistogramSampleFunction()")) return;
5050   isolate->stats_table()->
5051       SetAddHistogramSampleFunction(callback);
5052 }
5053
5054 void V8::EnableSlidingStateWindow() {
5055   i::Isolate* isolate = i::Isolate::Current();
5056   if (IsDeadCheck(isolate, "v8::V8::EnableSlidingStateWindow()")) return;
5057   isolate->logger()->EnableSlidingStateWindow();
5058 }
5059
5060
5061 void V8::SetFailedAccessCheckCallbackFunction(
5062       FailedAccessCheckCallback callback) {
5063   i::Isolate* isolate = i::Isolate::Current();
5064   if (IsDeadCheck(isolate, "v8::V8::SetFailedAccessCheckCallbackFunction()")) {
5065     return;
5066   }
5067   isolate->SetFailedAccessCheckCallback(callback);
5068 }
5069
5070 void V8::AddObjectGroup(Persistent<Value>* objects,
5071                         size_t length,
5072                         RetainedObjectInfo* info) {
5073   i::Isolate* isolate = i::Isolate::Current();
5074   if (IsDeadCheck(isolate, "v8::V8::AddObjectGroup()")) return;
5075   STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5076   isolate->global_handles()->AddObjectGroup(
5077       reinterpret_cast<i::Object***>(objects), length, info);
5078 }
5079
5080
5081 void V8::AddImplicitReferences(Persistent<Object> parent,
5082                                Persistent<Value>* children,
5083                                size_t length) {
5084   i::Isolate* isolate = i::Isolate::Current();
5085   if (IsDeadCheck(isolate, "v8::V8::AddImplicitReferences()")) return;
5086   STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5087   isolate->global_handles()->AddImplicitReferences(
5088       i::Handle<i::HeapObject>::cast(Utils::OpenHandle(*parent)).location(),
5089       reinterpret_cast<i::Object***>(children), length);
5090 }
5091
5092
5093 int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
5094   i::Isolate* isolate = i::Isolate::Current();
5095   if (IsDeadCheck(isolate, "v8::V8::AdjustAmountOfExternalAllocatedMemory()")) {
5096     return 0;
5097   }
5098   return isolate->heap()->AdjustAmountOfExternalAllocatedMemory(
5099       change_in_bytes);
5100 }
5101
5102
5103 void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
5104   i::Isolate* isolate = i::Isolate::Current();
5105   if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCPrologueCallback()")) return;
5106   isolate->heap()->SetGlobalGCPrologueCallback(callback);
5107 }
5108
5109
5110 void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
5111   i::Isolate* isolate = i::Isolate::Current();
5112   if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCEpilogueCallback()")) return;
5113   isolate->heap()->SetGlobalGCEpilogueCallback(callback);
5114 }
5115
5116
5117 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5118   i::Isolate* isolate = i::Isolate::Current();
5119   if (IsDeadCheck(isolate, "v8::V8::AddGCPrologueCallback()")) return;
5120   isolate->heap()->AddGCPrologueCallback(callback, gc_type);
5121 }
5122
5123
5124 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5125   i::Isolate* isolate = i::Isolate::Current();
5126   if (IsDeadCheck(isolate, "v8::V8::RemoveGCPrologueCallback()")) return;
5127   isolate->heap()->RemoveGCPrologueCallback(callback);
5128 }
5129
5130
5131 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5132   i::Isolate* isolate = i::Isolate::Current();
5133   if (IsDeadCheck(isolate, "v8::V8::AddGCEpilogueCallback()")) return;
5134   isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
5135 }
5136
5137
5138 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5139   i::Isolate* isolate = i::Isolate::Current();
5140   if (IsDeadCheck(isolate, "v8::V8::RemoveGCEpilogueCallback()")) return;
5141   isolate->heap()->RemoveGCEpilogueCallback(callback);
5142 }
5143
5144
5145 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5146                                      ObjectSpace space,
5147                                      AllocationAction action) {
5148   i::Isolate* isolate = i::Isolate::Current();
5149   if (IsDeadCheck(isolate, "v8::V8::AddMemoryAllocationCallback()")) return;
5150   isolate->memory_allocator()->AddMemoryAllocationCallback(
5151       callback, space, action);
5152 }
5153
5154
5155 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
5156   i::Isolate* isolate = i::Isolate::Current();
5157   if (IsDeadCheck(isolate, "v8::V8::RemoveMemoryAllocationCallback()")) return;
5158   isolate->memory_allocator()->RemoveMemoryAllocationCallback(
5159       callback);
5160 }
5161
5162
5163 void V8::PauseProfiler() {
5164   i::Isolate* isolate = i::Isolate::Current();
5165   isolate->logger()->PauseProfiler();
5166 }
5167
5168
5169 void V8::ResumeProfiler() {
5170   i::Isolate* isolate = i::Isolate::Current();
5171   isolate->logger()->ResumeProfiler();
5172 }
5173
5174
5175 bool V8::IsProfilerPaused() {
5176   i::Isolate* isolate = i::Isolate::Current();
5177   return isolate->logger()->IsProfilerPaused();
5178 }
5179
5180
5181 int V8::GetCurrentThreadId() {
5182   i::Isolate* isolate = i::Isolate::Current();
5183   EnsureInitializedForIsolate(isolate, "V8::GetCurrentThreadId()");
5184   return isolate->thread_id().ToInteger();
5185 }
5186
5187
5188 void V8::TerminateExecution(int thread_id) {
5189   i::Isolate* isolate = i::Isolate::Current();
5190   if (!isolate->IsInitialized()) return;
5191   API_ENTRY_CHECK(isolate, "V8::TerminateExecution()");
5192   // If the thread_id identifies the current thread just terminate
5193   // execution right away.  Otherwise, ask the thread manager to
5194   // terminate the thread with the given id if any.
5195   i::ThreadId internal_tid = i::ThreadId::FromInteger(thread_id);
5196   if (isolate->thread_id().Equals(internal_tid)) {
5197     isolate->stack_guard()->TerminateExecution();
5198   } else {
5199     isolate->thread_manager()->TerminateExecution(internal_tid);
5200   }
5201 }
5202
5203
5204 void V8::TerminateExecution(Isolate* isolate) {
5205   // If no isolate is supplied, use the default isolate.
5206   if (isolate != NULL) {
5207     reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->TerminateExecution();
5208   } else {
5209     i::Isolate::GetDefaultIsolateStackGuard()->TerminateExecution();
5210   }
5211 }
5212
5213
5214 bool V8::IsExecutionTerminating(Isolate* isolate) {
5215   i::Isolate* i_isolate = isolate != NULL ?
5216       reinterpret_cast<i::Isolate*>(isolate) : i::Isolate::Current();
5217   return IsExecutionTerminatingCheck(i_isolate);
5218 }
5219
5220
5221 Isolate* Isolate::GetCurrent() {
5222   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5223   return reinterpret_cast<Isolate*>(isolate);
5224 }
5225
5226
5227 Isolate* Isolate::New() {
5228   i::Isolate* isolate = new i::Isolate();
5229   return reinterpret_cast<Isolate*>(isolate);
5230 }
5231
5232
5233 void Isolate::Dispose() {
5234   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5235   if (!ApiCheck(!isolate->IsInUse(),
5236                 "v8::Isolate::Dispose()",
5237                 "Disposing the isolate that is entered by a thread.")) {
5238     return;
5239   }
5240   isolate->TearDown();
5241 }
5242
5243
5244 void Isolate::Enter() {
5245   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5246   isolate->Enter();
5247 }
5248
5249
5250 void Isolate::Exit() {
5251   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5252   isolate->Exit();
5253 }
5254
5255
5256 void Isolate::SetData(void* data) {
5257   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5258   isolate->SetData(data);
5259 }
5260
5261 void* Isolate::GetData() {
5262   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5263   return isolate->GetData();
5264 }
5265
5266
5267 String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj)
5268     : str_(NULL), length_(0) {
5269   i::Isolate* isolate = i::Isolate::Current();
5270   if (IsDeadCheck(isolate, "v8::String::Utf8Value::Utf8Value()")) return;
5271   if (obj.IsEmpty()) return;
5272   ENTER_V8(isolate);
5273   i::HandleScope scope(isolate);
5274   TryCatch try_catch;
5275   Handle<String> str = obj->ToString();
5276   if (str.IsEmpty()) return;
5277   length_ = str->Utf8Length();
5278   str_ = i::NewArray<char>(length_ + 1);
5279   str->WriteUtf8(str_);
5280 }
5281
5282
5283 String::Utf8Value::~Utf8Value() {
5284   i::DeleteArray(str_);
5285 }
5286
5287
5288 String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj)
5289     : str_(NULL), length_(0) {
5290   i::Isolate* isolate = i::Isolate::Current();
5291   if (IsDeadCheck(isolate, "v8::String::AsciiValue::AsciiValue()")) return;
5292   if (obj.IsEmpty()) return;
5293   ENTER_V8(isolate);
5294   i::HandleScope scope(isolate);
5295   TryCatch try_catch;
5296   Handle<String> str = obj->ToString();
5297   if (str.IsEmpty()) return;
5298   length_ = str->Length();
5299   str_ = i::NewArray<char>(length_ + 1);
5300   str->WriteAscii(str_);
5301 }
5302
5303
5304 String::AsciiValue::~AsciiValue() {
5305   i::DeleteArray(str_);
5306 }
5307
5308
5309 String::Value::Value(v8::Handle<v8::Value> obj)
5310     : str_(NULL), length_(0) {
5311   i::Isolate* isolate = i::Isolate::Current();
5312   if (IsDeadCheck(isolate, "v8::String::Value::Value()")) return;
5313   if (obj.IsEmpty()) return;
5314   ENTER_V8(isolate);
5315   i::HandleScope scope(isolate);
5316   TryCatch try_catch;
5317   Handle<String> str = obj->ToString();
5318   if (str.IsEmpty()) return;
5319   length_ = str->Length();
5320   str_ = i::NewArray<uint16_t>(length_ + 1);
5321   str->Write(str_);
5322 }
5323
5324
5325 String::Value::~Value() {
5326   i::DeleteArray(str_);
5327 }
5328
5329 Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
5330   i::Isolate* isolate = i::Isolate::Current();
5331   LOG_API(isolate, "RangeError");
5332   ON_BAILOUT(isolate, "v8::Exception::RangeError()", return Local<Value>());
5333   ENTER_V8(isolate);
5334   i::Object* error;
5335   {
5336     i::HandleScope scope(isolate);
5337     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5338     i::Handle<i::Object> result = isolate->factory()->NewRangeError(message);
5339     error = *result;
5340   }
5341   i::Handle<i::Object> result(error);
5342   return Utils::ToLocal(result);
5343 }
5344
5345 Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
5346   i::Isolate* isolate = i::Isolate::Current();
5347   LOG_API(isolate, "ReferenceError");
5348   ON_BAILOUT(isolate, "v8::Exception::ReferenceError()", return Local<Value>());
5349   ENTER_V8(isolate);
5350   i::Object* error;
5351   {
5352     i::HandleScope scope(isolate);
5353     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5354     i::Handle<i::Object> result =
5355         isolate->factory()->NewReferenceError(message);
5356     error = *result;
5357   }
5358   i::Handle<i::Object> result(error);
5359   return Utils::ToLocal(result);
5360 }
5361
5362 Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
5363   i::Isolate* isolate = i::Isolate::Current();
5364   LOG_API(isolate, "SyntaxError");
5365   ON_BAILOUT(isolate, "v8::Exception::SyntaxError()", return Local<Value>());
5366   ENTER_V8(isolate);
5367   i::Object* error;
5368   {
5369     i::HandleScope scope(isolate);
5370     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5371     i::Handle<i::Object> result = isolate->factory()->NewSyntaxError(message);
5372     error = *result;
5373   }
5374   i::Handle<i::Object> result(error);
5375   return Utils::ToLocal(result);
5376 }
5377
5378 Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
5379   i::Isolate* isolate = i::Isolate::Current();
5380   LOG_API(isolate, "TypeError");
5381   ON_BAILOUT(isolate, "v8::Exception::TypeError()", return Local<Value>());
5382   ENTER_V8(isolate);
5383   i::Object* error;
5384   {
5385     i::HandleScope scope(isolate);
5386     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5387     i::Handle<i::Object> result = isolate->factory()->NewTypeError(message);
5388     error = *result;
5389   }
5390   i::Handle<i::Object> result(error);
5391   return Utils::ToLocal(result);
5392 }
5393
5394 Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
5395   i::Isolate* isolate = i::Isolate::Current();
5396   LOG_API(isolate, "Error");
5397   ON_BAILOUT(isolate, "v8::Exception::Error()", return Local<Value>());
5398   ENTER_V8(isolate);
5399   i::Object* error;
5400   {
5401     i::HandleScope scope(isolate);
5402     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5403     i::Handle<i::Object> result = isolate->factory()->NewError(message);
5404     error = *result;
5405   }
5406   i::Handle<i::Object> result(error);
5407   return Utils::ToLocal(result);
5408 }
5409
5410
5411 // --- D e b u g   S u p p o r t ---
5412
5413 #ifdef ENABLE_DEBUGGER_SUPPORT
5414
5415 static void EventCallbackWrapper(const v8::Debug::EventDetails& event_details) {
5416   i::Isolate* isolate = i::Isolate::Current();
5417   if (isolate->debug_event_callback() != NULL) {
5418     isolate->debug_event_callback()(event_details.GetEvent(),
5419                                     event_details.GetExecutionState(),
5420                                     event_details.GetEventData(),
5421                                     event_details.GetCallbackData());
5422   }
5423 }
5424
5425
5426 bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
5427   i::Isolate* isolate = i::Isolate::Current();
5428   EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener()");
5429   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5430   ENTER_V8(isolate);
5431
5432   isolate->set_debug_event_callback(that);
5433
5434   i::HandleScope scope(isolate);
5435   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5436   if (that != NULL) {
5437     foreign =
5438         isolate->factory()->NewForeign(FUNCTION_ADDR(EventCallbackWrapper));
5439   }
5440   isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5441   return true;
5442 }
5443
5444
5445 bool Debug::SetDebugEventListener2(EventCallback2 that, Handle<Value> data) {
5446   i::Isolate* isolate = i::Isolate::Current();
5447   EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener2()");
5448   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener2()", return false);
5449   ENTER_V8(isolate);
5450   i::HandleScope scope(isolate);
5451   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5452   if (that != NULL) {
5453     foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
5454   }
5455   isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5456   return true;
5457 }
5458
5459
5460 bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
5461                                   Handle<Value> data) {
5462   i::Isolate* isolate = i::Isolate::Current();
5463   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5464   ENTER_V8(isolate);
5465   isolate->debugger()->SetEventListener(Utils::OpenHandle(*that),
5466                                                       Utils::OpenHandle(*data));
5467   return true;
5468 }
5469
5470
5471 void Debug::DebugBreak(Isolate* isolate) {
5472   // If no isolate is supplied, use the default isolate.
5473   if (isolate != NULL) {
5474     reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->DebugBreak();
5475   } else {
5476     i::Isolate::GetDefaultIsolateStackGuard()->DebugBreak();
5477   }
5478 }
5479
5480
5481 void Debug::CancelDebugBreak(Isolate* isolate) {
5482   // If no isolate is supplied, use the default isolate.
5483   if (isolate != NULL) {
5484     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5485     internal_isolate->stack_guard()->Continue(i::DEBUGBREAK);
5486   } else {
5487     i::Isolate::GetDefaultIsolateStackGuard()->Continue(i::DEBUGBREAK);
5488   }
5489 }
5490
5491
5492 void Debug::DebugBreakForCommand(ClientData* data, Isolate* isolate) {
5493   // If no isolate is supplied, use the default isolate.
5494   if (isolate != NULL) {
5495     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5496     internal_isolate->debugger()->EnqueueDebugCommand(data);
5497   } else {
5498     i::Isolate::GetDefaultIsolateDebugger()->EnqueueDebugCommand(data);
5499   }
5500 }
5501
5502
5503 static void MessageHandlerWrapper(const v8::Debug::Message& message) {
5504   i::Isolate* isolate = i::Isolate::Current();
5505   if (isolate->message_handler()) {
5506     v8::String::Value json(message.GetJSON());
5507     (isolate->message_handler())(*json, json.length(), message.GetClientData());
5508   }
5509 }
5510
5511
5512 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
5513                               bool message_handler_thread) {
5514   i::Isolate* isolate = i::Isolate::Current();
5515   EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5516   ENTER_V8(isolate);
5517
5518   // Message handler thread not supported any more. Parameter temporally left in
5519   // the API for client compatibility reasons.
5520   CHECK(!message_handler_thread);
5521
5522   // TODO(sgjesse) support the old message handler API through a simple wrapper.
5523   isolate->set_message_handler(handler);
5524   if (handler != NULL) {
5525     isolate->debugger()->SetMessageHandler(MessageHandlerWrapper);
5526   } else {
5527     isolate->debugger()->SetMessageHandler(NULL);
5528   }
5529 }
5530
5531
5532 void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
5533   i::Isolate* isolate = i::Isolate::Current();
5534   EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5535   ENTER_V8(isolate);
5536   isolate->debugger()->SetMessageHandler(handler);
5537 }
5538
5539
5540 void Debug::SendCommand(const uint16_t* command, int length,
5541                         ClientData* client_data,
5542                         Isolate* isolate) {
5543   // If no isolate is supplied, use the default isolate.
5544   if (isolate != NULL) {
5545     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5546     internal_isolate->debugger()->ProcessCommand(
5547         i::Vector<const uint16_t>(command, length), client_data);
5548   } else {
5549     i::Isolate::GetDefaultIsolateDebugger()->ProcessCommand(
5550         i::Vector<const uint16_t>(command, length), client_data);
5551   }
5552 }
5553
5554
5555 void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
5556                                    int period) {
5557   i::Isolate* isolate = i::Isolate::Current();
5558   EnsureInitializedForIsolate(isolate, "v8::Debug::SetHostDispatchHandler");
5559   ENTER_V8(isolate);
5560   isolate->debugger()->SetHostDispatchHandler(handler, period);
5561 }
5562
5563
5564 void Debug::SetDebugMessageDispatchHandler(
5565     DebugMessageDispatchHandler handler, bool provide_locker) {
5566   i::Isolate* isolate = i::Isolate::Current();
5567   EnsureInitializedForIsolate(isolate,
5568                               "v8::Debug::SetDebugMessageDispatchHandler");
5569   ENTER_V8(isolate);
5570   isolate->debugger()->SetDebugMessageDispatchHandler(
5571       handler, provide_locker);
5572 }
5573
5574
5575 Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
5576                          v8::Handle<v8::Value> data) {
5577   i::Isolate* isolate = i::Isolate::Current();
5578   if (!isolate->IsInitialized()) return Local<Value>();
5579   ON_BAILOUT(isolate, "v8::Debug::Call()", return Local<Value>());
5580   ENTER_V8(isolate);
5581   i::Handle<i::Object> result;
5582   EXCEPTION_PREAMBLE(isolate);
5583   if (data.IsEmpty()) {
5584     result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5585                                        isolate->factory()->undefined_value(),
5586                                        &has_pending_exception);
5587   } else {
5588     result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5589                                        Utils::OpenHandle(*data),
5590                                        &has_pending_exception);
5591   }
5592   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5593   return Utils::ToLocal(result);
5594 }
5595
5596
5597 Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
5598   i::Isolate* isolate = i::Isolate::Current();
5599   if (!isolate->IsInitialized()) return Local<Value>();
5600   ON_BAILOUT(isolate, "v8::Debug::GetMirror()", return Local<Value>());
5601   ENTER_V8(isolate);
5602   v8::HandleScope scope;
5603   i::Debug* isolate_debug = isolate->debug();
5604   isolate_debug->Load();
5605   i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global());
5606   i::Handle<i::String> name =
5607       isolate->factory()->LookupAsciiSymbol("MakeMirror");
5608   i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
5609   i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
5610   v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
5611   const int kArgc = 1;
5612   v8::Handle<v8::Value> argv[kArgc] = { obj };
5613   EXCEPTION_PREAMBLE(isolate);
5614   v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
5615                                               kArgc,
5616                                               argv);
5617   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5618   return scope.Close(result);
5619 }
5620
5621
5622 bool Debug::EnableAgent(const char* name, int port, bool wait_for_connection) {
5623   return i::Isolate::Current()->debugger()->StartAgent(name, port,
5624                                                        wait_for_connection);
5625 }
5626
5627
5628 void Debug::DisableAgent() {
5629   return i::Isolate::Current()->debugger()->StopAgent();
5630 }
5631
5632
5633 void Debug::ProcessDebugMessages() {
5634   i::Execution::ProcessDebugMesssages(true);
5635 }
5636
5637 Local<Context> Debug::GetDebugContext() {
5638   i::Isolate* isolate = i::Isolate::Current();
5639   EnsureInitializedForIsolate(isolate, "v8::Debug::GetDebugContext()");
5640   ENTER_V8(isolate);
5641   return Utils::ToLocal(i::Isolate::Current()->debugger()->GetDebugContext());
5642 }
5643
5644 #endif  // ENABLE_DEBUGGER_SUPPORT
5645
5646
5647 Handle<String> CpuProfileNode::GetFunctionName() const {
5648   i::Isolate* isolate = i::Isolate::Current();
5649   IsDeadCheck(isolate, "v8::CpuProfileNode::GetFunctionName");
5650   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5651   const i::CodeEntry* entry = node->entry();
5652   if (!entry->has_name_prefix()) {
5653     return Handle<String>(ToApi<String>(
5654         isolate->factory()->LookupAsciiSymbol(entry->name())));
5655   } else {
5656     return Handle<String>(ToApi<String>(isolate->factory()->NewConsString(
5657         isolate->factory()->LookupAsciiSymbol(entry->name_prefix()),
5658         isolate->factory()->LookupAsciiSymbol(entry->name()))));
5659   }
5660 }
5661
5662
5663 Handle<String> CpuProfileNode::GetScriptResourceName() const {
5664   i::Isolate* isolate = i::Isolate::Current();
5665   IsDeadCheck(isolate, "v8::CpuProfileNode::GetScriptResourceName");
5666   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5667   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5668       node->entry()->resource_name())));
5669 }
5670
5671
5672 int CpuProfileNode::GetLineNumber() const {
5673   i::Isolate* isolate = i::Isolate::Current();
5674   IsDeadCheck(isolate, "v8::CpuProfileNode::GetLineNumber");
5675   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
5676 }
5677
5678
5679 double CpuProfileNode::GetTotalTime() const {
5680   i::Isolate* isolate = i::Isolate::Current();
5681   IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalTime");
5682   return reinterpret_cast<const i::ProfileNode*>(this)->GetTotalMillis();
5683 }
5684
5685
5686 double CpuProfileNode::GetSelfTime() const {
5687   i::Isolate* isolate = i::Isolate::Current();
5688   IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfTime");
5689   return reinterpret_cast<const i::ProfileNode*>(this)->GetSelfMillis();
5690 }
5691
5692
5693 double CpuProfileNode::GetTotalSamplesCount() const {
5694   i::Isolate* isolate = i::Isolate::Current();
5695   IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalSamplesCount");
5696   return reinterpret_cast<const i::ProfileNode*>(this)->total_ticks();
5697 }
5698
5699
5700 double CpuProfileNode::GetSelfSamplesCount() const {
5701   i::Isolate* isolate = i::Isolate::Current();
5702   IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfSamplesCount");
5703   return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
5704 }
5705
5706
5707 unsigned CpuProfileNode::GetCallUid() const {
5708   i::Isolate* isolate = i::Isolate::Current();
5709   IsDeadCheck(isolate, "v8::CpuProfileNode::GetCallUid");
5710   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->GetCallUid();
5711 }
5712
5713
5714 int CpuProfileNode::GetChildrenCount() const {
5715   i::Isolate* isolate = i::Isolate::Current();
5716   IsDeadCheck(isolate, "v8::CpuProfileNode::GetChildrenCount");
5717   return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
5718 }
5719
5720
5721 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
5722   i::Isolate* isolate = i::Isolate::Current();
5723   IsDeadCheck(isolate, "v8::CpuProfileNode::GetChild");
5724   const i::ProfileNode* child =
5725       reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
5726   return reinterpret_cast<const CpuProfileNode*>(child);
5727 }
5728
5729
5730 void CpuProfile::Delete() {
5731   i::Isolate* isolate = i::Isolate::Current();
5732   IsDeadCheck(isolate, "v8::CpuProfile::Delete");
5733   i::CpuProfiler::DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
5734   if (i::CpuProfiler::GetProfilesCount() == 0 &&
5735       !i::CpuProfiler::HasDetachedProfiles()) {
5736     // If this was the last profile, clean up all accessory data as well.
5737     i::CpuProfiler::DeleteAllProfiles();
5738   }
5739 }
5740
5741
5742 unsigned CpuProfile::GetUid() const {
5743   i::Isolate* isolate = i::Isolate::Current();
5744   IsDeadCheck(isolate, "v8::CpuProfile::GetUid");
5745   return reinterpret_cast<const i::CpuProfile*>(this)->uid();
5746 }
5747
5748
5749 Handle<String> CpuProfile::GetTitle() const {
5750   i::Isolate* isolate = i::Isolate::Current();
5751   IsDeadCheck(isolate, "v8::CpuProfile::GetTitle");
5752   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5753   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5754       profile->title())));
5755 }
5756
5757
5758 const CpuProfileNode* CpuProfile::GetBottomUpRoot() const {
5759   i::Isolate* isolate = i::Isolate::Current();
5760   IsDeadCheck(isolate, "v8::CpuProfile::GetBottomUpRoot");
5761   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5762   return reinterpret_cast<const CpuProfileNode*>(profile->bottom_up()->root());
5763 }
5764
5765
5766 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
5767   i::Isolate* isolate = i::Isolate::Current();
5768   IsDeadCheck(isolate, "v8::CpuProfile::GetTopDownRoot");
5769   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5770   return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
5771 }
5772
5773
5774 int CpuProfiler::GetProfilesCount() {
5775   i::Isolate* isolate = i::Isolate::Current();
5776   IsDeadCheck(isolate, "v8::CpuProfiler::GetProfilesCount");
5777   return i::CpuProfiler::GetProfilesCount();
5778 }
5779
5780
5781 const CpuProfile* CpuProfiler::GetProfile(int index,
5782                                           Handle<Value> security_token) {
5783   i::Isolate* isolate = i::Isolate::Current();
5784   IsDeadCheck(isolate, "v8::CpuProfiler::GetProfile");
5785   return reinterpret_cast<const CpuProfile*>(
5786       i::CpuProfiler::GetProfile(
5787           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5788           index));
5789 }
5790
5791
5792 const CpuProfile* CpuProfiler::FindProfile(unsigned uid,
5793                                            Handle<Value> security_token) {
5794   i::Isolate* isolate = i::Isolate::Current();
5795   IsDeadCheck(isolate, "v8::CpuProfiler::FindProfile");
5796   return reinterpret_cast<const CpuProfile*>(
5797       i::CpuProfiler::FindProfile(
5798           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5799           uid));
5800 }
5801
5802
5803 void CpuProfiler::StartProfiling(Handle<String> title) {
5804   i::Isolate* isolate = i::Isolate::Current();
5805   IsDeadCheck(isolate, "v8::CpuProfiler::StartProfiling");
5806   i::CpuProfiler::StartProfiling(*Utils::OpenHandle(*title));
5807 }
5808
5809
5810 const CpuProfile* CpuProfiler::StopProfiling(Handle<String> title,
5811                                              Handle<Value> security_token) {
5812   i::Isolate* isolate = i::Isolate::Current();
5813   IsDeadCheck(isolate, "v8::CpuProfiler::StopProfiling");
5814   return reinterpret_cast<const CpuProfile*>(
5815       i::CpuProfiler::StopProfiling(
5816           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5817           *Utils::OpenHandle(*title)));
5818 }
5819
5820
5821 void CpuProfiler::DeleteAllProfiles() {
5822   i::Isolate* isolate = i::Isolate::Current();
5823   IsDeadCheck(isolate, "v8::CpuProfiler::DeleteAllProfiles");
5824   i::CpuProfiler::DeleteAllProfiles();
5825 }
5826
5827
5828 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
5829   return const_cast<i::HeapGraphEdge*>(
5830       reinterpret_cast<const i::HeapGraphEdge*>(edge));
5831 }
5832
5833
5834 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
5835   i::Isolate* isolate = i::Isolate::Current();
5836   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetType");
5837   return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
5838 }
5839
5840
5841 Handle<Value> HeapGraphEdge::GetName() const {
5842   i::Isolate* isolate = i::Isolate::Current();
5843   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetName");
5844   i::HeapGraphEdge* edge = ToInternal(this);
5845   switch (edge->type()) {
5846     case i::HeapGraphEdge::kContextVariable:
5847     case i::HeapGraphEdge::kInternal:
5848     case i::HeapGraphEdge::kProperty:
5849     case i::HeapGraphEdge::kShortcut:
5850       return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5851           edge->name())));
5852     case i::HeapGraphEdge::kElement:
5853     case i::HeapGraphEdge::kHidden:
5854       return Handle<Number>(ToApi<Number>(isolate->factory()->NewNumberFromInt(
5855           edge->index())));
5856     default: UNREACHABLE();
5857   }
5858   return v8::Undefined();
5859 }
5860
5861
5862 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
5863   i::Isolate* isolate = i::Isolate::Current();
5864   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetFromNode");
5865   const i::HeapEntry* from = ToInternal(this)->From();
5866   return reinterpret_cast<const HeapGraphNode*>(from);
5867 }
5868
5869
5870 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
5871   i::Isolate* isolate = i::Isolate::Current();
5872   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetToNode");
5873   const i::HeapEntry* to = ToInternal(this)->to();
5874   return reinterpret_cast<const HeapGraphNode*>(to);
5875 }
5876
5877
5878 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
5879   return const_cast<i::HeapEntry*>(
5880       reinterpret_cast<const i::HeapEntry*>(entry));
5881 }
5882
5883
5884 HeapGraphNode::Type HeapGraphNode::GetType() const {
5885   i::Isolate* isolate = i::Isolate::Current();
5886   IsDeadCheck(isolate, "v8::HeapGraphNode::GetType");
5887   return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
5888 }
5889
5890
5891 Handle<String> HeapGraphNode::GetName() const {
5892   i::Isolate* isolate = i::Isolate::Current();
5893   IsDeadCheck(isolate, "v8::HeapGraphNode::GetName");
5894   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5895       ToInternal(this)->name())));
5896 }
5897
5898
5899 uint64_t HeapGraphNode::GetId() const {
5900   i::Isolate* isolate = i::Isolate::Current();
5901   IsDeadCheck(isolate, "v8::HeapGraphNode::GetId");
5902   return ToInternal(this)->id();
5903 }
5904
5905
5906 int HeapGraphNode::GetSelfSize() const {
5907   i::Isolate* isolate = i::Isolate::Current();
5908   IsDeadCheck(isolate, "v8::HeapGraphNode::GetSelfSize");
5909   return ToInternal(this)->self_size();
5910 }
5911
5912
5913 int HeapGraphNode::GetRetainedSize(bool exact) const {
5914   i::Isolate* isolate = i::Isolate::Current();
5915   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainedSize");
5916   return ToInternal(this)->RetainedSize(exact);
5917 }
5918
5919
5920 int HeapGraphNode::GetChildrenCount() const {
5921   i::Isolate* isolate = i::Isolate::Current();
5922   IsDeadCheck(isolate, "v8::HeapSnapshot::GetChildrenCount");
5923   return ToInternal(this)->children().length();
5924 }
5925
5926
5927 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
5928   i::Isolate* isolate = i::Isolate::Current();
5929   IsDeadCheck(isolate, "v8::HeapSnapshot::GetChild");
5930   return reinterpret_cast<const HeapGraphEdge*>(
5931       &ToInternal(this)->children()[index]);
5932 }
5933
5934
5935 int HeapGraphNode::GetRetainersCount() const {
5936   i::Isolate* isolate = i::Isolate::Current();
5937   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainersCount");
5938   return ToInternal(this)->retainers().length();
5939 }
5940
5941
5942 const HeapGraphEdge* HeapGraphNode::GetRetainer(int index) const {
5943   i::Isolate* isolate = i::Isolate::Current();
5944   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainer");
5945   return reinterpret_cast<const HeapGraphEdge*>(
5946       ToInternal(this)->retainers()[index]);
5947 }
5948
5949
5950 const HeapGraphNode* HeapGraphNode::GetDominatorNode() const {
5951   i::Isolate* isolate = i::Isolate::Current();
5952   IsDeadCheck(isolate, "v8::HeapSnapshot::GetDominatorNode");
5953   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->dominator());
5954 }
5955
5956
5957 v8::Handle<v8::Value> HeapGraphNode::GetHeapValue() const {
5958   i::Isolate* isolate = i::Isolate::Current();
5959   IsDeadCheck(isolate, "v8::HeapGraphNode::GetHeapValue");
5960   i::Handle<i::HeapObject> object = ToInternal(this)->GetHeapObject();
5961   return v8::Handle<Value>(!object.is_null() ?
5962                            ToApi<Value>(object) : ToApi<Value>(
5963                                isolate->factory()->undefined_value()));
5964 }
5965
5966
5967 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
5968   return const_cast<i::HeapSnapshot*>(
5969       reinterpret_cast<const i::HeapSnapshot*>(snapshot));
5970 }
5971
5972
5973 void HeapSnapshot::Delete() {
5974   i::Isolate* isolate = i::Isolate::Current();
5975   IsDeadCheck(isolate, "v8::HeapSnapshot::Delete");
5976   if (i::HeapProfiler::GetSnapshotsCount() > 1) {
5977     ToInternal(this)->Delete();
5978   } else {
5979     // If this is the last snapshot, clean up all accessory data as well.
5980     i::HeapProfiler::DeleteAllSnapshots();
5981   }
5982 }
5983
5984
5985 HeapSnapshot::Type HeapSnapshot::GetType() const {
5986   i::Isolate* isolate = i::Isolate::Current();
5987   IsDeadCheck(isolate, "v8::HeapSnapshot::GetType");
5988   return static_cast<HeapSnapshot::Type>(ToInternal(this)->type());
5989 }
5990
5991
5992 unsigned HeapSnapshot::GetUid() const {
5993   i::Isolate* isolate = i::Isolate::Current();
5994   IsDeadCheck(isolate, "v8::HeapSnapshot::GetUid");
5995   return ToInternal(this)->uid();
5996 }
5997
5998
5999 Handle<String> HeapSnapshot::GetTitle() const {
6000   i::Isolate* isolate = i::Isolate::Current();
6001   IsDeadCheck(isolate, "v8::HeapSnapshot::GetTitle");
6002   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
6003       ToInternal(this)->title())));
6004 }
6005
6006
6007 const HeapGraphNode* HeapSnapshot::GetRoot() const {
6008   i::Isolate* isolate = i::Isolate::Current();
6009   IsDeadCheck(isolate, "v8::HeapSnapshot::GetHead");
6010   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
6011 }
6012
6013
6014 const HeapGraphNode* HeapSnapshot::GetNodeById(uint64_t id) const {
6015   i::Isolate* isolate = i::Isolate::Current();
6016   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodeById");
6017   return reinterpret_cast<const HeapGraphNode*>(
6018       ToInternal(this)->GetEntryById(id));
6019 }
6020
6021
6022 int HeapSnapshot::GetNodesCount() const {
6023   i::Isolate* isolate = i::Isolate::Current();
6024   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodesCount");
6025   return ToInternal(this)->entries()->length();
6026 }
6027
6028
6029 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
6030   i::Isolate* isolate = i::Isolate::Current();
6031   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNode");
6032   return reinterpret_cast<const HeapGraphNode*>(
6033       ToInternal(this)->entries()->at(index));
6034 }
6035
6036
6037 void HeapSnapshot::Serialize(OutputStream* stream,
6038                              HeapSnapshot::SerializationFormat format) const {
6039   i::Isolate* isolate = i::Isolate::Current();
6040   IsDeadCheck(isolate, "v8::HeapSnapshot::Serialize");
6041   ApiCheck(format == kJSON,
6042            "v8::HeapSnapshot::Serialize",
6043            "Unknown serialization format");
6044   ApiCheck(stream->GetOutputEncoding() == OutputStream::kAscii,
6045            "v8::HeapSnapshot::Serialize",
6046            "Unsupported output encoding");
6047   ApiCheck(stream->GetChunkSize() > 0,
6048            "v8::HeapSnapshot::Serialize",
6049            "Invalid stream chunk size");
6050   i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
6051   serializer.Serialize(stream);
6052 }
6053
6054
6055 int HeapProfiler::GetSnapshotsCount() {
6056   i::Isolate* isolate = i::Isolate::Current();
6057   IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshotsCount");
6058   return i::HeapProfiler::GetSnapshotsCount();
6059 }
6060
6061
6062 const HeapSnapshot* HeapProfiler::GetSnapshot(int index) {
6063   i::Isolate* isolate = i::Isolate::Current();
6064   IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshot");
6065   return reinterpret_cast<const HeapSnapshot*>(
6066       i::HeapProfiler::GetSnapshot(index));
6067 }
6068
6069
6070 const HeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {
6071   i::Isolate* isolate = i::Isolate::Current();
6072   IsDeadCheck(isolate, "v8::HeapProfiler::FindSnapshot");
6073   return reinterpret_cast<const HeapSnapshot*>(
6074       i::HeapProfiler::FindSnapshot(uid));
6075 }
6076
6077
6078 const HeapSnapshot* HeapProfiler::TakeSnapshot(Handle<String> title,
6079                                                HeapSnapshot::Type type,
6080                                                ActivityControl* control) {
6081   i::Isolate* isolate = i::Isolate::Current();
6082   IsDeadCheck(isolate, "v8::HeapProfiler::TakeSnapshot");
6083   i::HeapSnapshot::Type internal_type = i::HeapSnapshot::kFull;
6084   switch (type) {
6085     case HeapSnapshot::kFull:
6086       internal_type = i::HeapSnapshot::kFull;
6087       break;
6088     default:
6089       UNREACHABLE();
6090   }
6091   return reinterpret_cast<const HeapSnapshot*>(
6092       i::HeapProfiler::TakeSnapshot(
6093           *Utils::OpenHandle(*title), internal_type, control));
6094 }
6095
6096
6097 void HeapProfiler::DeleteAllSnapshots() {
6098   i::Isolate* isolate = i::Isolate::Current();
6099   IsDeadCheck(isolate, "v8::HeapProfiler::DeleteAllSnapshots");
6100   i::HeapProfiler::DeleteAllSnapshots();
6101 }
6102
6103
6104 void HeapProfiler::DefineWrapperClass(uint16_t class_id,
6105                                       WrapperInfoCallback callback) {
6106   i::Isolate::Current()->heap_profiler()->DefineWrapperClass(class_id,
6107                                                              callback);
6108 }
6109
6110
6111
6112 v8::Testing::StressType internal::Testing::stress_type_ =
6113     v8::Testing::kStressTypeOpt;
6114
6115
6116 void Testing::SetStressRunType(Testing::StressType type) {
6117   internal::Testing::set_stress_type(type);
6118 }
6119
6120 int Testing::GetStressRuns() {
6121   if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
6122 #ifdef DEBUG
6123   // In debug mode the code runs much slower so stressing will only make two
6124   // runs.
6125   return 2;
6126 #else
6127   return 5;
6128 #endif
6129 }
6130
6131
6132 static void SetFlagsFromString(const char* flags) {
6133   V8::SetFlagsFromString(flags, i::StrLength(flags));
6134 }
6135
6136
6137 void Testing::PrepareStressRun(int run) {
6138   static const char* kLazyOptimizations =
6139       "--prepare-always-opt --nolimit-inlining "
6140       "--noalways-opt --noopt-eagerly";
6141   static const char* kEagerOptimizations = "--opt-eagerly";
6142   static const char* kForcedOptimizations = "--always-opt";
6143
6144   // If deoptimization stressed turn on frequent deoptimization. If no value
6145   // is spefified through --deopt-every-n-times use a default default value.
6146   static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
6147   if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
6148       internal::FLAG_deopt_every_n_times == 0) {
6149     SetFlagsFromString(kDeoptEvery13Times);
6150   }
6151
6152 #ifdef DEBUG
6153   // As stressing in debug mode only make two runs skip the deopt stressing
6154   // here.
6155   if (run == GetStressRuns() - 1) {
6156     SetFlagsFromString(kForcedOptimizations);
6157   } else {
6158     SetFlagsFromString(kEagerOptimizations);
6159     SetFlagsFromString(kLazyOptimizations);
6160   }
6161 #else
6162   if (run == GetStressRuns() - 1) {
6163     SetFlagsFromString(kForcedOptimizations);
6164   } else if (run == GetStressRuns() - 2) {
6165     SetFlagsFromString(kEagerOptimizations);
6166   } else {
6167     SetFlagsFromString(kLazyOptimizations);
6168   }
6169 #endif
6170 }
6171
6172
6173 void Testing::DeoptimizeAll() {
6174   internal::Deoptimizer::DeoptimizeAll();
6175 }
6176
6177
6178 namespace internal {
6179
6180
6181 void HandleScopeImplementer::FreeThreadResources() {
6182   Free();
6183 }
6184
6185
6186 char* HandleScopeImplementer::ArchiveThread(char* storage) {
6187   v8::ImplementationUtilities::HandleScopeData* current =
6188       isolate_->handle_scope_data();
6189   handle_scope_data_ = *current;
6190   memcpy(storage, this, sizeof(*this));
6191
6192   ResetAfterArchive();
6193   current->Initialize();
6194
6195   return storage + ArchiveSpacePerThread();
6196 }
6197
6198
6199 int HandleScopeImplementer::ArchiveSpacePerThread() {
6200   return sizeof(HandleScopeImplementer);
6201 }
6202
6203
6204 char* HandleScopeImplementer::RestoreThread(char* storage) {
6205   memcpy(this, storage, sizeof(*this));
6206   *isolate_->handle_scope_data() = handle_scope_data_;
6207   return storage + ArchiveSpacePerThread();
6208 }
6209
6210
6211 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
6212   // Iterate over all handles in the blocks except for the last.
6213   for (int i = blocks()->length() - 2; i >= 0; --i) {
6214     Object** block = blocks()->at(i);
6215     v->VisitPointers(block, &block[kHandleBlockSize]);
6216   }
6217
6218   // Iterate over live handles in the last block (if any).
6219   if (!blocks()->is_empty()) {
6220     v->VisitPointers(blocks()->last(), handle_scope_data_.next);
6221   }
6222
6223   if (!saved_contexts_.is_empty()) {
6224     Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
6225     v->VisitPointers(start, start + saved_contexts_.length());
6226   }
6227 }
6228
6229
6230 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
6231   v8::ImplementationUtilities::HandleScopeData* current =
6232       isolate_->handle_scope_data();
6233   handle_scope_data_ = *current;
6234   IterateThis(v);
6235 }
6236
6237
6238 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
6239   HandleScopeImplementer* scope_implementer =
6240       reinterpret_cast<HandleScopeImplementer*>(storage);
6241   scope_implementer->IterateThis(v);
6242   return storage + ArchiveSpacePerThread();
6243 }
6244
6245 } }  // namespace v8::internal