[V8] QtScript/V8: Add new v8 api to check if a value is an error.
[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 void ObjectTemplate::MarkAsUseUserObjectComparison()
1468 {
1469   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1470   if (IsDeadCheck(isolate, "v8::ObjectTemplate::MarkAsUseUserObjectComparison()")) {
1471     return;
1472   }
1473   ENTER_V8(isolate);
1474   EnsureConstructor(this);
1475   Utils::OpenHandle(this)->set_use_user_object_comparison(i::Smi::FromInt(1));
1476 }
1477
1478 // --- S c r i p t D a t a ---
1479
1480
1481 ScriptData* ScriptData::PreCompile(const char* input, int length) {
1482   i::Utf8ToUC16CharacterStream stream(
1483       reinterpret_cast<const unsigned char*>(input), length);
1484   return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1485 }
1486
1487
1488 ScriptData* ScriptData::PreCompile(v8::Handle<String> source) {
1489   i::Handle<i::String> str = Utils::OpenHandle(*source);
1490   if (str->IsExternalTwoByteString()) {
1491     i::ExternalTwoByteStringUC16CharacterStream stream(
1492       i::Handle<i::ExternalTwoByteString>::cast(str), 0, str->length());
1493     return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1494   } else {
1495     i::GenericStringUC16CharacterStream stream(str, 0, str->length());
1496     return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1497   }
1498 }
1499
1500
1501 ScriptData* ScriptData::New(const char* data, int length) {
1502   // Return an empty ScriptData if the length is obviously invalid.
1503   if (length % sizeof(unsigned) != 0) {
1504     return new i::ScriptDataImpl();
1505   }
1506
1507   // Copy the data to ensure it is properly aligned.
1508   int deserialized_data_length = length / sizeof(unsigned);
1509   // If aligned, don't create a copy of the data.
1510   if (reinterpret_cast<intptr_t>(data) % sizeof(unsigned) == 0) {
1511     return new i::ScriptDataImpl(data, length);
1512   }
1513   // Copy the data to align it.
1514   unsigned* deserialized_data = i::NewArray<unsigned>(deserialized_data_length);
1515   i::OS::MemCopy(deserialized_data, data, length);
1516
1517   return new i::ScriptDataImpl(
1518       i::Vector<unsigned>(deserialized_data, deserialized_data_length));
1519 }
1520
1521
1522 // --- S c r i p t ---
1523
1524
1525 Local<Script> Script::New(v8::Handle<String> source,
1526                           v8::ScriptOrigin* origin,
1527                           v8::ScriptData* pre_data,
1528                           v8::Handle<String> script_data,
1529                           v8::Script::CompileFlags compile_flags) {
1530   i::Isolate* isolate = i::Isolate::Current();
1531   ON_BAILOUT(isolate, "v8::Script::New()", return Local<Script>());
1532   LOG_API(isolate, "Script::New");
1533   ENTER_V8(isolate);
1534   i::Handle<i::String> str = Utils::OpenHandle(*source);
1535   i::Handle<i::Object> name_obj;
1536   int line_offset = 0;
1537   int column_offset = 0;
1538   if (origin != NULL) {
1539     if (!origin->ResourceName().IsEmpty()) {
1540       name_obj = Utils::OpenHandle(*origin->ResourceName());
1541     }
1542     if (!origin->ResourceLineOffset().IsEmpty()) {
1543       line_offset = static_cast<int>(origin->ResourceLineOffset()->Value());
1544     }
1545     if (!origin->ResourceColumnOffset().IsEmpty()) {
1546       column_offset = static_cast<int>(origin->ResourceColumnOffset()->Value());
1547     }
1548   }
1549   EXCEPTION_PREAMBLE(isolate);
1550   i::ScriptDataImpl* pre_data_impl = static_cast<i::ScriptDataImpl*>(pre_data);
1551   // We assert that the pre-data is sane, even though we can actually
1552   // handle it if it turns out not to be in release mode.
1553   ASSERT(pre_data_impl == NULL || pre_data_impl->SanityCheck());
1554   // If the pre-data isn't sane we simply ignore it
1555   if (pre_data_impl != NULL && !pre_data_impl->SanityCheck()) {
1556     pre_data_impl = NULL;
1557   }
1558   i::Handle<i::SharedFunctionInfo> result =
1559       i::Compiler::Compile(str,
1560                            name_obj,
1561                            line_offset,
1562                            column_offset,
1563                            NULL,
1564                            pre_data_impl,
1565                            Utils::OpenHandle(*script_data),
1566                            i::NOT_NATIVES_CODE,
1567                            compile_flags);
1568   has_pending_exception = result.is_null();
1569   EXCEPTION_BAILOUT_CHECK(isolate, Local<Script>());
1570   return Local<Script>(ToApi<Script>(result));
1571 }
1572
1573
1574 Local<Script> Script::New(v8::Handle<String> source,
1575                           v8::Handle<Value> file_name,
1576                           v8::Script::CompileFlags compile_flags) {
1577   ScriptOrigin origin(file_name);
1578   return New(source, &origin, 0, Handle<String>(), compile_flags);
1579 }
1580
1581
1582 Local<Script> Script::Compile(v8::Handle<String> source,
1583                               v8::ScriptOrigin* origin,
1584                               v8::ScriptData* pre_data,
1585                               v8::Handle<String> script_data,
1586                               v8::Script::CompileFlags compile_flags) {
1587   i::Isolate* isolate = i::Isolate::Current();
1588   ON_BAILOUT(isolate, "v8::Script::Compile()", return Local<Script>());
1589   LOG_API(isolate, "Script::Compile");
1590   ENTER_V8(isolate);
1591   Local<Script> generic = New(source, origin, pre_data, script_data, compile_flags);
1592   if (generic.IsEmpty())
1593     return generic;
1594   i::Handle<i::Object> obj = Utils::OpenHandle(*generic);
1595   i::Handle<i::SharedFunctionInfo> function =
1596       i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1597   i::Handle<i::JSFunction> result =
1598       isolate->factory()->NewFunctionFromSharedFunctionInfo(
1599           function,
1600           isolate->global_context());
1601   return Local<Script>(ToApi<Script>(result));
1602 }
1603
1604
1605 Local<Script> Script::Compile(v8::Handle<String> source,
1606                               v8::Handle<Value> file_name,
1607                               v8::Handle<String> script_data,
1608                               v8::Script::CompileFlags compile_flags) {
1609   ScriptOrigin origin(file_name);
1610   return Compile(source, &origin, 0, script_data, compile_flags);
1611 }
1612
1613
1614 Local<Value> Script::Run() {
1615     return Run(Handle<Object>());
1616 }
1617
1618 Local<Value> Script::Run(Handle<Object> qml) {
1619   i::Isolate* isolate = i::Isolate::Current();
1620   ON_BAILOUT(isolate, "v8::Script::Run()", return Local<Value>());
1621   LOG_API(isolate, "Script::Run");
1622   ENTER_V8(isolate);
1623   i::Object* raw_result = NULL;
1624   {
1625     i::HandleScope scope(isolate);
1626     i::Handle<i::Object> obj = Utils::OpenHandle(this);
1627     i::Handle<i::JSFunction> fun;
1628     if (obj->IsSharedFunctionInfo()) {
1629       i::Handle<i::SharedFunctionInfo>
1630           function_info(i::SharedFunctionInfo::cast(*obj), isolate);
1631       fun = isolate->factory()->NewFunctionFromSharedFunctionInfo(
1632           function_info, isolate->global_context());
1633     } else {
1634       fun = i::Handle<i::JSFunction>(i::JSFunction::cast(*obj), isolate);
1635     }
1636     EXCEPTION_PREAMBLE(isolate);
1637     i::Handle<i::Object> qmlglobal = Utils::OpenHandle(*qml);
1638     i::Handle<i::Object> receiver(
1639         isolate->context()->global_proxy(), isolate);
1640     i::Handle<i::Object> result =
1641         i::Execution::Call(fun, receiver, 0, NULL, &has_pending_exception, false, qmlglobal);
1642     EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
1643     raw_result = *result;
1644   }
1645   i::Handle<i::Object> result(raw_result, isolate);
1646   return Utils::ToLocal(result);
1647 }
1648
1649
1650 static i::Handle<i::SharedFunctionInfo> OpenScript(Script* script) {
1651   i::Handle<i::Object> obj = Utils::OpenHandle(script);
1652   i::Handle<i::SharedFunctionInfo> result;
1653   if (obj->IsSharedFunctionInfo()) {
1654     result =
1655         i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1656   } else {
1657     result =
1658         i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared());
1659   }
1660   return result;
1661 }
1662
1663
1664 Local<Value> Script::Id() {
1665   i::Isolate* isolate = i::Isolate::Current();
1666   ON_BAILOUT(isolate, "v8::Script::Id()", return Local<Value>());
1667   LOG_API(isolate, "Script::Id");
1668   i::Object* raw_id = NULL;
1669   {
1670     i::HandleScope scope(isolate);
1671     i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1672     i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1673     i::Handle<i::Object> id(script->id());
1674     raw_id = *id;
1675   }
1676   i::Handle<i::Object> id(raw_id);
1677   return Utils::ToLocal(id);
1678 }
1679
1680
1681 void Script::SetData(v8::Handle<String> data) {
1682   i::Isolate* isolate = i::Isolate::Current();
1683   ON_BAILOUT(isolate, "v8::Script::SetData()", return);
1684   LOG_API(isolate, "Script::SetData");
1685   {
1686     i::HandleScope scope(isolate);
1687     i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1688     i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
1689     i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1690     script->set_data(*raw_data);
1691   }
1692 }
1693
1694
1695 // --- E x c e p t i o n s ---
1696
1697
1698 v8::TryCatch::TryCatch()
1699     : isolate_(i::Isolate::Current()),
1700       next_(isolate_->try_catch_handler_address()),
1701       exception_(isolate_->heap()->the_hole_value()),
1702       message_(i::Smi::FromInt(0)),
1703       is_verbose_(false),
1704       can_continue_(true),
1705       capture_message_(true),
1706       rethrow_(false) {
1707   isolate_->RegisterTryCatchHandler(this);
1708 }
1709
1710
1711 v8::TryCatch::~TryCatch() {
1712   ASSERT(isolate_ == i::Isolate::Current());
1713   if (rethrow_) {
1714     v8::HandleScope scope;
1715     v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(Exception());
1716     isolate_->UnregisterTryCatchHandler(this);
1717     v8::ThrowException(exc);
1718   } else {
1719     isolate_->UnregisterTryCatchHandler(this);
1720   }
1721 }
1722
1723
1724 bool v8::TryCatch::HasCaught() const {
1725   return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
1726 }
1727
1728
1729 bool v8::TryCatch::CanContinue() const {
1730   return can_continue_;
1731 }
1732
1733
1734 v8::Handle<v8::Value> v8::TryCatch::ReThrow() {
1735   if (!HasCaught()) return v8::Local<v8::Value>();
1736   rethrow_ = true;
1737   return v8::Undefined();
1738 }
1739
1740
1741 v8::Local<Value> v8::TryCatch::Exception() const {
1742   ASSERT(isolate_ == i::Isolate::Current());
1743   if (HasCaught()) {
1744     // Check for out of memory exception.
1745     i::Object* exception = reinterpret_cast<i::Object*>(exception_);
1746     return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
1747   } else {
1748     return v8::Local<Value>();
1749   }
1750 }
1751
1752
1753 v8::Local<Value> v8::TryCatch::StackTrace() const {
1754   ASSERT(isolate_ == i::Isolate::Current());
1755   if (HasCaught()) {
1756     i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
1757     if (!raw_obj->IsJSObject()) return v8::Local<Value>();
1758     i::HandleScope scope(isolate_);
1759     i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
1760     i::Handle<i::String> name = isolate_->factory()->LookupAsciiSymbol("stack");
1761     if (!obj->HasProperty(*name)) return v8::Local<Value>();
1762     i::Handle<i::Object> value = i::GetProperty(obj, name);
1763     if (value.is_null()) return v8::Local<Value>();
1764     return v8::Utils::ToLocal(scope.CloseAndEscape(value));
1765   } else {
1766     return v8::Local<Value>();
1767   }
1768 }
1769
1770
1771 v8::Local<v8::Message> v8::TryCatch::Message() const {
1772   ASSERT(isolate_ == i::Isolate::Current());
1773   if (HasCaught() && message_ != i::Smi::FromInt(0)) {
1774     i::Object* message = reinterpret_cast<i::Object*>(message_);
1775     return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
1776   } else {
1777     return v8::Local<v8::Message>();
1778   }
1779 }
1780
1781
1782 void v8::TryCatch::Reset() {
1783   ASSERT(isolate_ == i::Isolate::Current());
1784   exception_ = isolate_->heap()->the_hole_value();
1785   message_ = i::Smi::FromInt(0);
1786 }
1787
1788
1789 void v8::TryCatch::SetVerbose(bool value) {
1790   is_verbose_ = value;
1791 }
1792
1793
1794 void v8::TryCatch::SetCaptureMessage(bool value) {
1795   capture_message_ = value;
1796 }
1797
1798
1799 // --- M e s s a g e ---
1800
1801
1802 Local<String> Message::Get() const {
1803   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1804   ON_BAILOUT(isolate, "v8::Message::Get()", return Local<String>());
1805   ENTER_V8(isolate);
1806   HandleScope scope;
1807   i::Handle<i::Object> obj = Utils::OpenHandle(this);
1808   i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(obj);
1809   Local<String> result = Utils::ToLocal(raw_result);
1810   return scope.Close(result);
1811 }
1812
1813
1814 v8::Handle<Value> Message::GetScriptResourceName() const {
1815   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1816   if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceName()")) {
1817     return Local<String>();
1818   }
1819   ENTER_V8(isolate);
1820   HandleScope scope;
1821   i::Handle<i::JSMessageObject> message =
1822       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1823   // Return this.script.name.
1824   i::Handle<i::JSValue> script =
1825       i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1826   i::Handle<i::Object> resource_name(i::Script::cast(script->value())->name());
1827   return scope.Close(Utils::ToLocal(resource_name));
1828 }
1829
1830
1831 v8::Handle<Value> Message::GetScriptData() const {
1832   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1833   if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceData()")) {
1834     return Local<Value>();
1835   }
1836   ENTER_V8(isolate);
1837   HandleScope scope;
1838   i::Handle<i::JSMessageObject> message =
1839       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1840   // Return this.script.data.
1841   i::Handle<i::JSValue> script =
1842       i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1843   i::Handle<i::Object> data(i::Script::cast(script->value())->data());
1844   return scope.Close(Utils::ToLocal(data));
1845 }
1846
1847
1848 v8::Handle<v8::StackTrace> Message::GetStackTrace() const {
1849   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1850   if (IsDeadCheck(isolate, "v8::Message::GetStackTrace()")) {
1851     return Local<v8::StackTrace>();
1852   }
1853   ENTER_V8(isolate);
1854   HandleScope scope;
1855   i::Handle<i::JSMessageObject> message =
1856       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1857   i::Handle<i::Object> stackFramesObj(message->stack_frames());
1858   if (!stackFramesObj->IsJSArray()) return v8::Handle<v8::StackTrace>();
1859   i::Handle<i::JSArray> stackTrace =
1860       i::Handle<i::JSArray>::cast(stackFramesObj);
1861   return scope.Close(Utils::StackTraceToLocal(stackTrace));
1862 }
1863
1864
1865 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1866                                                i::Handle<i::Object> recv,
1867                                                int argc,
1868                                                i::Handle<i::Object> argv[],
1869                                                bool* has_pending_exception) {
1870   i::Isolate* isolate = i::Isolate::Current();
1871   i::Handle<i::String> fmt_str = isolate->factory()->LookupAsciiSymbol(name);
1872   i::Object* object_fun =
1873       isolate->js_builtins_object()->GetPropertyNoExceptionThrown(*fmt_str);
1874   i::Handle<i::JSFunction> fun =
1875       i::Handle<i::JSFunction>(i::JSFunction::cast(object_fun));
1876   i::Handle<i::Object> value =
1877       i::Execution::Call(fun, recv, argc, argv, has_pending_exception);
1878   return value;
1879 }
1880
1881
1882 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1883                                                i::Handle<i::Object> data,
1884                                                bool* has_pending_exception) {
1885   i::Handle<i::Object> argv[] = { data };
1886   return CallV8HeapFunction(name,
1887                             i::Isolate::Current()->js_builtins_object(),
1888                             ARRAY_SIZE(argv),
1889                             argv,
1890                             has_pending_exception);
1891 }
1892
1893
1894 int Message::GetLineNumber() const {
1895   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1896   ON_BAILOUT(isolate, "v8::Message::GetLineNumber()", return kNoLineNumberInfo);
1897   ENTER_V8(isolate);
1898   i::HandleScope scope(isolate);
1899
1900   EXCEPTION_PREAMBLE(isolate);
1901   i::Handle<i::Object> result = CallV8HeapFunction("GetLineNumber",
1902                                                    Utils::OpenHandle(this),
1903                                                    &has_pending_exception);
1904   EXCEPTION_BAILOUT_CHECK(isolate, 0);
1905   return static_cast<int>(result->Number());
1906 }
1907
1908
1909 int Message::GetStartPosition() const {
1910   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1911   if (IsDeadCheck(isolate, "v8::Message::GetStartPosition()")) return 0;
1912   ENTER_V8(isolate);
1913   i::HandleScope scope(isolate);
1914   i::Handle<i::JSMessageObject> message =
1915       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1916   return message->start_position();
1917 }
1918
1919
1920 int Message::GetEndPosition() const {
1921   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1922   if (IsDeadCheck(isolate, "v8::Message::GetEndPosition()")) return 0;
1923   ENTER_V8(isolate);
1924   i::HandleScope scope(isolate);
1925   i::Handle<i::JSMessageObject> message =
1926       i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1927   return message->end_position();
1928 }
1929
1930
1931 int Message::GetStartColumn() const {
1932   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1933   if (IsDeadCheck(isolate, "v8::Message::GetStartColumn()")) {
1934     return kNoColumnInfo;
1935   }
1936   ENTER_V8(isolate);
1937   i::HandleScope scope(isolate);
1938   i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1939   EXCEPTION_PREAMBLE(isolate);
1940   i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1941       "GetPositionInLine",
1942       data_obj,
1943       &has_pending_exception);
1944   EXCEPTION_BAILOUT_CHECK(isolate, 0);
1945   return static_cast<int>(start_col_obj->Number());
1946 }
1947
1948
1949 int Message::GetEndColumn() const {
1950   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1951   if (IsDeadCheck(isolate, "v8::Message::GetEndColumn()")) return kNoColumnInfo;
1952   ENTER_V8(isolate);
1953   i::HandleScope scope(isolate);
1954   i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1955   EXCEPTION_PREAMBLE(isolate);
1956   i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1957       "GetPositionInLine",
1958       data_obj,
1959       &has_pending_exception);
1960   EXCEPTION_BAILOUT_CHECK(isolate, 0);
1961   i::Handle<i::JSMessageObject> message =
1962       i::Handle<i::JSMessageObject>::cast(data_obj);
1963   int start = message->start_position();
1964   int end = message->end_position();
1965   return static_cast<int>(start_col_obj->Number()) + (end - start);
1966 }
1967
1968
1969 Local<String> Message::GetSourceLine() const {
1970   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1971   ON_BAILOUT(isolate, "v8::Message::GetSourceLine()", return Local<String>());
1972   ENTER_V8(isolate);
1973   HandleScope scope;
1974   EXCEPTION_PREAMBLE(isolate);
1975   i::Handle<i::Object> result = CallV8HeapFunction("GetSourceLine",
1976                                                    Utils::OpenHandle(this),
1977                                                    &has_pending_exception);
1978   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::String>());
1979   if (result->IsString()) {
1980     return scope.Close(Utils::ToLocal(i::Handle<i::String>::cast(result)));
1981   } else {
1982     return Local<String>();
1983   }
1984 }
1985
1986
1987 void Message::PrintCurrentStackTrace(FILE* out) {
1988   i::Isolate* isolate = i::Isolate::Current();
1989   if (IsDeadCheck(isolate, "v8::Message::PrintCurrentStackTrace()")) return;
1990   ENTER_V8(isolate);
1991   isolate->PrintCurrentStackTrace(out);
1992 }
1993
1994
1995 // --- S t a c k T r a c e ---
1996
1997 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
1998   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1999   if (IsDeadCheck(isolate, "v8::StackTrace::GetFrame()")) {
2000     return Local<StackFrame>();
2001   }
2002   ENTER_V8(isolate);
2003   HandleScope scope;
2004   i::Handle<i::JSArray> self = Utils::OpenHandle(this);
2005   i::Object* raw_object = self->GetElementNoExceptionThrown(index);
2006   i::Handle<i::JSObject> obj(i::JSObject::cast(raw_object));
2007   return scope.Close(Utils::StackFrameToLocal(obj));
2008 }
2009
2010
2011 int StackTrace::GetFrameCount() const {
2012   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2013   if (IsDeadCheck(isolate, "v8::StackTrace::GetFrameCount()")) return -1;
2014   ENTER_V8(isolate);
2015   return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2016 }
2017
2018
2019 Local<Array> StackTrace::AsArray() {
2020   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2021   if (IsDeadCheck(isolate, "v8::StackTrace::AsArray()")) Local<Array>();
2022   ENTER_V8(isolate);
2023   return Utils::ToLocal(Utils::OpenHandle(this));
2024 }
2025
2026
2027 Local<StackTrace> StackTrace::CurrentStackTrace(int frame_limit,
2028     StackTraceOptions options) {
2029   i::Isolate* isolate = i::Isolate::Current();
2030   if (IsDeadCheck(isolate, "v8::StackTrace::CurrentStackTrace()")) {
2031     Local<StackTrace>();
2032   }
2033   ENTER_V8(isolate);
2034   i::Handle<i::JSArray> stackTrace =
2035       isolate->CaptureCurrentStackTrace(frame_limit, options);
2036   return Utils::StackTraceToLocal(stackTrace);
2037 }
2038
2039
2040 // --- S t a c k F r a m e ---
2041
2042 int StackFrame::GetLineNumber() const {
2043   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2044   if (IsDeadCheck(isolate, "v8::StackFrame::GetLineNumber()")) {
2045     return Message::kNoLineNumberInfo;
2046   }
2047   ENTER_V8(isolate);
2048   i::HandleScope scope(isolate);
2049   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2050   i::Handle<i::Object> line = GetProperty(self, "lineNumber");
2051   if (!line->IsSmi()) {
2052     return Message::kNoLineNumberInfo;
2053   }
2054   return i::Smi::cast(*line)->value();
2055 }
2056
2057
2058 int StackFrame::GetColumn() const {
2059   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2060   if (IsDeadCheck(isolate, "v8::StackFrame::GetColumn()")) {
2061     return Message::kNoColumnInfo;
2062   }
2063   ENTER_V8(isolate);
2064   i::HandleScope scope(isolate);
2065   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2066   i::Handle<i::Object> column = GetProperty(self, "column");
2067   if (!column->IsSmi()) {
2068     return Message::kNoColumnInfo;
2069   }
2070   return i::Smi::cast(*column)->value();
2071 }
2072
2073
2074 Local<String> StackFrame::GetScriptName() const {
2075   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2076   if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptName()")) {
2077     return Local<String>();
2078   }
2079   ENTER_V8(isolate);
2080   HandleScope scope;
2081   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2082   i::Handle<i::Object> name = GetProperty(self, "scriptName");
2083   if (!name->IsString()) {
2084     return Local<String>();
2085   }
2086   return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2087 }
2088
2089
2090 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2091   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2092   if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptNameOrSourceURL()")) {
2093     return Local<String>();
2094   }
2095   ENTER_V8(isolate);
2096   HandleScope scope;
2097   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2098   i::Handle<i::Object> name = GetProperty(self, "scriptNameOrSourceURL");
2099   if (!name->IsString()) {
2100     return Local<String>();
2101   }
2102   return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2103 }
2104
2105
2106 Local<String> StackFrame::GetFunctionName() const {
2107   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2108   if (IsDeadCheck(isolate, "v8::StackFrame::GetFunctionName()")) {
2109     return Local<String>();
2110   }
2111   ENTER_V8(isolate);
2112   HandleScope scope;
2113   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2114   i::Handle<i::Object> name = GetProperty(self, "functionName");
2115   if (!name->IsString()) {
2116     return Local<String>();
2117   }
2118   return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2119 }
2120
2121
2122 bool StackFrame::IsEval() const {
2123   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2124   if (IsDeadCheck(isolate, "v8::StackFrame::IsEval()")) return false;
2125   ENTER_V8(isolate);
2126   i::HandleScope scope(isolate);
2127   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2128   i::Handle<i::Object> is_eval = GetProperty(self, "isEval");
2129   return is_eval->IsTrue();
2130 }
2131
2132
2133 bool StackFrame::IsConstructor() const {
2134   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2135   if (IsDeadCheck(isolate, "v8::StackFrame::IsConstructor()")) return false;
2136   ENTER_V8(isolate);
2137   i::HandleScope scope(isolate);
2138   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2139   i::Handle<i::Object> is_constructor = GetProperty(self, "isConstructor");
2140   return is_constructor->IsTrue();
2141 }
2142
2143
2144 // --- D a t a ---
2145
2146 bool Value::IsUndefined() const {
2147   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUndefined()")) {
2148     return false;
2149   }
2150   return Utils::OpenHandle(this)->IsUndefined();
2151 }
2152
2153
2154 bool Value::IsNull() const {
2155   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNull()")) return false;
2156   return Utils::OpenHandle(this)->IsNull();
2157 }
2158
2159
2160 bool Value::IsTrue() const {
2161   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsTrue()")) return false;
2162   return Utils::OpenHandle(this)->IsTrue();
2163 }
2164
2165
2166 bool Value::IsFalse() const {
2167   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFalse()")) return false;
2168   return Utils::OpenHandle(this)->IsFalse();
2169 }
2170
2171
2172 bool Value::IsFunction() const {
2173   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFunction()")) {
2174     return false;
2175   }
2176   return Utils::OpenHandle(this)->IsJSFunction();
2177 }
2178
2179
2180 bool Value::FullIsString() const {
2181   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsString()")) return false;
2182   bool result = Utils::OpenHandle(this)->IsString();
2183   ASSERT_EQ(result, QuickIsString());
2184   return result;
2185 }
2186
2187
2188 bool Value::IsArray() const {
2189   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsArray()")) return false;
2190   return Utils::OpenHandle(this)->IsJSArray();
2191 }
2192
2193
2194 bool Value::IsObject() const {
2195   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsObject()")) return false;
2196   return Utils::OpenHandle(this)->IsJSObject();
2197 }
2198
2199
2200 bool Value::IsNumber() const {
2201   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNumber()")) return false;
2202   return Utils::OpenHandle(this)->IsNumber();
2203 }
2204
2205
2206 bool Value::IsBoolean() const {
2207   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsBoolean()")) {
2208     return false;
2209   }
2210   return Utils::OpenHandle(this)->IsBoolean();
2211 }
2212
2213
2214 bool Value::IsExternal() const {
2215   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsExternal()")) {
2216     return false;
2217   }
2218   return Utils::OpenHandle(this)->IsForeign();
2219 }
2220
2221
2222 bool Value::IsInt32() const {
2223   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsInt32()")) return false;
2224   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2225   if (obj->IsSmi()) return true;
2226   if (obj->IsNumber()) {
2227     double value = obj->Number();
2228     return i::FastI2D(i::FastD2I(value)) == value;
2229   }
2230   return false;
2231 }
2232
2233
2234 bool Value::IsUint32() const {
2235   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUint32()")) return false;
2236   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2237   if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2238   if (obj->IsNumber()) {
2239     double value = obj->Number();
2240     return i::FastUI2D(i::FastD2UI(value)) == value;
2241   }
2242   return false;
2243 }
2244
2245
2246 bool Value::IsDate() const {
2247   i::Isolate* isolate = i::Isolate::Current();
2248   if (IsDeadCheck(isolate, "v8::Value::IsDate()")) return false;
2249   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2250   return obj->HasSpecificClassOf(isolate->heap()->Date_symbol());
2251 }
2252
2253
2254 bool Value::IsStringObject() const {
2255   i::Isolate* isolate = i::Isolate::Current();
2256   if (IsDeadCheck(isolate, "v8::Value::IsStringObject()")) return false;
2257   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2258   return obj->HasSpecificClassOf(isolate->heap()->String_symbol());
2259 }
2260
2261
2262 bool Value::IsNumberObject() const {
2263   i::Isolate* isolate = i::Isolate::Current();
2264   if (IsDeadCheck(isolate, "v8::Value::IsNumberObject()")) return false;
2265   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2266   return obj->HasSpecificClassOf(isolate->heap()->Number_symbol());
2267 }
2268
2269
2270 static i::Object* LookupBuiltin(i::Isolate* isolate,
2271                                 const char* builtin_name) {
2272   i::Handle<i::String> symbol =
2273       isolate->factory()->LookupAsciiSymbol(builtin_name);
2274   i::Handle<i::JSBuiltinsObject> builtins = isolate->js_builtins_object();
2275   return builtins->GetPropertyNoExceptionThrown(*symbol);
2276 }
2277
2278
2279 static bool CheckConstructor(i::Isolate* isolate,
2280                              i::Handle<i::JSObject> obj,
2281                              const char* class_name) {
2282   return obj->map()->constructor() == LookupBuiltin(isolate, class_name);
2283 }
2284
2285
2286 bool Value::IsNativeError() const {
2287   i::Isolate* isolate = i::Isolate::Current();
2288   if (IsDeadCheck(isolate, "v8::Value::IsNativeError()")) return false;
2289   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2290   if (obj->IsJSObject()) {
2291     i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
2292     return CheckConstructor(isolate, js_obj, "$Error") ||
2293         CheckConstructor(isolate, js_obj, "$EvalError") ||
2294         CheckConstructor(isolate, js_obj, "$RangeError") ||
2295         CheckConstructor(isolate, js_obj, "$ReferenceError") ||
2296         CheckConstructor(isolate, js_obj, "$SyntaxError") ||
2297         CheckConstructor(isolate, js_obj, "$TypeError") ||
2298         CheckConstructor(isolate, js_obj, "$URIError");
2299   } else {
2300     return false;
2301   }
2302 }
2303
2304
2305 bool Value::IsBooleanObject() const {
2306   i::Isolate* isolate = i::Isolate::Current();
2307   if (IsDeadCheck(isolate, "v8::Value::IsBooleanObject()")) return false;
2308   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2309   return obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol());
2310 }
2311
2312
2313 bool Value::IsRegExp() const {
2314   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsRegExp()")) return false;
2315   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2316   return obj->IsJSRegExp();
2317 }
2318
2319 bool Value::IsError() const {
2320   if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsError()")) return false;
2321   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2322   return obj->HasSpecificClassOf(HEAP->Error_symbol());
2323 }
2324
2325
2326 Local<String> Value::ToString() const {
2327   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2328   i::Handle<i::Object> str;
2329   if (obj->IsString()) {
2330     str = obj;
2331   } else {
2332     i::Isolate* isolate = i::Isolate::Current();
2333     if (IsDeadCheck(isolate, "v8::Value::ToString()")) {
2334       return Local<String>();
2335     }
2336     LOG_API(isolate, "ToString");
2337     ENTER_V8(isolate);
2338     EXCEPTION_PREAMBLE(isolate);
2339     str = i::Execution::ToString(obj, &has_pending_exception);
2340     EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2341   }
2342   return Local<String>(ToApi<String>(str));
2343 }
2344
2345
2346 Local<String> Value::ToDetailString() const {
2347   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2348   i::Handle<i::Object> str;
2349   if (obj->IsString()) {
2350     str = obj;
2351   } else {
2352     i::Isolate* isolate = i::Isolate::Current();
2353     if (IsDeadCheck(isolate, "v8::Value::ToDetailString()")) {
2354       return Local<String>();
2355     }
2356     LOG_API(isolate, "ToDetailString");
2357     ENTER_V8(isolate);
2358     EXCEPTION_PREAMBLE(isolate);
2359     str = i::Execution::ToDetailString(obj, &has_pending_exception);
2360     EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2361   }
2362   return Local<String>(ToApi<String>(str));
2363 }
2364
2365
2366 Local<v8::Object> Value::ToObject() const {
2367   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2368   i::Handle<i::Object> val;
2369   if (obj->IsJSObject()) {
2370     val = obj;
2371   } else {
2372     i::Isolate* isolate = i::Isolate::Current();
2373     if (IsDeadCheck(isolate, "v8::Value::ToObject()")) {
2374       return Local<v8::Object>();
2375     }
2376     LOG_API(isolate, "ToObject");
2377     ENTER_V8(isolate);
2378     EXCEPTION_PREAMBLE(isolate);
2379     val = i::Execution::ToObject(obj, &has_pending_exception);
2380     EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
2381   }
2382   return Local<v8::Object>(ToApi<Object>(val));
2383 }
2384
2385
2386 Local<Boolean> Value::ToBoolean() const {
2387   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2388   if (obj->IsBoolean()) {
2389     return Local<Boolean>(ToApi<Boolean>(obj));
2390   } else {
2391     i::Isolate* isolate = i::Isolate::Current();
2392     if (IsDeadCheck(isolate, "v8::Value::ToBoolean()")) {
2393       return Local<Boolean>();
2394     }
2395     LOG_API(isolate, "ToBoolean");
2396     ENTER_V8(isolate);
2397     i::Handle<i::Object> val = i::Execution::ToBoolean(obj);
2398     return Local<Boolean>(ToApi<Boolean>(val));
2399   }
2400 }
2401
2402
2403 Local<Number> Value::ToNumber() const {
2404   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2405   i::Handle<i::Object> num;
2406   if (obj->IsNumber()) {
2407     num = obj;
2408   } else {
2409     i::Isolate* isolate = i::Isolate::Current();
2410     if (IsDeadCheck(isolate, "v8::Value::ToNumber()")) {
2411       return Local<Number>();
2412     }
2413     LOG_API(isolate, "ToNumber");
2414     ENTER_V8(isolate);
2415     EXCEPTION_PREAMBLE(isolate);
2416     num = i::Execution::ToNumber(obj, &has_pending_exception);
2417     EXCEPTION_BAILOUT_CHECK(isolate, Local<Number>());
2418   }
2419   return Local<Number>(ToApi<Number>(num));
2420 }
2421
2422
2423 Local<Integer> Value::ToInteger() const {
2424   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2425   i::Handle<i::Object> num;
2426   if (obj->IsSmi()) {
2427     num = obj;
2428   } else {
2429     i::Isolate* isolate = i::Isolate::Current();
2430     if (IsDeadCheck(isolate, "v8::Value::ToInteger()")) return Local<Integer>();
2431     LOG_API(isolate, "ToInteger");
2432     ENTER_V8(isolate);
2433     EXCEPTION_PREAMBLE(isolate);
2434     num = i::Execution::ToInteger(obj, &has_pending_exception);
2435     EXCEPTION_BAILOUT_CHECK(isolate, Local<Integer>());
2436   }
2437   return Local<Integer>(ToApi<Integer>(num));
2438 }
2439
2440
2441 void External::CheckCast(v8::Value* that) {
2442   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Cast()")) return;
2443   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2444   ApiCheck(obj->IsForeign(),
2445            "v8::External::Cast()",
2446            "Could not convert to external");
2447 }
2448
2449
2450 void v8::Object::CheckCast(Value* that) {
2451   if (IsDeadCheck(i::Isolate::Current(), "v8::Object::Cast()")) return;
2452   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2453   ApiCheck(obj->IsJSObject(),
2454            "v8::Object::Cast()",
2455            "Could not convert to object");
2456 }
2457
2458
2459 void v8::Function::CheckCast(Value* that) {
2460   if (IsDeadCheck(i::Isolate::Current(), "v8::Function::Cast()")) return;
2461   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2462   ApiCheck(obj->IsJSFunction(),
2463            "v8::Function::Cast()",
2464            "Could not convert to function");
2465 }
2466
2467
2468 void v8::String::CheckCast(v8::Value* that) {
2469   if (IsDeadCheck(i::Isolate::Current(), "v8::String::Cast()")) return;
2470   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2471   ApiCheck(obj->IsString(),
2472            "v8::String::Cast()",
2473            "Could not convert to string");
2474 }
2475
2476
2477 void v8::Number::CheckCast(v8::Value* that) {
2478   if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Cast()")) return;
2479   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2480   ApiCheck(obj->IsNumber(),
2481            "v8::Number::Cast()",
2482            "Could not convert to number");
2483 }
2484
2485
2486 void v8::Integer::CheckCast(v8::Value* that) {
2487   if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Cast()")) return;
2488   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2489   ApiCheck(obj->IsNumber(),
2490            "v8::Integer::Cast()",
2491            "Could not convert to number");
2492 }
2493
2494
2495 void v8::Array::CheckCast(Value* that) {
2496   if (IsDeadCheck(i::Isolate::Current(), "v8::Array::Cast()")) return;
2497   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2498   ApiCheck(obj->IsJSArray(),
2499            "v8::Array::Cast()",
2500            "Could not convert to array");
2501 }
2502
2503
2504 void v8::Date::CheckCast(v8::Value* that) {
2505   i::Isolate* isolate = i::Isolate::Current();
2506   if (IsDeadCheck(isolate, "v8::Date::Cast()")) return;
2507   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2508   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Date_symbol()),
2509            "v8::Date::Cast()",
2510            "Could not convert to date");
2511 }
2512
2513
2514 void v8::StringObject::CheckCast(v8::Value* that) {
2515   i::Isolate* isolate = i::Isolate::Current();
2516   if (IsDeadCheck(isolate, "v8::StringObject::Cast()")) return;
2517   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2518   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->String_symbol()),
2519            "v8::StringObject::Cast()",
2520            "Could not convert to StringObject");
2521 }
2522
2523
2524 void v8::NumberObject::CheckCast(v8::Value* that) {
2525   i::Isolate* isolate = i::Isolate::Current();
2526   if (IsDeadCheck(isolate, "v8::NumberObject::Cast()")) return;
2527   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2528   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Number_symbol()),
2529            "v8::NumberObject::Cast()",
2530            "Could not convert to NumberObject");
2531 }
2532
2533
2534 void v8::BooleanObject::CheckCast(v8::Value* that) {
2535   i::Isolate* isolate = i::Isolate::Current();
2536   if (IsDeadCheck(isolate, "v8::BooleanObject::Cast()")) return;
2537   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2538   ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol()),
2539            "v8::BooleanObject::Cast()",
2540            "Could not convert to BooleanObject");
2541 }
2542
2543
2544 void v8::RegExp::CheckCast(v8::Value* that) {
2545   if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::Cast()")) return;
2546   i::Handle<i::Object> obj = Utils::OpenHandle(that);
2547   ApiCheck(obj->IsJSRegExp(),
2548            "v8::RegExp::Cast()",
2549            "Could not convert to regular expression");
2550 }
2551
2552
2553 bool Value::BooleanValue() const {
2554   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2555   if (obj->IsBoolean()) {
2556     return obj->IsTrue();
2557   } else {
2558     i::Isolate* isolate = i::Isolate::Current();
2559     if (IsDeadCheck(isolate, "v8::Value::BooleanValue()")) return false;
2560     LOG_API(isolate, "BooleanValue");
2561     ENTER_V8(isolate);
2562     i::Handle<i::Object> value = i::Execution::ToBoolean(obj);
2563     return value->IsTrue();
2564   }
2565 }
2566
2567
2568 double Value::NumberValue() const {
2569   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2570   i::Handle<i::Object> num;
2571   if (obj->IsNumber()) {
2572     num = obj;
2573   } else {
2574     i::Isolate* isolate = i::Isolate::Current();
2575     if (IsDeadCheck(isolate, "v8::Value::NumberValue()")) {
2576       return i::OS::nan_value();
2577     }
2578     LOG_API(isolate, "NumberValue");
2579     ENTER_V8(isolate);
2580     EXCEPTION_PREAMBLE(isolate);
2581     num = i::Execution::ToNumber(obj, &has_pending_exception);
2582     EXCEPTION_BAILOUT_CHECK(isolate, i::OS::nan_value());
2583   }
2584   return num->Number();
2585 }
2586
2587
2588 int64_t Value::IntegerValue() const {
2589   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2590   i::Handle<i::Object> num;
2591   if (obj->IsNumber()) {
2592     num = obj;
2593   } else {
2594     i::Isolate* isolate = i::Isolate::Current();
2595     if (IsDeadCheck(isolate, "v8::Value::IntegerValue()")) return 0;
2596     LOG_API(isolate, "IntegerValue");
2597     ENTER_V8(isolate);
2598     EXCEPTION_PREAMBLE(isolate);
2599     num = i::Execution::ToInteger(obj, &has_pending_exception);
2600     EXCEPTION_BAILOUT_CHECK(isolate, 0);
2601   }
2602   if (num->IsSmi()) {
2603     return i::Smi::cast(*num)->value();
2604   } else {
2605     return static_cast<int64_t>(num->Number());
2606   }
2607 }
2608
2609
2610 Local<Int32> Value::ToInt32() const {
2611   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2612   i::Handle<i::Object> num;
2613   if (obj->IsSmi()) {
2614     num = obj;
2615   } else {
2616     i::Isolate* isolate = i::Isolate::Current();
2617     if (IsDeadCheck(isolate, "v8::Value::ToInt32()")) return Local<Int32>();
2618     LOG_API(isolate, "ToInt32");
2619     ENTER_V8(isolate);
2620     EXCEPTION_PREAMBLE(isolate);
2621     num = i::Execution::ToInt32(obj, &has_pending_exception);
2622     EXCEPTION_BAILOUT_CHECK(isolate, Local<Int32>());
2623   }
2624   return Local<Int32>(ToApi<Int32>(num));
2625 }
2626
2627
2628 Local<Uint32> Value::ToUint32() const {
2629   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2630   i::Handle<i::Object> num;
2631   if (obj->IsSmi()) {
2632     num = obj;
2633   } else {
2634     i::Isolate* isolate = i::Isolate::Current();
2635     if (IsDeadCheck(isolate, "v8::Value::ToUint32()")) return Local<Uint32>();
2636     LOG_API(isolate, "ToUInt32");
2637     ENTER_V8(isolate);
2638     EXCEPTION_PREAMBLE(isolate);
2639     num = i::Execution::ToUint32(obj, &has_pending_exception);
2640     EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2641   }
2642   return Local<Uint32>(ToApi<Uint32>(num));
2643 }
2644
2645
2646 Local<Uint32> Value::ToArrayIndex() const {
2647   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2648   if (obj->IsSmi()) {
2649     if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
2650     return Local<Uint32>();
2651   }
2652   i::Isolate* isolate = i::Isolate::Current();
2653   if (IsDeadCheck(isolate, "v8::Value::ToArrayIndex()")) return Local<Uint32>();
2654   LOG_API(isolate, "ToArrayIndex");
2655   ENTER_V8(isolate);
2656   EXCEPTION_PREAMBLE(isolate);
2657   i::Handle<i::Object> string_obj =
2658       i::Execution::ToString(obj, &has_pending_exception);
2659   EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2660   i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
2661   uint32_t index;
2662   if (str->AsArrayIndex(&index)) {
2663     i::Handle<i::Object> value;
2664     if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
2665       value = i::Handle<i::Object>(i::Smi::FromInt(index));
2666     } else {
2667       value = isolate->factory()->NewNumber(index);
2668     }
2669     return Utils::Uint32ToLocal(value);
2670   }
2671   return Local<Uint32>();
2672 }
2673
2674
2675 int32_t Value::Int32Value() const {
2676   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2677   if (obj->IsSmi()) {
2678     return i::Smi::cast(*obj)->value();
2679   } else {
2680     i::Isolate* isolate = i::Isolate::Current();
2681     if (IsDeadCheck(isolate, "v8::Value::Int32Value()")) return 0;
2682     LOG_API(isolate, "Int32Value (slow)");
2683     ENTER_V8(isolate);
2684     EXCEPTION_PREAMBLE(isolate);
2685     i::Handle<i::Object> num =
2686         i::Execution::ToInt32(obj, &has_pending_exception);
2687     EXCEPTION_BAILOUT_CHECK(isolate, 0);
2688     if (num->IsSmi()) {
2689       return i::Smi::cast(*num)->value();
2690     } else {
2691       return static_cast<int32_t>(num->Number());
2692     }
2693   }
2694 }
2695
2696
2697 bool Value::Equals(Handle<Value> that) const {
2698   i::Isolate* isolate = i::Isolate::Current();
2699   if (IsDeadCheck(isolate, "v8::Value::Equals()")
2700       || EmptyCheck("v8::Value::Equals()", this)
2701       || EmptyCheck("v8::Value::Equals()", that)) {
2702     return false;
2703   }
2704   LOG_API(isolate, "Equals");
2705   ENTER_V8(isolate);
2706   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2707   i::Handle<i::Object> other = Utils::OpenHandle(*that);
2708   // If both obj and other are JSObjects, we'd better compare by identity
2709   // immediately when going into JS builtin.  The reason is Invoke
2710   // would overwrite global object receiver with global proxy.
2711   if (obj->IsJSObject() && other->IsJSObject()) {
2712     return *obj == *other;
2713   }
2714   i::Handle<i::Object> args[] = { other };
2715   EXCEPTION_PREAMBLE(isolate);
2716   i::Handle<i::Object> result =
2717       CallV8HeapFunction("EQUALS", obj, ARRAY_SIZE(args), args,
2718                          &has_pending_exception);
2719   EXCEPTION_BAILOUT_CHECK(isolate, false);
2720   return *result == i::Smi::FromInt(i::EQUAL);
2721 }
2722
2723
2724 bool Value::StrictEquals(Handle<Value> that) const {
2725   i::Isolate* isolate = i::Isolate::Current();
2726   if (IsDeadCheck(isolate, "v8::Value::StrictEquals()")
2727       || EmptyCheck("v8::Value::StrictEquals()", this)
2728       || EmptyCheck("v8::Value::StrictEquals()", that)) {
2729     return false;
2730   }
2731   LOG_API(isolate, "StrictEquals");
2732   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2733   i::Handle<i::Object> other = Utils::OpenHandle(*that);
2734   // Must check HeapNumber first, since NaN !== NaN.
2735   if (obj->IsHeapNumber()) {
2736     if (!other->IsNumber()) return false;
2737     double x = obj->Number();
2738     double y = other->Number();
2739     // Must check explicitly for NaN:s on Windows, but -0 works fine.
2740     return x == y && !isnan(x) && !isnan(y);
2741   } else if (*obj == *other) {  // Also covers Booleans.
2742     return true;
2743   } else if (obj->IsSmi()) {
2744     return other->IsNumber() && obj->Number() == other->Number();
2745   } else if (obj->IsString()) {
2746     return other->IsString() &&
2747       i::String::cast(*obj)->Equals(i::String::cast(*other));
2748   } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
2749     return other->IsUndefined() || other->IsUndetectableObject();
2750   } else {
2751     return false;
2752   }
2753 }
2754
2755
2756 uint32_t Value::Uint32Value() const {
2757   i::Handle<i::Object> obj = Utils::OpenHandle(this);
2758   if (obj->IsSmi()) {
2759     return i::Smi::cast(*obj)->value();
2760   } else {
2761     i::Isolate* isolate = i::Isolate::Current();
2762     if (IsDeadCheck(isolate, "v8::Value::Uint32Value()")) return 0;
2763     LOG_API(isolate, "Uint32Value");
2764     ENTER_V8(isolate);
2765     EXCEPTION_PREAMBLE(isolate);
2766     i::Handle<i::Object> num =
2767         i::Execution::ToUint32(obj, &has_pending_exception);
2768     EXCEPTION_BAILOUT_CHECK(isolate, 0);
2769     if (num->IsSmi()) {
2770       return i::Smi::cast(*num)->value();
2771     } else {
2772       return static_cast<uint32_t>(num->Number());
2773     }
2774   }
2775 }
2776
2777
2778 bool v8::Object::Set(v8::Handle<Value> key, v8::Handle<Value> value,
2779                      v8::PropertyAttribute attribs) {
2780   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2781   ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2782   ENTER_V8(isolate);
2783   i::HandleScope scope(isolate);
2784   i::Handle<i::Object> self = Utils::OpenHandle(this);
2785   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2786   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2787   EXCEPTION_PREAMBLE(isolate);
2788   i::Handle<i::Object> obj = i::SetProperty(
2789       self,
2790       key_obj,
2791       value_obj,
2792       static_cast<PropertyAttributes>(attribs),
2793       i::kNonStrictMode);
2794   has_pending_exception = obj.is_null();
2795   EXCEPTION_BAILOUT_CHECK(isolate, false);
2796   return true;
2797 }
2798
2799
2800 bool v8::Object::Set(uint32_t index, v8::Handle<Value> value) {
2801   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2802   ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2803   ENTER_V8(isolate);
2804   i::HandleScope scope(isolate);
2805   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2806   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2807   EXCEPTION_PREAMBLE(isolate);
2808   i::Handle<i::Object> obj = i::SetElement(
2809       self,
2810       index,
2811       value_obj,
2812       i::kNonStrictMode);
2813   has_pending_exception = obj.is_null();
2814   EXCEPTION_BAILOUT_CHECK(isolate, false);
2815   return true;
2816 }
2817
2818
2819 bool v8::Object::ForceSet(v8::Handle<Value> key,
2820                           v8::Handle<Value> value,
2821                           v8::PropertyAttribute attribs) {
2822   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2823   ON_BAILOUT(isolate, "v8::Object::ForceSet()", return false);
2824   ENTER_V8(isolate);
2825   i::HandleScope scope(isolate);
2826   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2827   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2828   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2829   EXCEPTION_PREAMBLE(isolate);
2830   i::Handle<i::Object> obj = i::ForceSetProperty(
2831       self,
2832       key_obj,
2833       value_obj,
2834       static_cast<PropertyAttributes>(attribs));
2835   has_pending_exception = obj.is_null();
2836   EXCEPTION_BAILOUT_CHECK(isolate, false);
2837   return true;
2838 }
2839
2840
2841 bool v8::Object::ForceDelete(v8::Handle<Value> key) {
2842   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2843   ON_BAILOUT(isolate, "v8::Object::ForceDelete()", return false);
2844   ENTER_V8(isolate);
2845   i::HandleScope scope(isolate);
2846   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2847   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2848
2849   // When turning on access checks for a global object deoptimize all functions
2850   // as optimized code does not always handle access checks.
2851   i::Deoptimizer::DeoptimizeGlobalObject(*self);
2852
2853   EXCEPTION_PREAMBLE(isolate);
2854   i::Handle<i::Object> obj = i::ForceDeleteProperty(self, key_obj);
2855   has_pending_exception = obj.is_null();
2856   EXCEPTION_BAILOUT_CHECK(isolate, false);
2857   return obj->IsTrue();
2858 }
2859
2860
2861 Local<Value> v8::Object::Get(v8::Handle<Value> key) {
2862   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2863   ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2864   ENTER_V8(isolate);
2865   i::Handle<i::Object> self = Utils::OpenHandle(this);
2866   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2867   EXCEPTION_PREAMBLE(isolate);
2868   i::Handle<i::Object> result = i::GetProperty(self, key_obj);
2869   has_pending_exception = result.is_null();
2870   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2871   return Utils::ToLocal(result);
2872 }
2873
2874
2875 Local<Value> v8::Object::Get(uint32_t index) {
2876   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2877   ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2878   ENTER_V8(isolate);
2879   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2880   EXCEPTION_PREAMBLE(isolate);
2881   i::Handle<i::Object> result = i::Object::GetElement(self, index);
2882   has_pending_exception = result.is_null();
2883   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2884   return Utils::ToLocal(result);
2885 }
2886
2887
2888 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Handle<Value> key) {
2889   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2890   ON_BAILOUT(isolate, "v8::Object::GetPropertyAttribute()",
2891              return static_cast<PropertyAttribute>(NONE));
2892   ENTER_V8(isolate);
2893   i::HandleScope scope(isolate);
2894   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2895   i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2896   if (!key_obj->IsString()) {
2897     EXCEPTION_PREAMBLE(isolate);
2898     key_obj = i::Execution::ToString(key_obj, &has_pending_exception);
2899     EXCEPTION_BAILOUT_CHECK(isolate, static_cast<PropertyAttribute>(NONE));
2900   }
2901   i::Handle<i::String> key_string = i::Handle<i::String>::cast(key_obj);
2902   PropertyAttributes result = self->GetPropertyAttribute(*key_string);
2903   if (result == ABSENT) return static_cast<PropertyAttribute>(NONE);
2904   return static_cast<PropertyAttribute>(result);
2905 }
2906
2907
2908 Local<Value> v8::Object::GetPrototype() {
2909   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2910   ON_BAILOUT(isolate, "v8::Object::GetPrototype()",
2911              return Local<v8::Value>());
2912   ENTER_V8(isolate);
2913   i::Handle<i::Object> self = Utils::OpenHandle(this);
2914   i::Handle<i::Object> result = i::GetPrototype(self);
2915   return Utils::ToLocal(result);
2916 }
2917
2918
2919 bool v8::Object::SetPrototype(Handle<Value> value) {
2920   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2921   ON_BAILOUT(isolate, "v8::Object::SetPrototype()", return false);
2922   ENTER_V8(isolate);
2923   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2924   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2925   // We do not allow exceptions thrown while setting the prototype
2926   // to propagate outside.
2927   TryCatch try_catch;
2928   EXCEPTION_PREAMBLE(isolate);
2929   i::Handle<i::Object> result = i::SetPrototype(self, value_obj);
2930   has_pending_exception = result.is_null();
2931   EXCEPTION_BAILOUT_CHECK(isolate, false);
2932   return true;
2933 }
2934
2935
2936 Local<Object> v8::Object::FindInstanceInPrototypeChain(
2937     v8::Handle<FunctionTemplate> tmpl) {
2938   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2939   ON_BAILOUT(isolate,
2940              "v8::Object::FindInstanceInPrototypeChain()",
2941              return Local<v8::Object>());
2942   ENTER_V8(isolate);
2943   i::JSObject* object = *Utils::OpenHandle(this);
2944   i::FunctionTemplateInfo* tmpl_info = *Utils::OpenHandle(*tmpl);
2945   while (!object->IsInstanceOf(tmpl_info)) {
2946     i::Object* prototype = object->GetPrototype();
2947     if (!prototype->IsJSObject()) return Local<Object>();
2948     object = i::JSObject::cast(prototype);
2949   }
2950   return Utils::ToLocal(i::Handle<i::JSObject>(object));
2951 }
2952
2953
2954 Local<Array> v8::Object::GetPropertyNames() {
2955   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2956   ON_BAILOUT(isolate, "v8::Object::GetPropertyNames()",
2957              return Local<v8::Array>());
2958   ENTER_V8(isolate);
2959   i::HandleScope scope(isolate);
2960   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2961   bool threw = false;
2962   i::Handle<i::FixedArray> value =
2963       i::GetKeysInFixedArrayFor(self, i::INCLUDE_PROTOS, &threw);
2964   if (threw) return Local<v8::Array>();
2965   // Because we use caching to speed up enumeration it is important
2966   // to never change the result of the basic enumeration function so
2967   // we clone the result.
2968   i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2969   i::Handle<i::JSArray> result =
2970       isolate->factory()->NewJSArrayWithElements(elms);
2971   return Utils::ToLocal(scope.CloseAndEscape(result));
2972 }
2973
2974
2975 Local<Array> v8::Object::GetOwnPropertyNames() {
2976   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2977   ON_BAILOUT(isolate, "v8::Object::GetOwnPropertyNames()",
2978              return Local<v8::Array>());
2979   ENTER_V8(isolate);
2980   i::HandleScope scope(isolate);
2981   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2982   bool threw = false;
2983   i::Handle<i::FixedArray> value =
2984       i::GetKeysInFixedArrayFor(self, i::LOCAL_ONLY, &threw);
2985   if (threw) return Local<v8::Array>();
2986   // Because we use caching to speed up enumeration it is important
2987   // to never change the result of the basic enumeration function so
2988   // we clone the result.
2989   i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2990   i::Handle<i::JSArray> result =
2991       isolate->factory()->NewJSArrayWithElements(elms);
2992   return Utils::ToLocal(scope.CloseAndEscape(result));
2993 }
2994
2995
2996 Local<String> v8::Object::ObjectProtoToString() {
2997   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2998   ON_BAILOUT(isolate, "v8::Object::ObjectProtoToString()",
2999              return Local<v8::String>());
3000   ENTER_V8(isolate);
3001   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3002
3003   i::Handle<i::Object> name(self->class_name());
3004
3005   // Native implementation of Object.prototype.toString (v8natives.js):
3006   //   var c = %ClassOf(this);
3007   //   if (c === 'Arguments') c  = 'Object';
3008   //   return "[object " + c + "]";
3009
3010   if (!name->IsString()) {
3011     return v8::String::New("[object ]");
3012
3013   } else {
3014     i::Handle<i::String> class_name = i::Handle<i::String>::cast(name);
3015     if (class_name->IsEqualTo(i::CStrVector("Arguments"))) {
3016       return v8::String::New("[object Object]");
3017
3018     } else {
3019       const char* prefix = "[object ";
3020       Local<String> str = Utils::ToLocal(class_name);
3021       const char* postfix = "]";
3022
3023       int prefix_len = i::StrLength(prefix);
3024       int str_len = str->Length();
3025       int postfix_len = i::StrLength(postfix);
3026
3027       int buf_len = prefix_len + str_len + postfix_len;
3028       i::ScopedVector<char> buf(buf_len);
3029
3030       // Write prefix.
3031       char* ptr = buf.start();
3032       memcpy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3033       ptr += prefix_len;
3034
3035       // Write real content.
3036       str->WriteAscii(ptr, 0, str_len);
3037       ptr += str_len;
3038
3039       // Write postfix.
3040       memcpy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3041
3042       // Copy the buffer into a heap-allocated string and return it.
3043       Local<String> result = v8::String::New(buf.start(), buf_len);
3044       return result;
3045     }
3046   }
3047 }
3048
3049
3050 Local<String> v8::Object::GetConstructorName() {
3051   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3052   ON_BAILOUT(isolate, "v8::Object::GetConstructorName()",
3053              return Local<v8::String>());
3054   ENTER_V8(isolate);
3055   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3056   i::Handle<i::String> name(self->constructor_name());
3057   return Utils::ToLocal(name);
3058 }
3059
3060
3061 bool v8::Object::Delete(v8::Handle<String> key) {
3062   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3063   ON_BAILOUT(isolate, "v8::Object::Delete()", return false);
3064   ENTER_V8(isolate);
3065   i::HandleScope scope(isolate);
3066   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3067   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3068   return i::DeleteProperty(self, key_obj)->IsTrue();
3069 }
3070
3071
3072 bool v8::Object::Has(v8::Handle<String> key) {
3073   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3074   ON_BAILOUT(isolate, "v8::Object::Has()", return false);
3075   ENTER_V8(isolate);
3076   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3077   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3078   return self->HasProperty(*key_obj);
3079 }
3080
3081
3082 bool v8::Object::Delete(uint32_t index) {
3083   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3084   ON_BAILOUT(isolate, "v8::Object::DeleteProperty()",
3085              return false);
3086   ENTER_V8(isolate);
3087   HandleScope scope;
3088   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3089   return i::DeleteElement(self, index)->IsTrue();
3090 }
3091
3092
3093 bool v8::Object::Has(uint32_t index) {
3094   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3095   ON_BAILOUT(isolate, "v8::Object::HasProperty()", return false);
3096   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3097   return self->HasElement(index);
3098 }
3099
3100
3101 bool Object::SetAccessor(Handle<String> name,
3102                          AccessorGetter getter,
3103                          AccessorSetter setter,
3104                          v8::Handle<Value> data,
3105                          AccessControl settings,
3106                          PropertyAttribute attributes) {
3107   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3108   ON_BAILOUT(isolate, "v8::Object::SetAccessor()", return false);
3109   ENTER_V8(isolate);
3110   i::HandleScope scope(isolate);
3111   i::Handle<i::AccessorInfo> info = MakeAccessorInfo(name,
3112                                                      getter, setter, data,
3113                                                      settings, attributes);
3114   i::Handle<i::Object> result = i::SetAccessor(Utils::OpenHandle(this), info);
3115   return !result.is_null() && !result->IsUndefined();
3116 }
3117
3118
3119 bool v8::Object::HasOwnProperty(Handle<String> key) {
3120   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3121   ON_BAILOUT(isolate, "v8::Object::HasOwnProperty()",
3122              return false);
3123   return Utils::OpenHandle(this)->HasLocalProperty(
3124       *Utils::OpenHandle(*key));
3125 }
3126
3127
3128 bool v8::Object::HasRealNamedProperty(Handle<String> key) {
3129   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3130   ON_BAILOUT(isolate, "v8::Object::HasRealNamedProperty()",
3131              return false);
3132   return Utils::OpenHandle(this)->HasRealNamedProperty(
3133       *Utils::OpenHandle(*key));
3134 }
3135
3136
3137 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
3138   ON_BAILOUT(Utils::OpenHandle(this)->GetIsolate(),
3139              "v8::Object::HasRealIndexedProperty()",
3140              return false);
3141   return Utils::OpenHandle(this)->HasRealElementProperty(index);
3142 }
3143
3144
3145 bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
3146   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3147   ON_BAILOUT(isolate,
3148              "v8::Object::HasRealNamedCallbackProperty()",
3149              return false);
3150   ENTER_V8(isolate);
3151   return Utils::OpenHandle(this)->HasRealNamedCallbackProperty(
3152       *Utils::OpenHandle(*key));
3153 }
3154
3155
3156 bool v8::Object::HasNamedLookupInterceptor() {
3157   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3158   ON_BAILOUT(isolate, "v8::Object::HasNamedLookupInterceptor()",
3159              return false);
3160   return Utils::OpenHandle(this)->HasNamedInterceptor();
3161 }
3162
3163
3164 bool v8::Object::HasIndexedLookupInterceptor() {
3165   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3166   ON_BAILOUT(isolate, "v8::Object::HasIndexedLookupInterceptor()",
3167              return false);
3168   return Utils::OpenHandle(this)->HasIndexedInterceptor();
3169 }
3170
3171
3172 static Local<Value> GetPropertyByLookup(i::Isolate* isolate,
3173                                         i::Handle<i::JSObject> receiver,
3174                                         i::Handle<i::String> name,
3175                                         i::LookupResult* lookup) {
3176   if (!lookup->IsProperty()) {
3177     // No real property was found.
3178     return Local<Value>();
3179   }
3180
3181   // If the property being looked up is a callback, it can throw
3182   // an exception.
3183   EXCEPTION_PREAMBLE(isolate);
3184   PropertyAttributes ignored;
3185   i::Handle<i::Object> result =
3186       i::Object::GetProperty(receiver, receiver, lookup, name,
3187                              &ignored);
3188   has_pending_exception = result.is_null();
3189   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3190
3191   return Utils::ToLocal(result);
3192 }
3193
3194
3195 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
3196       Handle<String> key) {
3197   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3198   ON_BAILOUT(isolate,
3199              "v8::Object::GetRealNamedPropertyInPrototypeChain()",
3200              return Local<Value>());
3201   ENTER_V8(isolate);
3202   i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3203   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3204   i::LookupResult lookup(isolate);
3205   self_obj->LookupRealNamedPropertyInPrototypes(*key_obj, &lookup);
3206   return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3207 }
3208
3209
3210 Local<Value> v8::Object::GetRealNamedProperty(Handle<String> key) {
3211   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3212   ON_BAILOUT(isolate, "v8::Object::GetRealNamedProperty()",
3213              return Local<Value>());
3214   ENTER_V8(isolate);
3215   i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3216   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3217   i::LookupResult lookup(isolate);
3218   self_obj->LookupRealNamedProperty(*key_obj, &lookup);
3219   return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3220 }
3221
3222
3223 // Turns on access checks by copying the map and setting the check flag.
3224 // Because the object gets a new map, existing inline cache caching
3225 // the old map of this object will fail.
3226 void v8::Object::TurnOnAccessCheck() {
3227   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3228   ON_BAILOUT(isolate, "v8::Object::TurnOnAccessCheck()", return);
3229   ENTER_V8(isolate);
3230   i::HandleScope scope(isolate);
3231   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3232
3233   // When turning on access checks for a global object deoptimize all functions
3234   // as optimized code does not always handle access checks.
3235   i::Deoptimizer::DeoptimizeGlobalObject(*obj);
3236
3237   i::Handle<i::Map> new_map =
3238       isolate->factory()->CopyMapDropTransitions(i::Handle<i::Map>(obj->map()));
3239   new_map->set_is_access_check_needed(true);
3240   obj->set_map(*new_map);
3241 }
3242
3243
3244 bool v8::Object::IsDirty() {
3245   return Utils::OpenHandle(this)->IsDirty();
3246 }
3247
3248
3249 Local<v8::Object> v8::Object::Clone() {
3250   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3251   ON_BAILOUT(isolate, "v8::Object::Clone()", return Local<Object>());
3252   ENTER_V8(isolate);
3253   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3254   EXCEPTION_PREAMBLE(isolate);
3255   i::Handle<i::JSObject> result = i::Copy(self);
3256   has_pending_exception = result.is_null();
3257   EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3258   return Utils::ToLocal(result);
3259 }
3260
3261
3262 static i::Context* GetCreationContext(i::JSObject* object) {
3263   i::Object* constructor = object->map()->constructor();
3264   i::JSFunction* function;
3265   if (!constructor->IsJSFunction()) {
3266     // Functions have null as a constructor,
3267     // but any JSFunction knows its context immediately.
3268     ASSERT(object->IsJSFunction());
3269     function = i::JSFunction::cast(object);
3270   } else {
3271     function = i::JSFunction::cast(constructor);
3272   }
3273   return function->context()->global_context();
3274 }
3275
3276
3277 Local<v8::Context> v8::Object::CreationContext() {
3278   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3279   ON_BAILOUT(isolate,
3280              "v8::Object::CreationContext()", return Local<v8::Context>());
3281   ENTER_V8(isolate);
3282   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3283   i::Context* context = GetCreationContext(*self);
3284   return Utils::ToLocal(i::Handle<i::Context>(context));
3285 }
3286
3287
3288 int v8::Object::GetIdentityHash() {
3289   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3290   ON_BAILOUT(isolate, "v8::Object::GetIdentityHash()", return 0);
3291   ENTER_V8(isolate);
3292   i::HandleScope scope(isolate);
3293   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3294   return i::GetIdentityHash(self);
3295 }
3296
3297
3298 bool v8::Object::SetHiddenValue(v8::Handle<v8::String> key,
3299                                 v8::Handle<v8::Value> value) {
3300   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3301   ON_BAILOUT(isolate, "v8::Object::SetHiddenValue()", return false);
3302   ENTER_V8(isolate);
3303   i::HandleScope scope(isolate);
3304   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3305   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3306   i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3307   i::Handle<i::Object> result = i::SetHiddenProperty(self, key_obj, value_obj);
3308   return *result == *self;
3309 }
3310
3311
3312 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Handle<v8::String> key) {
3313   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3314   ON_BAILOUT(isolate, "v8::Object::GetHiddenValue()",
3315              return Local<v8::Value>());
3316   ENTER_V8(isolate);
3317   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3318   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3319   i::Handle<i::Object> result(self->GetHiddenProperty(*key_obj));
3320   if (result->IsUndefined()) return v8::Local<v8::Value>();
3321   return Utils::ToLocal(result);
3322 }
3323
3324
3325 bool v8::Object::DeleteHiddenValue(v8::Handle<v8::String> key) {
3326   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3327   ON_BAILOUT(isolate, "v8::DeleteHiddenValue()", return false);
3328   ENTER_V8(isolate);
3329   i::HandleScope scope(isolate);
3330   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3331   i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3332   self->DeleteHiddenProperty(*key_obj);
3333   return true;
3334 }
3335
3336
3337 namespace {
3338
3339 static i::ElementsKind GetElementsKindFromExternalArrayType(
3340     ExternalArrayType array_type) {
3341   switch (array_type) {
3342     case kExternalByteArray:
3343       return i::EXTERNAL_BYTE_ELEMENTS;
3344       break;
3345     case kExternalUnsignedByteArray:
3346       return i::EXTERNAL_UNSIGNED_BYTE_ELEMENTS;
3347       break;
3348     case kExternalShortArray:
3349       return i::EXTERNAL_SHORT_ELEMENTS;
3350       break;
3351     case kExternalUnsignedShortArray:
3352       return i::EXTERNAL_UNSIGNED_SHORT_ELEMENTS;
3353       break;
3354     case kExternalIntArray:
3355       return i::EXTERNAL_INT_ELEMENTS;
3356       break;
3357     case kExternalUnsignedIntArray:
3358       return i::EXTERNAL_UNSIGNED_INT_ELEMENTS;
3359       break;
3360     case kExternalFloatArray:
3361       return i::EXTERNAL_FLOAT_ELEMENTS;
3362       break;
3363     case kExternalDoubleArray:
3364       return i::EXTERNAL_DOUBLE_ELEMENTS;
3365       break;
3366     case kExternalPixelArray:
3367       return i::EXTERNAL_PIXEL_ELEMENTS;
3368       break;
3369   }
3370   UNREACHABLE();
3371   return i::DICTIONARY_ELEMENTS;
3372 }
3373
3374
3375 void PrepareExternalArrayElements(i::Handle<i::JSObject> object,
3376                                   void* data,
3377                                   ExternalArrayType array_type,
3378                                   int length) {
3379   i::Isolate* isolate = object->GetIsolate();
3380   i::Handle<i::ExternalArray> array =
3381       isolate->factory()->NewExternalArray(length, array_type, data);
3382
3383   i::Handle<i::Map> external_array_map =
3384       isolate->factory()->GetElementsTransitionMap(
3385           object,
3386           GetElementsKindFromExternalArrayType(array_type));
3387
3388   object->set_map(*external_array_map);
3389   object->set_elements(*array);
3390 }
3391
3392 }  // namespace
3393
3394
3395 void v8::Object::SetIndexedPropertiesToPixelData(uint8_t* data, int length) {
3396   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3397   ON_BAILOUT(isolate, "v8::SetElementsToPixelData()", return);
3398   ENTER_V8(isolate);
3399   i::HandleScope scope(isolate);
3400   if (!ApiCheck(length <= i::ExternalPixelArray::kMaxLength,
3401                 "v8::Object::SetIndexedPropertiesToPixelData()",
3402                 "length exceeds max acceptable value")) {
3403     return;
3404   }
3405   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3406   if (!ApiCheck(!self->IsJSArray(),
3407                 "v8::Object::SetIndexedPropertiesToPixelData()",
3408                 "JSArray is not supported")) {
3409     return;
3410   }
3411   PrepareExternalArrayElements(self, data, kExternalPixelArray, length);
3412 }
3413
3414
3415 bool v8::Object::HasIndexedPropertiesInPixelData() {
3416   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3417   ON_BAILOUT(self->GetIsolate(), "v8::HasIndexedPropertiesInPixelData()",
3418              return false);
3419   return self->HasExternalPixelElements();
3420 }
3421
3422
3423 uint8_t* v8::Object::GetIndexedPropertiesPixelData() {
3424   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3425   ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelData()",
3426              return NULL);
3427   if (self->HasExternalPixelElements()) {
3428     return i::ExternalPixelArray::cast(self->elements())->
3429         external_pixel_pointer();
3430   } else {
3431     return NULL;
3432   }
3433 }
3434
3435
3436 int v8::Object::GetIndexedPropertiesPixelDataLength() {
3437   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3438   ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelDataLength()",
3439              return -1);
3440   if (self->HasExternalPixelElements()) {
3441     return i::ExternalPixelArray::cast(self->elements())->length();
3442   } else {
3443     return -1;
3444   }
3445 }
3446
3447
3448 void v8::Object::SetIndexedPropertiesToExternalArrayData(
3449     void* data,
3450     ExternalArrayType array_type,
3451     int length) {
3452   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3453   ON_BAILOUT(isolate, "v8::SetIndexedPropertiesToExternalArrayData()", return);
3454   ENTER_V8(isolate);
3455   i::HandleScope scope(isolate);
3456   if (!ApiCheck(length <= i::ExternalArray::kMaxLength,
3457                 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3458                 "length exceeds max acceptable value")) {
3459     return;
3460   }
3461   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3462   if (!ApiCheck(!self->IsJSArray(),
3463                 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3464                 "JSArray is not supported")) {
3465     return;
3466   }
3467   PrepareExternalArrayElements(self, data, array_type, length);
3468 }
3469
3470
3471 bool v8::Object::HasIndexedPropertiesInExternalArrayData() {
3472   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3473   ON_BAILOUT(self->GetIsolate(),
3474              "v8::HasIndexedPropertiesInExternalArrayData()",
3475              return false);
3476   return self->HasExternalArrayElements();
3477 }
3478
3479
3480 void* v8::Object::GetIndexedPropertiesExternalArrayData() {
3481   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3482   ON_BAILOUT(self->GetIsolate(),
3483              "v8::GetIndexedPropertiesExternalArrayData()",
3484              return NULL);
3485   if (self->HasExternalArrayElements()) {
3486     return i::ExternalArray::cast(self->elements())->external_pointer();
3487   } else {
3488     return NULL;
3489   }
3490 }
3491
3492
3493 ExternalArrayType v8::Object::GetIndexedPropertiesExternalArrayDataType() {
3494   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3495   ON_BAILOUT(self->GetIsolate(),
3496              "v8::GetIndexedPropertiesExternalArrayDataType()",
3497              return static_cast<ExternalArrayType>(-1));
3498   switch (self->elements()->map()->instance_type()) {
3499     case i::EXTERNAL_BYTE_ARRAY_TYPE:
3500       return kExternalByteArray;
3501     case i::EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
3502       return kExternalUnsignedByteArray;
3503     case i::EXTERNAL_SHORT_ARRAY_TYPE:
3504       return kExternalShortArray;
3505     case i::EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
3506       return kExternalUnsignedShortArray;
3507     case i::EXTERNAL_INT_ARRAY_TYPE:
3508       return kExternalIntArray;
3509     case i::EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
3510       return kExternalUnsignedIntArray;
3511     case i::EXTERNAL_FLOAT_ARRAY_TYPE:
3512       return kExternalFloatArray;
3513     case i::EXTERNAL_DOUBLE_ARRAY_TYPE:
3514       return kExternalDoubleArray;
3515     case i::EXTERNAL_PIXEL_ARRAY_TYPE:
3516       return kExternalPixelArray;
3517     default:
3518       return static_cast<ExternalArrayType>(-1);
3519   }
3520 }
3521
3522
3523 int v8::Object::GetIndexedPropertiesExternalArrayDataLength() {
3524   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3525   ON_BAILOUT(self->GetIsolate(),
3526              "v8::GetIndexedPropertiesExternalArrayDataLength()",
3527              return 0);
3528   if (self->HasExternalArrayElements()) {
3529     return i::ExternalArray::cast(self->elements())->length();
3530   } else {
3531     return -1;
3532   }
3533 }
3534
3535
3536 bool v8::Object::IsCallable() {
3537   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3538   ON_BAILOUT(isolate, "v8::Object::IsCallable()", return false);
3539   ENTER_V8(isolate);
3540   i::HandleScope scope(isolate);
3541   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3542   if (obj->IsJSFunction()) return true;
3543   return i::Execution::GetFunctionDelegate(obj)->IsJSFunction();
3544 }
3545
3546
3547 Local<v8::Value> Object::CallAsFunction(v8::Handle<v8::Object> recv,
3548                                         int argc,
3549                                         v8::Handle<v8::Value> argv[]) {
3550   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3551   ON_BAILOUT(isolate, "v8::Object::CallAsFunction()",
3552              return Local<v8::Value>());
3553   LOG_API(isolate, "Object::CallAsFunction");
3554   ENTER_V8(isolate);
3555   i::HandleScope scope(isolate);
3556   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3557   i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3558   STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3559   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3560   i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>();
3561   if (obj->IsJSFunction()) {
3562     fun = i::Handle<i::JSFunction>::cast(obj);
3563   } else {
3564     EXCEPTION_PREAMBLE(isolate);
3565     i::Handle<i::Object> delegate =
3566         i::Execution::TryGetFunctionDelegate(obj, &has_pending_exception);
3567     EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3568     fun = i::Handle<i::JSFunction>::cast(delegate);
3569     recv_obj = obj;
3570   }
3571   EXCEPTION_PREAMBLE(isolate);
3572   i::Handle<i::Object> returned =
3573       i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3574   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3575   return Utils::ToLocal(scope.CloseAndEscape(returned));
3576 }
3577
3578
3579 Local<v8::Value> Object::CallAsConstructor(int argc,
3580                                            v8::Handle<v8::Value> argv[]) {
3581   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3582   ON_BAILOUT(isolate, "v8::Object::CallAsConstructor()",
3583              return Local<v8::Object>());
3584   LOG_API(isolate, "Object::CallAsConstructor");
3585   ENTER_V8(isolate);
3586   i::HandleScope scope(isolate);
3587   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3588   STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3589   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3590   if (obj->IsJSFunction()) {
3591     i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(obj);
3592     EXCEPTION_PREAMBLE(isolate);
3593     i::Handle<i::Object> returned =
3594         i::Execution::New(fun, argc, args, &has_pending_exception);
3595     EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3596     return Utils::ToLocal(scope.CloseAndEscape(
3597         i::Handle<i::JSObject>::cast(returned)));
3598   }
3599   EXCEPTION_PREAMBLE(isolate);
3600   i::Handle<i::Object> delegate =
3601       i::Execution::TryGetConstructorDelegate(obj, &has_pending_exception);
3602   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3603   if (!delegate->IsUndefined()) {
3604     i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(delegate);
3605     EXCEPTION_PREAMBLE(isolate);
3606     i::Handle<i::Object> returned =
3607         i::Execution::Call(fun, obj, argc, args, &has_pending_exception);
3608     EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3609     ASSERT(!delegate->IsUndefined());
3610     return Utils::ToLocal(scope.CloseAndEscape(returned));
3611   }
3612   return Local<v8::Object>();
3613 }
3614
3615
3616 Local<v8::Object> Function::NewInstance() const {
3617   return NewInstance(0, NULL);
3618 }
3619
3620
3621 Local<v8::Object> Function::NewInstance(int argc,
3622                                         v8::Handle<v8::Value> argv[]) const {
3623   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3624   ON_BAILOUT(isolate, "v8::Function::NewInstance()",
3625              return Local<v8::Object>());
3626   LOG_API(isolate, "Function::NewInstance");
3627   ENTER_V8(isolate);
3628   HandleScope scope;
3629   i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
3630   STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3631   i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3632   EXCEPTION_PREAMBLE(isolate);
3633   i::Handle<i::Object> returned =
3634       i::Execution::New(function, argc, args, &has_pending_exception);
3635   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3636   return scope.Close(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
3637 }
3638
3639
3640 Local<v8::Value> Function::Call(v8::Handle<v8::Object> recv, int argc,
3641                                 v8::Handle<v8::Value> argv[]) {
3642   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3643   ON_BAILOUT(isolate, "v8::Function::Call()", return Local<v8::Value>());
3644   LOG_API(isolate, "Function::Call");
3645   ENTER_V8(isolate);
3646   i::Object* raw_result = NULL;
3647   {
3648     i::HandleScope scope(isolate);
3649     i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
3650     i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3651     STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3652     i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3653     EXCEPTION_PREAMBLE(isolate);
3654     i::Handle<i::Object> returned =
3655         i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3656     EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3657     raw_result = *returned;
3658   }
3659   i::Handle<i::Object> result(raw_result);
3660   return Utils::ToLocal(result);
3661 }
3662
3663
3664 void Function::SetName(v8::Handle<v8::String> name) {
3665   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3666   ENTER_V8(isolate);
3667   USE(isolate);
3668   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3669   func->shared()->set_name(*Utils::OpenHandle(*name));
3670 }
3671
3672
3673 Handle<Value> Function::GetName() const {
3674   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3675   return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name()));
3676 }
3677
3678
3679 ScriptOrigin Function::GetScriptOrigin() const {
3680   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3681   if (func->shared()->script()->IsScript()) {
3682     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
3683     v8::ScriptOrigin origin(
3684       Utils::ToLocal(i::Handle<i::Object>(script->name())),
3685       v8::Integer::New(script->line_offset()->value()),
3686       v8::Integer::New(script->column_offset()->value()));
3687     return origin;
3688   }
3689   return v8::ScriptOrigin(Handle<Value>());
3690 }
3691
3692
3693 const int Function::kLineOffsetNotFound = -1;
3694
3695
3696 int Function::GetScriptLineNumber() const {
3697   i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3698   if (func->shared()->script()->IsScript()) {
3699     i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
3700     return i::GetScriptLineNumber(script, func->shared()->start_position());
3701   }
3702   return kLineOffsetNotFound;
3703 }
3704
3705
3706 int String::Length() const {
3707   i::Handle<i::String> str = Utils::OpenHandle(this);
3708   if (IsDeadCheck(str->GetIsolate(), "v8::String::Length()")) return 0;
3709   return str->length();
3710 }
3711
3712
3713 int String::Utf8Length() const {
3714   i::Handle<i::String> str = Utils::OpenHandle(this);
3715   if (IsDeadCheck(str->GetIsolate(), "v8::String::Utf8Length()")) return 0;
3716   return str->Utf8Length();
3717 }
3718
3719
3720 uint32_t String::Hash() const {
3721   i::Handle<i::String> str = Utils::OpenHandle(this);
3722   if (IsDeadCheck(str->GetIsolate(), "v8::String::Hash()")) return 0;
3723   return str->Hash();
3724 }
3725
3726
3727 String::CompleteHashData String::CompleteHash() const {
3728   i::Handle<i::String> str = Utils::OpenHandle(this);
3729   if (IsDeadCheck(str->GetIsolate(), "v8::String::CompleteHash()")) return CompleteHashData();
3730   CompleteHashData result;
3731   result.length = str->length();
3732   result.hash = str->Hash();
3733   if (str->IsSeqString())
3734       result.symbol_id = i::SeqString::cast(*str)->symbol_id();
3735   return result;
3736 }
3737
3738
3739 uint32_t String::ComputeHash(uint16_t *string, int length) {
3740   return i::HashSequentialString<i::uc16>(string, length) >> i::String::kHashShift;
3741 }
3742
3743
3744 uint32_t String::ComputeHash(char *string, int length) {
3745   return i::HashSequentialString<char>(string, length) >> i::String::kHashShift;
3746 }
3747
3748
3749 uint16_t String::GetCharacter(int index)
3750 {
3751   i::Handle<i::String> str = Utils::OpenHandle(this);
3752   return str->Get(index);
3753 }
3754
3755
3756 bool String::Equals(uint16_t *string, int length) {
3757   i::Handle<i::String> str = Utils::OpenHandle(this);
3758   if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3759   return str->SlowEqualsExternal(string, length);
3760 }
3761
3762
3763 bool String::Equals(char *string, int length)
3764 {
3765   i::Handle<i::String> str = Utils::OpenHandle(this);
3766   if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3767   return str->SlowEqualsExternal(string, length);
3768 }
3769
3770
3771 int String::WriteUtf8(char* buffer,
3772                       int capacity,
3773                       int* nchars_ref,
3774                       int options) const {
3775   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3776   if (IsDeadCheck(isolate, "v8::String::WriteUtf8()")) return 0;
3777   LOG_API(isolate, "String::WriteUtf8");
3778   ENTER_V8(isolate);
3779   i::Handle<i::String> str = Utils::OpenHandle(this);
3780   if (str->IsAsciiRepresentation()) {
3781     int len;
3782     if (capacity == -1) {
3783       capacity = str->length() + 1;
3784       len = str->length();
3785     } else {
3786       len = i::Min(capacity, str->length());
3787     }
3788     i::String::WriteToFlat(*str, buffer, 0, len);
3789     if (nchars_ref != NULL) *nchars_ref = len;
3790     if (!(options & NO_NULL_TERMINATION) && capacity > len) {
3791       buffer[len] = '\0';
3792       return len + 1;
3793     }
3794     return len;
3795   }
3796
3797   i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3798   isolate->string_tracker()->RecordWrite(str);
3799   if (options & HINT_MANY_WRITES_EXPECTED) {
3800     // Flatten the string for efficiency.  This applies whether we are
3801     // using StringInputBuffer or Get(i) to access the characters.
3802     FlattenString(str);
3803   }
3804   write_input_buffer.Reset(0, *str);
3805   int len = str->length();
3806   // Encode the first K - 3 bytes directly into the buffer since we
3807   // know there's room for them.  If no capacity is given we copy all
3808   // of them here.
3809   int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
3810   int i;
3811   int pos = 0;
3812   int nchars = 0;
3813   for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
3814     i::uc32 c = write_input_buffer.GetNext();
3815     int written = unibrow::Utf8::Encode(buffer + pos, c);
3816     pos += written;
3817     nchars++;
3818   }
3819   if (i < len) {
3820     // For the last characters we need to check the length for each one
3821     // because they may be longer than the remaining space in the
3822     // buffer.
3823     char intermediate[unibrow::Utf8::kMaxEncodedSize];
3824     for (; i < len && pos < capacity; i++) {
3825       i::uc32 c = write_input_buffer.GetNext();
3826       int written = unibrow::Utf8::Encode(intermediate, c);
3827       if (pos + written <= capacity) {
3828         for (int j = 0; j < written; j++)
3829           buffer[pos + j] = intermediate[j];
3830         pos += written;
3831         nchars++;
3832       } else {
3833         // We've reached the end of the buffer
3834         break;
3835       }
3836     }
3837   }
3838   if (nchars_ref != NULL) *nchars_ref = nchars;
3839   if (!(options & NO_NULL_TERMINATION) &&
3840       (i == len && (capacity == -1 || pos < capacity)))
3841     buffer[pos++] = '\0';
3842   return pos;
3843 }
3844
3845
3846 int String::WriteAscii(char* buffer,
3847                        int start,
3848                        int length,
3849                        int options) const {
3850   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3851   if (IsDeadCheck(isolate, "v8::String::WriteAscii()")) return 0;
3852   LOG_API(isolate, "String::WriteAscii");
3853   ENTER_V8(isolate);
3854   i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3855   ASSERT(start >= 0 && length >= -1);
3856   i::Handle<i::String> str = Utils::OpenHandle(this);
3857   isolate->string_tracker()->RecordWrite(str);
3858   if (options & HINT_MANY_WRITES_EXPECTED) {
3859     // Flatten the string for efficiency.  This applies whether we are
3860     // using StringInputBuffer or Get(i) to access the characters.
3861     str->TryFlatten();
3862   }
3863   int end = length;
3864   if ( (length == -1) || (length > str->length() - start) )
3865     end = str->length() - start;
3866   if (end < 0) return 0;
3867   write_input_buffer.Reset(start, *str);
3868   int i;
3869   for (i = 0; i < end; i++) {
3870     char c = static_cast<char>(write_input_buffer.GetNext());
3871     if (c == '\0') c = ' ';
3872     buffer[i] = c;
3873   }
3874   if (!(options & NO_NULL_TERMINATION) && (length == -1 || i < length))
3875     buffer[i] = '\0';
3876   return i;
3877 }
3878
3879
3880 int String::Write(uint16_t* buffer,
3881                   int start,
3882                   int length,
3883                   int options) const {
3884   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3885   if (IsDeadCheck(isolate, "v8::String::Write()")) return 0;
3886   LOG_API(isolate, "String::Write");
3887   ENTER_V8(isolate);
3888   ASSERT(start >= 0 && length >= -1);
3889   i::Handle<i::String> str = Utils::OpenHandle(this);
3890   isolate->string_tracker()->RecordWrite(str);
3891   if (options & HINT_MANY_WRITES_EXPECTED) {
3892     // Flatten the string for efficiency.  This applies whether we are
3893     // using StringInputBuffer or Get(i) to access the characters.
3894     str->TryFlatten();
3895   }
3896   int end = start + length;
3897   if ((length == -1) || (length > str->length() - start) )
3898     end = str->length();
3899   if (end < 0) return 0;
3900   i::String::WriteToFlat(*str, buffer, start, end);
3901   if (!(options & NO_NULL_TERMINATION) &&
3902       (length == -1 || end - start < length)) {
3903     buffer[end - start] = '\0';
3904   }
3905   return end - start;
3906 }
3907
3908
3909 bool v8::String::IsExternal() const {
3910   i::Handle<i::String> str = Utils::OpenHandle(this);
3911   if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternal()")) {
3912     return false;
3913   }
3914   EnsureInitializedForIsolate(str->GetIsolate(), "v8::String::IsExternal()");
3915   return i::StringShape(*str).IsExternalTwoByte();
3916 }
3917
3918
3919 bool v8::String::IsExternalAscii() const {
3920   i::Handle<i::String> str = Utils::OpenHandle(this);
3921   if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternalAscii()")) {
3922     return false;
3923   }
3924   return i::StringShape(*str).IsExternalAscii();
3925 }
3926
3927
3928 void v8::String::VerifyExternalStringResource(
3929     v8::String::ExternalStringResource* value) const {
3930   i::Handle<i::String> str = Utils::OpenHandle(this);
3931   const v8::String::ExternalStringResource* expected;
3932   if (i::StringShape(*str).IsExternalTwoByte()) {
3933     const void* resource =
3934         i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
3935     expected = reinterpret_cast<const ExternalStringResource*>(resource);
3936   } else {
3937     expected = NULL;
3938   }
3939   CHECK_EQ(expected, value);
3940 }
3941
3942
3943 const v8::String::ExternalAsciiStringResource*
3944       v8::String::GetExternalAsciiStringResource() const {
3945   i::Handle<i::String> str = Utils::OpenHandle(this);
3946   if (IsDeadCheck(str->GetIsolate(),
3947                   "v8::String::GetExternalAsciiStringResource()")) {
3948     return NULL;
3949   }
3950   if (i::StringShape(*str).IsExternalAscii()) {
3951     const void* resource =
3952         i::Handle<i::ExternalAsciiString>::cast(str)->resource();
3953     return reinterpret_cast<const ExternalAsciiStringResource*>(resource);
3954   } else {
3955     return NULL;
3956   }
3957 }
3958
3959
3960 double Number::Value() const {
3961   if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Value()")) return 0;
3962   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3963   return obj->Number();
3964 }
3965
3966
3967 bool Boolean::Value() const {
3968   if (IsDeadCheck(i::Isolate::Current(), "v8::Boolean::Value()")) return false;
3969   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3970   return obj->IsTrue();
3971 }
3972
3973
3974 int64_t Integer::Value() const {
3975   if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Value()")) return 0;
3976   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3977   if (obj->IsSmi()) {
3978     return i::Smi::cast(*obj)->value();
3979   } else {
3980     return static_cast<int64_t>(obj->Number());
3981   }
3982 }
3983
3984
3985 int32_t Int32::Value() const {
3986   if (IsDeadCheck(i::Isolate::Current(), "v8::Int32::Value()")) return 0;
3987   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3988   if (obj->IsSmi()) {
3989     return i::Smi::cast(*obj)->value();
3990   } else {
3991     return static_cast<int32_t>(obj->Number());
3992   }
3993 }
3994
3995
3996 uint32_t Uint32::Value() const {
3997   if (IsDeadCheck(i::Isolate::Current(), "v8::Uint32::Value()")) return 0;
3998   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3999   if (obj->IsSmi()) {
4000     return i::Smi::cast(*obj)->value();
4001   } else {
4002     return static_cast<uint32_t>(obj->Number());
4003   }
4004 }
4005
4006
4007 int v8::Object::InternalFieldCount() {
4008   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4009   if (IsDeadCheck(obj->GetIsolate(), "v8::Object::InternalFieldCount()")) {
4010     return 0;
4011   }
4012   return obj->GetInternalFieldCount();
4013 }
4014
4015
4016 Local<Value> v8::Object::CheckedGetInternalField(int index) {
4017   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4018   if (IsDeadCheck(obj->GetIsolate(), "v8::Object::GetInternalField()")) {
4019     return Local<Value>();
4020   }
4021   if (!ApiCheck(index < obj->GetInternalFieldCount(),
4022                 "v8::Object::GetInternalField()",
4023                 "Reading internal field out of bounds")) {
4024     return Local<Value>();
4025   }
4026   i::Handle<i::Object> value(obj->GetInternalField(index));
4027   Local<Value> result = Utils::ToLocal(value);
4028 #ifdef DEBUG
4029   Local<Value> unchecked = UncheckedGetInternalField(index);
4030   ASSERT(unchecked.IsEmpty() || (unchecked == result));
4031 #endif
4032   return result;
4033 }
4034
4035
4036 void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
4037   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4038   i::Isolate* isolate = obj->GetIsolate();
4039   if (IsDeadCheck(isolate, "v8::Object::SetInternalField()")) {
4040     return;
4041   }
4042   if (!ApiCheck(index < obj->GetInternalFieldCount(),
4043                 "v8::Object::SetInternalField()",
4044                 "Writing internal field out of bounds")) {
4045     return;
4046   }
4047   ENTER_V8(isolate);
4048   i::Handle<i::Object> val = Utils::OpenHandle(*value);
4049   obj->SetInternalField(index, *val);
4050 }
4051
4052
4053 static bool CanBeEncodedAsSmi(void* ptr) {
4054   const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4055   return ((address & i::kEncodablePointerMask) == 0);
4056 }
4057
4058
4059 static i::Smi* EncodeAsSmi(void* ptr) {
4060   ASSERT(CanBeEncodedAsSmi(ptr));
4061   const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4062   i::Smi* result = reinterpret_cast<i::Smi*>(address << i::kPointerToSmiShift);
4063   ASSERT(i::Internals::HasSmiTag(result));
4064   ASSERT_EQ(result, i::Smi::FromInt(result->value()));
4065   ASSERT_EQ(ptr, i::Internals::GetExternalPointerFromSmi(result));
4066   return result;
4067 }
4068
4069
4070 void v8::Object::SetPointerInInternalField(int index, void* value) {
4071   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4072   ENTER_V8(isolate);
4073   if (CanBeEncodedAsSmi(value)) {
4074     Utils::OpenHandle(this)->SetInternalField(index, EncodeAsSmi(value));
4075   } else {
4076     HandleScope scope;
4077     i::Handle<i::Foreign> foreign =
4078         isolate->factory()->NewForeign(
4079             reinterpret_cast<i::Address>(value), i::TENURED);
4080     if (!foreign.is_null())
4081         Utils::OpenHandle(this)->SetInternalField(index, *foreign);
4082   }
4083   ASSERT_EQ(value, GetPointerFromInternalField(index));
4084 }
4085
4086
4087 void v8::Object::SetExternalResource(v8::Object::ExternalResource *resource) {
4088   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4089   ENTER_V8(isolate);
4090   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4091   if (CanBeEncodedAsSmi(resource)) {
4092     obj->SetExternalResourceObject(EncodeAsSmi(resource));
4093   } else {
4094     obj->SetExternalResourceObject(*isolate->factory()->NewForeign(static_cast<i::Address>((void *)resource)));
4095   }
4096   if (!obj->IsSymbol()) {
4097     isolate->heap()->external_string_table()->AddObject(*obj);
4098   }
4099 }
4100
4101
4102 v8::Object::ExternalResource *v8::Object::GetExternalResource() {
4103   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4104   i::Object* value = obj->GetExternalResourceObject();
4105   if (value->IsSmi()) {
4106     return reinterpret_cast<v8::Object::ExternalResource*>(i::Internals::GetExternalPointerFromSmi(value));
4107   } else if (value->IsForeign()) {
4108     return reinterpret_cast<v8::Object::ExternalResource*>(i::Foreign::cast(value)->address());
4109   } else {
4110     return NULL;
4111   }
4112 }
4113
4114
4115 // --- E n v i r o n m e n t ---
4116
4117
4118 bool v8::V8::Initialize() {
4119   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4120   if (isolate != NULL && isolate->IsInitialized()) {
4121     return true;
4122   }
4123   return InitializeHelper();
4124 }
4125
4126
4127 void v8::V8::SetEntropySource(EntropySource source) {
4128   i::V8::SetEntropySource(source);
4129 }
4130
4131
4132 bool v8::V8::Dispose() {
4133   i::Isolate* isolate = i::Isolate::Current();
4134   if (!ApiCheck(isolate != NULL && isolate->IsDefaultIsolate(),
4135                 "v8::V8::Dispose()",
4136                 "Use v8::Isolate::Dispose() for a non-default isolate.")) {
4137     return false;
4138   }
4139   i::V8::TearDown();
4140   return true;
4141 }
4142
4143
4144 HeapStatistics::HeapStatistics(): total_heap_size_(0),
4145                                   total_heap_size_executable_(0),
4146                                   used_heap_size_(0),
4147                                   heap_size_limit_(0) { }
4148
4149
4150 void v8::V8::GetHeapStatistics(HeapStatistics* heap_statistics) {
4151   if (!i::Isolate::Current()->IsInitialized()) {
4152     // Isolate is unitialized thus heap is not configured yet.
4153     heap_statistics->set_total_heap_size(0);
4154     heap_statistics->set_total_heap_size_executable(0);
4155     heap_statistics->set_used_heap_size(0);
4156     heap_statistics->set_heap_size_limit(0);
4157     return;
4158   }
4159
4160   i::Heap* heap = i::Isolate::Current()->heap();
4161   heap_statistics->set_total_heap_size(heap->CommittedMemory());
4162   heap_statistics->set_total_heap_size_executable(
4163       heap->CommittedMemoryExecutable());
4164   heap_statistics->set_used_heap_size(heap->SizeOfObjects());
4165   heap_statistics->set_heap_size_limit(heap->MaxReserved());
4166 }
4167
4168
4169 bool v8::V8::IdleNotification() {
4170   // Returning true tells the caller that it need not
4171   // continue to call IdleNotification.
4172   i::Isolate* isolate = i::Isolate::Current();
4173   if (isolate == NULL || !isolate->IsInitialized()) return true;
4174   return i::V8::IdleNotification();
4175 }
4176
4177
4178 void v8::V8::LowMemoryNotification() {
4179   i::Isolate* isolate = i::Isolate::Current();
4180   if (isolate == NULL || !isolate->IsInitialized()) return;
4181   isolate->heap()->CollectAllAvailableGarbage();
4182 }
4183
4184
4185 int v8::V8::ContextDisposedNotification() {
4186   i::Isolate* isolate = i::Isolate::Current();
4187   if (!isolate->IsInitialized()) return 0;
4188   return isolate->heap()->NotifyContextDisposed();
4189 }
4190
4191
4192 const char* v8::V8::GetVersion() {
4193   return i::Version::GetVersion();
4194 }
4195
4196
4197 static i::Handle<i::FunctionTemplateInfo>
4198     EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
4199   if (templ->constructor()->IsUndefined()) {
4200     Local<FunctionTemplate> constructor = FunctionTemplate::New();
4201     Utils::OpenHandle(*constructor)->set_instance_template(*templ);
4202     templ->set_constructor(*Utils::OpenHandle(*constructor));
4203   }
4204   return i::Handle<i::FunctionTemplateInfo>(
4205     i::FunctionTemplateInfo::cast(templ->constructor()));
4206 }
4207
4208
4209 Persistent<Context> v8::Context::New(
4210     v8::ExtensionConfiguration* extensions,
4211     v8::Handle<ObjectTemplate> global_template,
4212     v8::Handle<Value> global_object) {
4213   i::Isolate* isolate = i::Isolate::Current();
4214   EnsureInitializedForIsolate(isolate, "v8::Context::New()");
4215   LOG_API(isolate, "Context::New");
4216   ON_BAILOUT(isolate, "v8::Context::New()", return Persistent<Context>());
4217
4218   // Enter V8 via an ENTER_V8 scope.
4219   i::Handle<i::Context> env;
4220   {
4221     ENTER_V8(isolate);
4222     v8::Handle<ObjectTemplate> proxy_template = global_template;
4223     i::Handle<i::FunctionTemplateInfo> proxy_constructor;
4224     i::Handle<i::FunctionTemplateInfo> global_constructor;
4225
4226     if (!global_template.IsEmpty()) {
4227       // Make sure that the global_template has a constructor.
4228       global_constructor =
4229           EnsureConstructor(Utils::OpenHandle(*global_template));
4230
4231       // Create a fresh template for the global proxy object.
4232       proxy_template = ObjectTemplate::New();
4233       proxy_constructor =
4234           EnsureConstructor(Utils::OpenHandle(*proxy_template));
4235
4236       // Set the global template to be the prototype template of
4237       // global proxy template.
4238       proxy_constructor->set_prototype_template(
4239           *Utils::OpenHandle(*global_template));
4240
4241       // Migrate security handlers from global_template to
4242       // proxy_template.  Temporarily removing access check
4243       // information from the global template.
4244       if (!global_constructor->access_check_info()->IsUndefined()) {
4245         proxy_constructor->set_access_check_info(
4246             global_constructor->access_check_info());
4247         proxy_constructor->set_needs_access_check(
4248             global_constructor->needs_access_check());
4249         global_constructor->set_needs_access_check(false);
4250         global_constructor->set_access_check_info(
4251             isolate->heap()->undefined_value());
4252       }
4253     }
4254
4255     // Create the environment.
4256     env = isolate->bootstrapper()->CreateEnvironment(
4257         isolate,
4258         Utils::OpenHandle(*global_object),
4259         proxy_template,
4260         extensions);
4261
4262     // Restore the access check info on the global template.
4263     if (!global_template.IsEmpty()) {
4264       ASSERT(!global_constructor.is_null());
4265       ASSERT(!proxy_constructor.is_null());
4266       global_constructor->set_access_check_info(
4267           proxy_constructor->access_check_info());
4268       global_constructor->set_needs_access_check(
4269           proxy_constructor->needs_access_check());
4270     }
4271     isolate->runtime_profiler()->Reset();
4272   }
4273   // Leave V8.
4274
4275   if (env.is_null()) {
4276     return Persistent<Context>();
4277   }
4278   return Persistent<Context>(Utils::ToLocal(env));
4279 }
4280
4281
4282 void v8::Context::SetSecurityToken(Handle<Value> token) {
4283   i::Isolate* isolate = i::Isolate::Current();
4284   if (IsDeadCheck(isolate, "v8::Context::SetSecurityToken()")) {
4285     return;
4286   }
4287   ENTER_V8(isolate);
4288   i::Handle<i::Context> env = Utils::OpenHandle(this);
4289   i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
4290   env->set_security_token(*token_handle);
4291 }
4292
4293
4294 void v8::Context::UseDefaultSecurityToken() {
4295   i::Isolate* isolate = i::Isolate::Current();
4296   if (IsDeadCheck(isolate,
4297                   "v8::Context::UseDefaultSecurityToken()")) {
4298     return;
4299   }
4300   ENTER_V8(isolate);
4301   i::Handle<i::Context> env = Utils::OpenHandle(this);
4302   env->set_security_token(env->global());
4303 }
4304
4305
4306 Handle<Value> v8::Context::GetSecurityToken() {
4307   i::Isolate* isolate = i::Isolate::Current();
4308   if (IsDeadCheck(isolate, "v8::Context::GetSecurityToken()")) {
4309     return Handle<Value>();
4310   }
4311   i::Handle<i::Context> env = Utils::OpenHandle(this);
4312   i::Object* security_token = env->security_token();
4313   i::Handle<i::Object> token_handle(security_token);
4314   return Utils::ToLocal(token_handle);
4315 }
4316
4317
4318 bool Context::HasOutOfMemoryException() {
4319   i::Handle<i::Context> env = Utils::OpenHandle(this);
4320   return env->has_out_of_memory();
4321 }
4322
4323
4324 bool Context::InContext() {
4325   return i::Isolate::Current()->context() != NULL;
4326 }
4327
4328
4329 v8::Local<v8::Context> Context::GetEntered() {
4330   i::Isolate* isolate = i::Isolate::Current();
4331   if (!EnsureInitializedForIsolate(isolate, "v8::Context::GetEntered()")) {
4332     return Local<Context>();
4333   }
4334   i::Handle<i::Object> last =
4335       isolate->handle_scope_implementer()->LastEnteredContext();
4336   if (last.is_null()) return Local<Context>();
4337   i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
4338   return Utils::ToLocal(context);
4339 }
4340
4341
4342 v8::Local<v8::Context> Context::GetCurrent() {
4343   i::Isolate* isolate = i::Isolate::Current();
4344   if (IsDeadCheck(isolate, "v8::Context::GetCurrent()")) {
4345     return Local<Context>();
4346   }
4347   i::Handle<i::Object> current = isolate->global_context();
4348   if (current.is_null()) return Local<Context>();
4349   i::Handle<i::Context> context = i::Handle<i::Context>::cast(current);
4350   return Utils::ToLocal(context);
4351 }
4352
4353
4354 v8::Local<v8::Context> Context::GetCalling() {
4355   i::Isolate* isolate = i::Isolate::Current();
4356   if (IsDeadCheck(isolate, "v8::Context::GetCalling()")) {
4357     return Local<Context>();
4358   }
4359   i::Handle<i::Object> calling =
4360       isolate->GetCallingGlobalContext();
4361   if (calling.is_null()) return Local<Context>();
4362   i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
4363   return Utils::ToLocal(context);
4364 }
4365
4366
4367 v8::Local<v8::Object> Context::GetCallingQmlGlobal() {
4368   i::Isolate* isolate = i::Isolate::Current();
4369   if (IsDeadCheck(isolate, "v8::Context::GetCallingQmlGlobal()")) {
4370     return Local<Object>();
4371   }
4372
4373   i::Context *context = isolate->context();
4374   if (!context->qml_global()->IsUndefined()) {
4375     i::Handle<i::Object> qmlglobal(context->qml_global());
4376     return Utils::ToLocal(i::Handle<i::JSObject>::cast(qmlglobal));
4377   }
4378
4379   i::JavaScriptFrameIterator it;
4380   if (it.done()) return Local<Object>();
4381   context = i::Context::cast(it.frame()->context());
4382   if (!context->qml_global()->IsUndefined()) {
4383     i::Handle<i::Object> qmlglobal(context->qml_global());
4384     return Utils::ToLocal(i::Handle<i::JSObject>::cast(qmlglobal));
4385   } else {
4386       return Local<Object>();
4387   }
4388 }
4389
4390 v8::Local<v8::Value> Context::GetCallingScriptData()
4391 {
4392   i::Isolate* isolate = i::Isolate::Current();
4393   if (IsDeadCheck(isolate, "v8::Context::GetCallingScriptData()")) {
4394     return Local<Object>();
4395   }
4396
4397   i::JavaScriptFrameIterator it;
4398   if (it.done()) return Local<Object>();
4399   i::Handle<i::Script> script(i::Script::cast(i::JSFunction::cast(it.frame()->function())->shared()->script()));
4400   return Utils::ToLocal(i::Handle<i::Object>(script->data()));
4401 }
4402
4403 v8::Local<v8::Object> Context::Global() {
4404   if (IsDeadCheck(i::Isolate::Current(), "v8::Context::Global()")) {
4405     return Local<v8::Object>();
4406   }
4407   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4408   i::Handle<i::Context> context =
4409       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4410   i::Handle<i::Object> global(context->global_proxy());
4411   return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
4412 }
4413
4414
4415 void Context::DetachGlobal() {
4416   i::Isolate* isolate = i::Isolate::Current();
4417   if (IsDeadCheck(isolate, "v8::Context::DetachGlobal()")) return;
4418   ENTER_V8(isolate);
4419   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4420   i::Handle<i::Context> context =
4421       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4422   isolate->bootstrapper()->DetachGlobal(context);
4423 }
4424
4425
4426 void Context::ReattachGlobal(Handle<Object> global_object) {
4427   i::Isolate* isolate = i::Isolate::Current();
4428   if (IsDeadCheck(isolate, "v8::Context::ReattachGlobal()")) return;
4429   ENTER_V8(isolate);
4430   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4431   i::Handle<i::Context> context =
4432       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4433   isolate->bootstrapper()->ReattachGlobal(
4434       context,
4435       Utils::OpenHandle(*global_object));
4436 }
4437
4438
4439 void Context::AllowCodeGenerationFromStrings(bool allow) {
4440   i::Isolate* isolate = i::Isolate::Current();
4441   if (IsDeadCheck(isolate, "v8::Context::AllowCodeGenerationFromStrings()")) {
4442     return;
4443   }
4444   ENTER_V8(isolate);
4445   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4446   i::Handle<i::Context> context =
4447       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4448   context->set_allow_code_gen_from_strings(
4449       allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
4450 }
4451
4452
4453 void V8::SetWrapperClassId(i::Object** global_handle, uint16_t class_id) {
4454   i::GlobalHandles::SetWrapperClassId(global_handle, class_id);
4455 }
4456
4457
4458 Local<v8::Object> ObjectTemplate::NewInstance() {
4459   i::Isolate* isolate = i::Isolate::Current();
4460   ON_BAILOUT(isolate, "v8::ObjectTemplate::NewInstance()",
4461              return Local<v8::Object>());
4462   LOG_API(isolate, "ObjectTemplate::NewInstance");
4463   ENTER_V8(isolate);
4464   EXCEPTION_PREAMBLE(isolate);
4465   i::Handle<i::Object> obj =
4466       i::Execution::InstantiateObject(Utils::OpenHandle(this),
4467                                       &has_pending_exception);
4468   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
4469   return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
4470 }
4471
4472
4473 Local<v8::Function> FunctionTemplate::GetFunction() {
4474   i::Isolate* isolate = i::Isolate::Current();
4475   ON_BAILOUT(isolate, "v8::FunctionTemplate::GetFunction()",
4476              return Local<v8::Function>());
4477   LOG_API(isolate, "FunctionTemplate::GetFunction");
4478   ENTER_V8(isolate);
4479   EXCEPTION_PREAMBLE(isolate);
4480   i::Handle<i::Object> obj =
4481       i::Execution::InstantiateFunction(Utils::OpenHandle(this),
4482                                         &has_pending_exception);
4483   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Function>());
4484   return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
4485 }
4486
4487
4488 bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
4489   ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
4490              return false);
4491   i::Object* obj = *Utils::OpenHandle(*value);
4492   return obj->IsInstanceOf(*Utils::OpenHandle(this));
4493 }
4494
4495
4496 static Local<External> ExternalNewImpl(void* data) {
4497   return Utils::ToLocal(FACTORY->NewForeign(static_cast<i::Address>(data)));
4498 }
4499
4500 static void* ExternalValueImpl(i::Handle<i::Object> obj) {
4501   return reinterpret_cast<void*>(i::Foreign::cast(*obj)->address());
4502 }
4503
4504
4505 Local<Value> v8::External::Wrap(void* data) {
4506   i::Isolate* isolate = i::Isolate::Current();
4507   STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4508   EnsureInitializedForIsolate(isolate, "v8::External::Wrap()");
4509   LOG_API(isolate, "External::Wrap");
4510   ENTER_V8(isolate);
4511
4512   v8::Local<v8::Value> result = CanBeEncodedAsSmi(data)
4513       ? Utils::ToLocal(i::Handle<i::Object>(EncodeAsSmi(data)))
4514       : v8::Local<v8::Value>(ExternalNewImpl(data));
4515
4516   ASSERT_EQ(data, Unwrap(result));
4517   return result;
4518 }
4519
4520
4521 void* v8::Object::SlowGetPointerFromInternalField(int index) {
4522   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4523   i::Object* value = obj->GetInternalField(index);
4524   if (value->IsSmi()) {
4525     return i::Internals::GetExternalPointerFromSmi(value);
4526   } else if (value->IsForeign()) {
4527     return reinterpret_cast<void*>(i::Foreign::cast(value)->address());
4528   } else {
4529     return NULL;
4530   }
4531 }
4532
4533
4534 void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
4535   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Unwrap()")) return 0;
4536   i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
4537   void* result;
4538   if (obj->IsSmi()) {
4539     result = i::Internals::GetExternalPointerFromSmi(*obj);
4540   } else if (obj->IsForeign()) {
4541     result = ExternalValueImpl(obj);
4542   } else {
4543     result = NULL;
4544   }
4545   ASSERT_EQ(result, QuickUnwrap(wrapper));
4546   return result;
4547 }
4548
4549
4550 Local<External> v8::External::New(void* data) {
4551   STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4552   i::Isolate* isolate = i::Isolate::Current();
4553   EnsureInitializedForIsolate(isolate, "v8::External::New()");
4554   LOG_API(isolate, "External::New");
4555   ENTER_V8(isolate);
4556   return ExternalNewImpl(data);
4557 }
4558
4559
4560 void* External::Value() const {
4561   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Value()")) return 0;
4562   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4563   return ExternalValueImpl(obj);
4564 }
4565
4566
4567 Local<String> v8::String::Empty() {
4568   i::Isolate* isolate = i::Isolate::Current();
4569   EnsureInitializedForIsolate(isolate, "v8::String::Empty()");
4570   LOG_API(isolate, "String::Empty()");
4571   return Utils::ToLocal(isolate->factory()->empty_symbol());
4572 }
4573
4574
4575 Local<String> v8::String::New(const char* data, int length) {
4576   i::Isolate* isolate = i::Isolate::Current();
4577   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4578   LOG_API(isolate, "String::New(char)");
4579   if (length == 0) return Empty();
4580   ENTER_V8(isolate);
4581   if (length == -1) length = i::StrLength(data);
4582   i::Handle<i::String> result =
4583       isolate->factory()->NewStringFromUtf8(
4584           i::Vector<const char>(data, length));
4585   return Utils::ToLocal(result);
4586 }
4587
4588
4589 Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
4590   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
4591   i::Isolate* isolate = left_string->GetIsolate();
4592   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4593   LOG_API(isolate, "String::New(char)");
4594   ENTER_V8(isolate);
4595   i::Handle<i::String> right_string = Utils::OpenHandle(*right);
4596   i::Handle<i::String> result = isolate->factory()->NewConsString(left_string,
4597                                                                   right_string);
4598   return Utils::ToLocal(result);
4599 }
4600
4601
4602 Local<String> v8::String::NewUndetectable(const char* data, int length) {
4603   i::Isolate* isolate = i::Isolate::Current();
4604   EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4605   LOG_API(isolate, "String::NewUndetectable(char)");
4606   ENTER_V8(isolate);
4607   if (length == -1) length = i::StrLength(data);
4608   i::Handle<i::String> result =
4609       isolate->factory()->NewStringFromUtf8(
4610           i::Vector<const char>(data, length));
4611   result->MarkAsUndetectable();
4612   return Utils::ToLocal(result);
4613 }
4614
4615
4616 static int TwoByteStringLength(const uint16_t* data) {
4617   int length = 0;
4618   while (data[length] != '\0') length++;
4619   return length;
4620 }
4621
4622
4623 Local<String> v8::String::New(const uint16_t* data, int length) {
4624   i::Isolate* isolate = i::Isolate::Current();
4625   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4626   LOG_API(isolate, "String::New(uint16_)");
4627   if (length == 0) return Empty();
4628   ENTER_V8(isolate);
4629   if (length == -1) length = TwoByteStringLength(data);
4630   i::Handle<i::String> result =
4631       isolate->factory()->NewStringFromTwoByte(
4632           i::Vector<const uint16_t>(data, length));
4633   return Utils::ToLocal(result);
4634 }
4635
4636
4637 Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
4638   i::Isolate* isolate = i::Isolate::Current();
4639   EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4640   LOG_API(isolate, "String::NewUndetectable(uint16_)");
4641   ENTER_V8(isolate);
4642   if (length == -1) length = TwoByteStringLength(data);
4643   i::Handle<i::String> result =
4644       isolate->factory()->NewStringFromTwoByte(
4645           i::Vector<const uint16_t>(data, length));
4646   result->MarkAsUndetectable();
4647   return Utils::ToLocal(result);
4648 }
4649
4650
4651 i::Handle<i::String> NewExternalStringHandle(i::Isolate* isolate,
4652       v8::String::ExternalStringResource* resource) {
4653   i::Handle<i::String> result =
4654       isolate->factory()->NewExternalStringFromTwoByte(resource);
4655   return result;
4656 }
4657
4658
4659 i::Handle<i::String> NewExternalAsciiStringHandle(i::Isolate* isolate,
4660       v8::String::ExternalAsciiStringResource* resource) {
4661   i::Handle<i::String> result =
4662       isolate->factory()->NewExternalStringFromAscii(resource);
4663   return result;
4664 }
4665
4666
4667 Local<String> v8::String::NewExternal(
4668       v8::String::ExternalStringResource* resource) {
4669   i::Isolate* isolate = i::Isolate::Current();
4670   EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4671   LOG_API(isolate, "String::NewExternal");
4672   ENTER_V8(isolate);
4673   i::Handle<i::String> result = NewExternalStringHandle(isolate, resource);
4674   isolate->heap()->external_string_table()->AddString(*result);
4675   return Utils::ToLocal(result);
4676 }
4677
4678
4679 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
4680   i::Handle<i::String> obj = Utils::OpenHandle(this);
4681   i::Isolate* isolate = obj->GetIsolate();
4682   if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4683   if (i::StringShape(*obj).IsExternalTwoByte()) {
4684     return false;  // Already an external string.
4685   }
4686   ENTER_V8(isolate);
4687   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4688     return false;
4689   }
4690   if (isolate->heap()->IsInGCPostProcessing()) {
4691     return false;
4692   }
4693   bool result = obj->MakeExternal(resource);
4694   if (result && !obj->IsSymbol()) {
4695     isolate->heap()->external_string_table()->AddString(*obj);
4696   }
4697   return result;
4698 }
4699
4700
4701 Local<String> v8::String::NewExternal(
4702       v8::String::ExternalAsciiStringResource* resource) {
4703   i::Isolate* isolate = i::Isolate::Current();
4704   EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4705   LOG_API(isolate, "String::NewExternal");
4706   ENTER_V8(isolate);
4707   i::Handle<i::String> result = NewExternalAsciiStringHandle(isolate, resource);
4708   isolate->heap()->external_string_table()->AddString(*result);
4709   return Utils::ToLocal(result);
4710 }
4711
4712
4713 bool v8::String::MakeExternal(
4714     v8::String::ExternalAsciiStringResource* resource) {
4715   i::Handle<i::String> obj = Utils::OpenHandle(this);
4716   i::Isolate* isolate = obj->GetIsolate();
4717   if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4718   if (i::StringShape(*obj).IsExternalTwoByte()) {
4719     return false;  // Already an external string.
4720   }
4721   ENTER_V8(isolate);
4722   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4723     return false;
4724   }
4725   if (isolate->heap()->IsInGCPostProcessing()) {
4726     return false;
4727   }
4728   bool result = obj->MakeExternal(resource);
4729   if (result && !obj->IsSymbol()) {
4730     isolate->heap()->external_string_table()->AddString(*obj);
4731   }
4732   return result;
4733 }
4734
4735
4736 bool v8::String::CanMakeExternal() {
4737   if (!internal::FLAG_clever_optimizations) return false;
4738   i::Handle<i::String> obj = Utils::OpenHandle(this);
4739   i::Isolate* isolate = obj->GetIsolate();
4740   if (IsDeadCheck(isolate, "v8::String::CanMakeExternal()")) return false;
4741   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4742     return false;
4743   }
4744   int size = obj->Size();  // Byte size of the original string.
4745   if (size < i::ExternalString::kSize)
4746     return false;
4747   i::StringShape shape(*obj);
4748   return !shape.IsExternal();
4749 }
4750
4751
4752 Local<v8::Object> v8::Object::New() {
4753   i::Isolate* isolate = i::Isolate::Current();
4754   EnsureInitializedForIsolate(isolate, "v8::Object::New()");
4755   LOG_API(isolate, "Object::New");
4756   ENTER_V8(isolate);
4757   i::Handle<i::JSObject> obj =
4758       isolate->factory()->NewJSObject(isolate->object_function());
4759   return Utils::ToLocal(obj);
4760 }
4761
4762
4763 Local<v8::Value> v8::NumberObject::New(double value) {
4764   i::Isolate* isolate = i::Isolate::Current();
4765   EnsureInitializedForIsolate(isolate, "v8::NumberObject::New()");
4766   LOG_API(isolate, "NumberObject::New");
4767   ENTER_V8(isolate);
4768   i::Handle<i::Object> number = isolate->factory()->NewNumber(value);
4769   i::Handle<i::Object> obj = isolate->factory()->ToObject(number);
4770   return Utils::ToLocal(obj);
4771 }
4772
4773
4774 double v8::NumberObject::NumberValue() const {
4775   i::Isolate* isolate = i::Isolate::Current();
4776   if (IsDeadCheck(isolate, "v8::NumberObject::NumberValue()")) return 0;
4777   LOG_API(isolate, "NumberObject::NumberValue");
4778   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4779   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4780   return jsvalue->value()->Number();
4781 }
4782
4783
4784 Local<v8::Value> v8::BooleanObject::New(bool value) {
4785   i::Isolate* isolate = i::Isolate::Current();
4786   EnsureInitializedForIsolate(isolate, "v8::BooleanObject::New()");
4787   LOG_API(isolate, "BooleanObject::New");
4788   ENTER_V8(isolate);
4789   i::Handle<i::Object> boolean(value ? isolate->heap()->true_value()
4790                                      : isolate->heap()->false_value());
4791   i::Handle<i::Object> obj = isolate->factory()->ToObject(boolean);
4792   return Utils::ToLocal(obj);
4793 }
4794
4795
4796 bool v8::BooleanObject::BooleanValue() const {
4797   i::Isolate* isolate = i::Isolate::Current();
4798   if (IsDeadCheck(isolate, "v8::BooleanObject::BooleanValue()")) return 0;
4799   LOG_API(isolate, "BooleanObject::BooleanValue");
4800   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4801   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4802   return jsvalue->value()->IsTrue();
4803 }
4804
4805
4806 Local<v8::Value> v8::StringObject::New(Handle<String> value) {
4807   i::Isolate* isolate = i::Isolate::Current();
4808   EnsureInitializedForIsolate(isolate, "v8::StringObject::New()");
4809   LOG_API(isolate, "StringObject::New");
4810   ENTER_V8(isolate);
4811   i::Handle<i::Object> obj =
4812       isolate->factory()->ToObject(Utils::OpenHandle(*value));
4813   return Utils::ToLocal(obj);
4814 }
4815
4816
4817 Local<v8::String> v8::StringObject::StringValue() const {
4818   i::Isolate* isolate = i::Isolate::Current();
4819   if (IsDeadCheck(isolate, "v8::StringObject::StringValue()")) {
4820     return Local<v8::String>();
4821   }
4822   LOG_API(isolate, "StringObject::StringValue");
4823   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4824   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4825   return Utils::ToLocal(
4826       i::Handle<i::String>(i::String::cast(jsvalue->value())));
4827 }
4828
4829
4830 Local<v8::Value> v8::Date::New(double time) {
4831   i::Isolate* isolate = i::Isolate::Current();
4832   EnsureInitializedForIsolate(isolate, "v8::Date::New()");
4833   LOG_API(isolate, "Date::New");
4834   if (isnan(time)) {
4835     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4836     time = i::OS::nan_value();
4837   }
4838   ENTER_V8(isolate);
4839   EXCEPTION_PREAMBLE(isolate);
4840   i::Handle<i::Object> obj =
4841       i::Execution::NewDate(time, &has_pending_exception);
4842   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Value>());
4843   return Utils::ToLocal(obj);
4844 }
4845
4846
4847 double v8::Date::NumberValue() const {
4848   i::Isolate* isolate = i::Isolate::Current();
4849   if (IsDeadCheck(isolate, "v8::Date::NumberValue()")) return 0;
4850   LOG_API(isolate, "Date::NumberValue");
4851   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4852   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4853   return jsvalue->value()->Number();
4854 }
4855
4856
4857 void v8::Date::DateTimeConfigurationChangeNotification() {
4858   i::Isolate* isolate = i::Isolate::Current();
4859   ON_BAILOUT(isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
4860              return);
4861   LOG_API(isolate, "Date::DateTimeConfigurationChangeNotification");
4862   ENTER_V8(isolate);
4863
4864   i::HandleScope scope(isolate);
4865   // Get the function ResetDateCache (defined in date-delay.js).
4866   i::Handle<i::String> func_name_str =
4867       isolate->factory()->LookupAsciiSymbol("ResetDateCache");
4868   i::MaybeObject* result =
4869       isolate->js_builtins_object()->GetProperty(*func_name_str);
4870   i::Object* object_func;
4871   if (!result->ToObject(&object_func)) {
4872     return;
4873   }
4874
4875   if (object_func->IsJSFunction()) {
4876     i::Handle<i::JSFunction> func =
4877         i::Handle<i::JSFunction>(i::JSFunction::cast(object_func));
4878
4879     // Call ResetDateCache(0 but expect no exceptions:
4880     bool caught_exception = false;
4881     i::Execution::TryCall(func,
4882                           isolate->js_builtins_object(),
4883                           0,
4884                           NULL,
4885                           &caught_exception);
4886   }
4887 }
4888
4889
4890 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
4891   char flags_buf[3];
4892   int num_flags = 0;
4893   if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
4894   if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
4895   if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
4896   ASSERT(num_flags <= static_cast<int>(ARRAY_SIZE(flags_buf)));
4897   return FACTORY->LookupSymbol(
4898       i::Vector<const char>(flags_buf, num_flags));
4899 }
4900
4901
4902 Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
4903                                   Flags flags) {
4904   i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
4905   EnsureInitializedForIsolate(isolate, "v8::RegExp::New()");
4906   LOG_API(isolate, "RegExp::New");
4907   ENTER_V8(isolate);
4908   EXCEPTION_PREAMBLE(isolate);
4909   i::Handle<i::JSRegExp> obj = i::Execution::NewJSRegExp(
4910       Utils::OpenHandle(*pattern),
4911       RegExpFlagsToString(flags),
4912       &has_pending_exception);
4913   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::RegExp>());
4914   return Utils::ToLocal(i::Handle<i::JSRegExp>::cast(obj));
4915 }
4916
4917
4918 Local<v8::String> v8::RegExp::GetSource() const {
4919   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4920   if (IsDeadCheck(isolate, "v8::RegExp::GetSource()")) {
4921     return Local<v8::String>();
4922   }
4923   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4924   return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
4925 }
4926
4927
4928 // Assert that the static flags cast in GetFlags is valid.
4929 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag)        \
4930   STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) ==     \
4931                 static_cast<int>(i::JSRegExp::internal_flag))
4932 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
4933 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
4934 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
4935 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
4936 #undef REGEXP_FLAG_ASSERT_EQ
4937
4938 v8::RegExp::Flags v8::RegExp::GetFlags() const {
4939   if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::GetFlags()")) {
4940     return v8::RegExp::kNone;
4941   }
4942   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4943   return static_cast<RegExp::Flags>(obj->GetFlags().value());
4944 }
4945
4946
4947 Local<v8::Array> v8::Array::New(int length) {
4948   i::Isolate* isolate = i::Isolate::Current();
4949   EnsureInitializedForIsolate(isolate, "v8::Array::New()");
4950   LOG_API(isolate, "Array::New");
4951   ENTER_V8(isolate);
4952   int real_length = length > 0 ? length : 0;
4953   i::Handle<i::JSArray> obj = isolate->factory()->NewJSArray(real_length);
4954   i::Handle<i::Object> length_obj =
4955       isolate->factory()->NewNumberFromInt(real_length);
4956   obj->set_length(*length_obj);
4957   return Utils::ToLocal(obj);
4958 }
4959
4960
4961 uint32_t v8::Array::Length() const {
4962   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4963   if (IsDeadCheck(isolate, "v8::Array::Length()")) return 0;
4964   i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
4965   i::Object* length = obj->length();
4966   if (length->IsSmi()) {
4967     return i::Smi::cast(length)->value();
4968   } else {
4969     return static_cast<uint32_t>(length->Number());
4970   }
4971 }
4972
4973
4974 Local<Object> Array::CloneElementAt(uint32_t index) {
4975   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4976   ON_BAILOUT(isolate, "v8::Array::CloneElementAt()", return Local<Object>());
4977   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4978   if (!self->HasFastElements()) {
4979     return Local<Object>();
4980   }
4981   i::FixedArray* elms = i::FixedArray::cast(self->elements());
4982   i::Object* paragon = elms->get(index);
4983   if (!paragon->IsJSObject()) {
4984     return Local<Object>();
4985   }
4986   i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
4987   EXCEPTION_PREAMBLE(isolate);
4988   ENTER_V8(isolate);
4989   i::Handle<i::JSObject> result = i::Copy(paragon_handle);
4990   has_pending_exception = result.is_null();
4991   EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
4992   return Utils::ToLocal(result);
4993 }
4994
4995
4996 Local<String> v8::String::NewSymbol(const char* data, int length) {
4997   i::Isolate* isolate = i::Isolate::Current();
4998   EnsureInitializedForIsolate(isolate, "v8::String::NewSymbol()");
4999   LOG_API(isolate, "String::NewSymbol(char)");
5000   ENTER_V8(isolate);
5001   if (length == -1) length = i::StrLength(data);
5002   i::Handle<i::String> result =
5003       isolate->factory()->LookupSymbol(i::Vector<const char>(data, length));
5004   return Utils::ToLocal(result);
5005 }
5006
5007
5008 Local<Number> v8::Number::New(double value) {
5009   i::Isolate* isolate = i::Isolate::Current();
5010   EnsureInitializedForIsolate(isolate, "v8::Number::New()");
5011   if (isnan(value)) {
5012     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
5013     value = i::OS::nan_value();
5014   }
5015   ENTER_V8(isolate);
5016   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5017   return Utils::NumberToLocal(result);
5018 }
5019
5020
5021 Local<Integer> v8::Integer::New(int32_t value) {
5022   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5023   EnsureInitializedForIsolate(isolate, "v8::Integer::New()");
5024   if (i::Smi::IsValid(value)) {
5025     return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
5026                                                       isolate));
5027   }
5028   ENTER_V8(isolate);
5029   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5030   return Utils::IntegerToLocal(result);
5031 }
5032
5033
5034 Local<Integer> Integer::NewFromUnsigned(uint32_t value) {
5035   bool fits_into_int32_t = (value & (1 << 31)) == 0;
5036   if (fits_into_int32_t) {
5037     return Integer::New(static_cast<int32_t>(value));
5038   }
5039   i::Isolate* isolate = i::Isolate::Current();
5040   ENTER_V8(isolate);
5041   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5042   return Utils::IntegerToLocal(result);
5043 }
5044
5045
5046 void V8::IgnoreOutOfMemoryException() {
5047   EnterIsolateIfNeeded()->set_ignore_out_of_memory(true);
5048 }
5049
5050
5051 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
5052   i::Isolate* isolate = i::Isolate::Current();
5053   EnsureInitializedForIsolate(isolate, "v8::V8::AddMessageListener()");
5054   ON_BAILOUT(isolate, "v8::V8::AddMessageListener()", return false);
5055   ENTER_V8(isolate);
5056   i::HandleScope scope(isolate);
5057   NeanderArray listeners(isolate->factory()->message_listeners());
5058   NeanderObject obj(2);
5059   obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
5060   obj.set(1, data.IsEmpty() ?
5061              isolate->heap()->undefined_value() :
5062              *Utils::OpenHandle(*data));
5063   listeners.add(obj.value());
5064   return true;
5065 }
5066
5067
5068 void V8::RemoveMessageListeners(MessageCallback that) {
5069   i::Isolate* isolate = i::Isolate::Current();
5070   EnsureInitializedForIsolate(isolate, "v8::V8::RemoveMessageListener()");
5071   ON_BAILOUT(isolate, "v8::V8::RemoveMessageListeners()", return);
5072   ENTER_V8(isolate);
5073   i::HandleScope scope(isolate);
5074   NeanderArray listeners(isolate->factory()->message_listeners());
5075   for (int i = 0; i < listeners.length(); i++) {
5076     if (listeners.get(i)->IsUndefined()) continue;  // skip deleted ones
5077
5078     NeanderObject listener(i::JSObject::cast(listeners.get(i)));
5079     i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
5080     if (callback_obj->address() == FUNCTION_ADDR(that)) {
5081       listeners.set(i, isolate->heap()->undefined_value());
5082     }
5083   }
5084 }
5085
5086
5087 void V8::SetCaptureStackTraceForUncaughtExceptions(
5088       bool capture,
5089       int frame_limit,
5090       StackTrace::StackTraceOptions options) {
5091   i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
5092       capture,
5093       frame_limit,
5094       options);
5095 }
5096
5097
5098 void V8::SetCounterFunction(CounterLookupCallback callback) {
5099   i::Isolate* isolate = EnterIsolateIfNeeded();
5100   if (IsDeadCheck(isolate, "v8::V8::SetCounterFunction()")) return;
5101   isolate->stats_table()->SetCounterFunction(callback);
5102 }
5103
5104 void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
5105   i::Isolate* isolate = EnterIsolateIfNeeded();
5106   if (IsDeadCheck(isolate, "v8::V8::SetCreateHistogramFunction()")) return;
5107   isolate->stats_table()->SetCreateHistogramFunction(callback);
5108 }
5109
5110 void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
5111   i::Isolate* isolate = EnterIsolateIfNeeded();
5112   if (IsDeadCheck(isolate, "v8::V8::SetAddHistogramSampleFunction()")) return;
5113   isolate->stats_table()->
5114       SetAddHistogramSampleFunction(callback);
5115 }
5116
5117 void V8::EnableSlidingStateWindow() {
5118   i::Isolate* isolate = i::Isolate::Current();
5119   if (IsDeadCheck(isolate, "v8::V8::EnableSlidingStateWindow()")) return;
5120   isolate->logger()->EnableSlidingStateWindow();
5121 }
5122
5123
5124 void V8::SetFailedAccessCheckCallbackFunction(
5125       FailedAccessCheckCallback callback) {
5126   i::Isolate* isolate = i::Isolate::Current();
5127   if (IsDeadCheck(isolate, "v8::V8::SetFailedAccessCheckCallbackFunction()")) {
5128     return;
5129   }
5130   isolate->SetFailedAccessCheckCallback(callback);
5131 }
5132
5133
5134 void V8::SetUserObjectComparisonCallbackFunction(
5135       UserObjectComparisonCallback callback) {
5136   i::Isolate* isolate = i::Isolate::Current();
5137   if (IsDeadCheck(isolate, "v8::V8::SetUserObjectComparisonCallbackFunction()")) {
5138     return;
5139   }
5140   isolate->SetUserObjectComparisonCallback(callback);
5141 }
5142
5143
5144 void V8::AddObjectGroup(Persistent<Value>* objects,
5145                         size_t length,
5146                         RetainedObjectInfo* info) {
5147   i::Isolate* isolate = i::Isolate::Current();
5148   if (IsDeadCheck(isolate, "v8::V8::AddObjectGroup()")) return;
5149   STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5150   isolate->global_handles()->AddObjectGroup(
5151       reinterpret_cast<i::Object***>(objects), length, info);
5152 }
5153
5154
5155 void V8::AddImplicitReferences(Persistent<Object> parent,
5156                                Persistent<Value>* children,
5157                                size_t length) {
5158   i::Isolate* isolate = i::Isolate::Current();
5159   if (IsDeadCheck(isolate, "v8::V8::AddImplicitReferences()")) return;
5160   STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5161   isolate->global_handles()->AddImplicitReferences(
5162       i::Handle<i::HeapObject>::cast(Utils::OpenHandle(*parent)).location(),
5163       reinterpret_cast<i::Object***>(children), length);
5164 }
5165
5166
5167 int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
5168   i::Isolate* isolate = i::Isolate::Current();
5169   if (IsDeadCheck(isolate, "v8::V8::AdjustAmountOfExternalAllocatedMemory()")) {
5170     return 0;
5171   }
5172   return isolate->heap()->AdjustAmountOfExternalAllocatedMemory(
5173       change_in_bytes);
5174 }
5175
5176
5177 void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
5178   i::Isolate* isolate = i::Isolate::Current();
5179   if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCPrologueCallback()")) return;
5180   isolate->heap()->SetGlobalGCPrologueCallback(callback);
5181 }
5182
5183
5184 void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
5185   i::Isolate* isolate = i::Isolate::Current();
5186   if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCEpilogueCallback()")) return;
5187   isolate->heap()->SetGlobalGCEpilogueCallback(callback);
5188 }
5189
5190
5191 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5192   i::Isolate* isolate = i::Isolate::Current();
5193   if (IsDeadCheck(isolate, "v8::V8::AddGCPrologueCallback()")) return;
5194   isolate->heap()->AddGCPrologueCallback(callback, gc_type);
5195 }
5196
5197
5198 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5199   i::Isolate* isolate = i::Isolate::Current();
5200   if (IsDeadCheck(isolate, "v8::V8::RemoveGCPrologueCallback()")) return;
5201   isolate->heap()->RemoveGCPrologueCallback(callback);
5202 }
5203
5204
5205 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5206   i::Isolate* isolate = i::Isolate::Current();
5207   if (IsDeadCheck(isolate, "v8::V8::AddGCEpilogueCallback()")) return;
5208   isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
5209 }
5210
5211
5212 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5213   i::Isolate* isolate = i::Isolate::Current();
5214   if (IsDeadCheck(isolate, "v8::V8::RemoveGCEpilogueCallback()")) return;
5215   isolate->heap()->RemoveGCEpilogueCallback(callback);
5216 }
5217
5218
5219 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5220                                      ObjectSpace space,
5221                                      AllocationAction action) {
5222   i::Isolate* isolate = i::Isolate::Current();
5223   if (IsDeadCheck(isolate, "v8::V8::AddMemoryAllocationCallback()")) return;
5224   isolate->memory_allocator()->AddMemoryAllocationCallback(
5225       callback, space, action);
5226 }
5227
5228
5229 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
5230   i::Isolate* isolate = i::Isolate::Current();
5231   if (IsDeadCheck(isolate, "v8::V8::RemoveMemoryAllocationCallback()")) return;
5232   isolate->memory_allocator()->RemoveMemoryAllocationCallback(
5233       callback);
5234 }
5235
5236
5237 void V8::PauseProfiler() {
5238   i::Isolate* isolate = i::Isolate::Current();
5239   isolate->logger()->PauseProfiler();
5240 }
5241
5242
5243 void V8::ResumeProfiler() {
5244   i::Isolate* isolate = i::Isolate::Current();
5245   isolate->logger()->ResumeProfiler();
5246 }
5247
5248
5249 bool V8::IsProfilerPaused() {
5250   i::Isolate* isolate = i::Isolate::Current();
5251   return isolate->logger()->IsProfilerPaused();
5252 }
5253
5254
5255 int V8::GetCurrentThreadId() {
5256   i::Isolate* isolate = i::Isolate::Current();
5257   EnsureInitializedForIsolate(isolate, "V8::GetCurrentThreadId()");
5258   return isolate->thread_id().ToInteger();
5259 }
5260
5261
5262 void V8::TerminateExecution(int thread_id) {
5263   i::Isolate* isolate = i::Isolate::Current();
5264   if (!isolate->IsInitialized()) return;
5265   API_ENTRY_CHECK(isolate, "V8::TerminateExecution()");
5266   // If the thread_id identifies the current thread just terminate
5267   // execution right away.  Otherwise, ask the thread manager to
5268   // terminate the thread with the given id if any.
5269   i::ThreadId internal_tid = i::ThreadId::FromInteger(thread_id);
5270   if (isolate->thread_id().Equals(internal_tid)) {
5271     isolate->stack_guard()->TerminateExecution();
5272   } else {
5273     isolate->thread_manager()->TerminateExecution(internal_tid);
5274   }
5275 }
5276
5277
5278 void V8::TerminateExecution(Isolate* isolate) {
5279   // If no isolate is supplied, use the default isolate.
5280   if (isolate != NULL) {
5281     reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->TerminateExecution();
5282   } else {
5283     i::Isolate::GetDefaultIsolateStackGuard()->TerminateExecution();
5284   }
5285 }
5286
5287
5288 bool V8::IsExecutionTerminating(Isolate* isolate) {
5289   i::Isolate* i_isolate = isolate != NULL ?
5290       reinterpret_cast<i::Isolate*>(isolate) : i::Isolate::Current();
5291   return IsExecutionTerminatingCheck(i_isolate);
5292 }
5293
5294
5295 Isolate* Isolate::GetCurrent() {
5296   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5297   return reinterpret_cast<Isolate*>(isolate);
5298 }
5299
5300
5301 Isolate* Isolate::New() {
5302   i::Isolate* isolate = new i::Isolate();
5303   return reinterpret_cast<Isolate*>(isolate);
5304 }
5305
5306
5307 void Isolate::Dispose() {
5308   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5309   if (!ApiCheck(!isolate->IsInUse(),
5310                 "v8::Isolate::Dispose()",
5311                 "Disposing the isolate that is entered by a thread.")) {
5312     return;
5313   }
5314   isolate->TearDown();
5315 }
5316
5317
5318 void Isolate::Enter() {
5319   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5320   isolate->Enter();
5321 }
5322
5323
5324 void Isolate::Exit() {
5325   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5326   isolate->Exit();
5327 }
5328
5329
5330 void Isolate::SetData(void* data) {
5331   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5332   isolate->SetData(data);
5333 }
5334
5335 void* Isolate::GetData() {
5336   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5337   return isolate->GetData();
5338 }
5339
5340
5341 String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj)
5342     : str_(NULL), length_(0) {
5343   i::Isolate* isolate = i::Isolate::Current();
5344   if (IsDeadCheck(isolate, "v8::String::Utf8Value::Utf8Value()")) return;
5345   if (obj.IsEmpty()) return;
5346   ENTER_V8(isolate);
5347   i::HandleScope scope(isolate);
5348   TryCatch try_catch;
5349   Handle<String> str = obj->ToString();
5350   if (str.IsEmpty()) return;
5351   length_ = str->Utf8Length();
5352   str_ = i::NewArray<char>(length_ + 1);
5353   str->WriteUtf8(str_);
5354 }
5355
5356
5357 String::Utf8Value::~Utf8Value() {
5358   i::DeleteArray(str_);
5359 }
5360
5361
5362 String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj)
5363     : str_(NULL), length_(0) {
5364   i::Isolate* isolate = i::Isolate::Current();
5365   if (IsDeadCheck(isolate, "v8::String::AsciiValue::AsciiValue()")) return;
5366   if (obj.IsEmpty()) return;
5367   ENTER_V8(isolate);
5368   i::HandleScope scope(isolate);
5369   TryCatch try_catch;
5370   Handle<String> str = obj->ToString();
5371   if (str.IsEmpty()) return;
5372   length_ = str->Length();
5373   str_ = i::NewArray<char>(length_ + 1);
5374   str->WriteAscii(str_);
5375 }
5376
5377
5378 String::AsciiValue::~AsciiValue() {
5379   i::DeleteArray(str_);
5380 }
5381
5382
5383 String::Value::Value(v8::Handle<v8::Value> obj)
5384     : str_(NULL), length_(0) {
5385   i::Isolate* isolate = i::Isolate::Current();
5386   if (IsDeadCheck(isolate, "v8::String::Value::Value()")) return;
5387   if (obj.IsEmpty()) return;
5388   ENTER_V8(isolate);
5389   i::HandleScope scope(isolate);
5390   TryCatch try_catch;
5391   Handle<String> str = obj->ToString();
5392   if (str.IsEmpty()) return;
5393   length_ = str->Length();
5394   str_ = i::NewArray<uint16_t>(length_ + 1);
5395   str->Write(str_);
5396 }
5397
5398
5399 String::Value::~Value() {
5400   i::DeleteArray(str_);
5401 }
5402
5403 Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
5404   i::Isolate* isolate = i::Isolate::Current();
5405   LOG_API(isolate, "RangeError");
5406   ON_BAILOUT(isolate, "v8::Exception::RangeError()", return Local<Value>());
5407   ENTER_V8(isolate);
5408   i::Object* error;
5409   {
5410     i::HandleScope scope(isolate);
5411     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5412     i::Handle<i::Object> result = isolate->factory()->NewRangeError(message);
5413     error = *result;
5414   }
5415   i::Handle<i::Object> result(error);
5416   return Utils::ToLocal(result);
5417 }
5418
5419 Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
5420   i::Isolate* isolate = i::Isolate::Current();
5421   LOG_API(isolate, "ReferenceError");
5422   ON_BAILOUT(isolate, "v8::Exception::ReferenceError()", return Local<Value>());
5423   ENTER_V8(isolate);
5424   i::Object* error;
5425   {
5426     i::HandleScope scope(isolate);
5427     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5428     i::Handle<i::Object> result =
5429         isolate->factory()->NewReferenceError(message);
5430     error = *result;
5431   }
5432   i::Handle<i::Object> result(error);
5433   return Utils::ToLocal(result);
5434 }
5435
5436 Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
5437   i::Isolate* isolate = i::Isolate::Current();
5438   LOG_API(isolate, "SyntaxError");
5439   ON_BAILOUT(isolate, "v8::Exception::SyntaxError()", return Local<Value>());
5440   ENTER_V8(isolate);
5441   i::Object* error;
5442   {
5443     i::HandleScope scope(isolate);
5444     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5445     i::Handle<i::Object> result = isolate->factory()->NewSyntaxError(message);
5446     error = *result;
5447   }
5448   i::Handle<i::Object> result(error);
5449   return Utils::ToLocal(result);
5450 }
5451
5452 Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
5453   i::Isolate* isolate = i::Isolate::Current();
5454   LOG_API(isolate, "TypeError");
5455   ON_BAILOUT(isolate, "v8::Exception::TypeError()", return Local<Value>());
5456   ENTER_V8(isolate);
5457   i::Object* error;
5458   {
5459     i::HandleScope scope(isolate);
5460     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5461     i::Handle<i::Object> result = isolate->factory()->NewTypeError(message);
5462     error = *result;
5463   }
5464   i::Handle<i::Object> result(error);
5465   return Utils::ToLocal(result);
5466 }
5467
5468 Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
5469   i::Isolate* isolate = i::Isolate::Current();
5470   LOG_API(isolate, "Error");
5471   ON_BAILOUT(isolate, "v8::Exception::Error()", return Local<Value>());
5472   ENTER_V8(isolate);
5473   i::Object* error;
5474   {
5475     i::HandleScope scope(isolate);
5476     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5477     i::Handle<i::Object> result = isolate->factory()->NewError(message);
5478     error = *result;
5479   }
5480   i::Handle<i::Object> result(error);
5481   return Utils::ToLocal(result);
5482 }
5483
5484
5485 // --- D e b u g   S u p p o r t ---
5486
5487 #ifdef ENABLE_DEBUGGER_SUPPORT
5488
5489 static void EventCallbackWrapper(const v8::Debug::EventDetails& event_details) {
5490   i::Isolate* isolate = i::Isolate::Current();
5491   if (isolate->debug_event_callback() != NULL) {
5492     isolate->debug_event_callback()(event_details.GetEvent(),
5493                                     event_details.GetExecutionState(),
5494                                     event_details.GetEventData(),
5495                                     event_details.GetCallbackData());
5496   }
5497 }
5498
5499
5500 bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
5501   i::Isolate* isolate = i::Isolate::Current();
5502   EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener()");
5503   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5504   ENTER_V8(isolate);
5505
5506   isolate->set_debug_event_callback(that);
5507
5508   i::HandleScope scope(isolate);
5509   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5510   if (that != NULL) {
5511     foreign =
5512         isolate->factory()->NewForeign(FUNCTION_ADDR(EventCallbackWrapper));
5513   }
5514   isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5515   return true;
5516 }
5517
5518
5519 bool Debug::SetDebugEventListener2(EventCallback2 that, Handle<Value> data) {
5520   i::Isolate* isolate = i::Isolate::Current();
5521   EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener2()");
5522   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener2()", return false);
5523   ENTER_V8(isolate);
5524   i::HandleScope scope(isolate);
5525   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5526   if (that != NULL) {
5527     foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
5528   }
5529   isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5530   return true;
5531 }
5532
5533
5534 bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
5535                                   Handle<Value> data) {
5536   i::Isolate* isolate = i::Isolate::Current();
5537   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5538   ENTER_V8(isolate);
5539   isolate->debugger()->SetEventListener(Utils::OpenHandle(*that),
5540                                                       Utils::OpenHandle(*data));
5541   return true;
5542 }
5543
5544
5545 void Debug::DebugBreak(Isolate* isolate) {
5546   // If no isolate is supplied, use the default isolate.
5547   if (isolate != NULL) {
5548     reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->DebugBreak();
5549   } else {
5550     i::Isolate::GetDefaultIsolateStackGuard()->DebugBreak();
5551   }
5552 }
5553
5554
5555 void Debug::CancelDebugBreak(Isolate* isolate) {
5556   // If no isolate is supplied, use the default isolate.
5557   if (isolate != NULL) {
5558     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5559     internal_isolate->stack_guard()->Continue(i::DEBUGBREAK);
5560   } else {
5561     i::Isolate::GetDefaultIsolateStackGuard()->Continue(i::DEBUGBREAK);
5562   }
5563 }
5564
5565
5566 void Debug::DebugBreakForCommand(ClientData* data, Isolate* isolate) {
5567   // If no isolate is supplied, use the default isolate.
5568   if (isolate != NULL) {
5569     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5570     internal_isolate->debugger()->EnqueueDebugCommand(data);
5571   } else {
5572     i::Isolate::GetDefaultIsolateDebugger()->EnqueueDebugCommand(data);
5573   }
5574 }
5575
5576
5577 static void MessageHandlerWrapper(const v8::Debug::Message& message) {
5578   i::Isolate* isolate = i::Isolate::Current();
5579   if (isolate->message_handler()) {
5580     v8::String::Value json(message.GetJSON());
5581     (isolate->message_handler())(*json, json.length(), message.GetClientData());
5582   }
5583 }
5584
5585
5586 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
5587                               bool message_handler_thread) {
5588   i::Isolate* isolate = i::Isolate::Current();
5589   EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5590   ENTER_V8(isolate);
5591
5592   // Message handler thread not supported any more. Parameter temporally left in
5593   // the API for client compatibility reasons.
5594   CHECK(!message_handler_thread);
5595
5596   // TODO(sgjesse) support the old message handler API through a simple wrapper.
5597   isolate->set_message_handler(handler);
5598   if (handler != NULL) {
5599     isolate->debugger()->SetMessageHandler(MessageHandlerWrapper);
5600   } else {
5601     isolate->debugger()->SetMessageHandler(NULL);
5602   }
5603 }
5604
5605
5606 void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
5607   i::Isolate* isolate = i::Isolate::Current();
5608   EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5609   ENTER_V8(isolate);
5610   isolate->debugger()->SetMessageHandler(handler);
5611 }
5612
5613
5614 void Debug::SendCommand(const uint16_t* command, int length,
5615                         ClientData* client_data,
5616                         Isolate* isolate) {
5617   // If no isolate is supplied, use the default isolate.
5618   if (isolate != NULL) {
5619     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5620     internal_isolate->debugger()->ProcessCommand(
5621         i::Vector<const uint16_t>(command, length), client_data);
5622   } else {
5623     i::Isolate::GetDefaultIsolateDebugger()->ProcessCommand(
5624         i::Vector<const uint16_t>(command, length), client_data);
5625   }
5626 }
5627
5628
5629 void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
5630                                    int period) {
5631   i::Isolate* isolate = i::Isolate::Current();
5632   EnsureInitializedForIsolate(isolate, "v8::Debug::SetHostDispatchHandler");
5633   ENTER_V8(isolate);
5634   isolate->debugger()->SetHostDispatchHandler(handler, period);
5635 }
5636
5637
5638 void Debug::SetDebugMessageDispatchHandler(
5639     DebugMessageDispatchHandler handler, bool provide_locker) {
5640   i::Isolate* isolate = i::Isolate::Current();
5641   EnsureInitializedForIsolate(isolate,
5642                               "v8::Debug::SetDebugMessageDispatchHandler");
5643   ENTER_V8(isolate);
5644   isolate->debugger()->SetDebugMessageDispatchHandler(
5645       handler, provide_locker);
5646 }
5647
5648
5649 Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
5650                          v8::Handle<v8::Value> data) {
5651   i::Isolate* isolate = i::Isolate::Current();
5652   if (!isolate->IsInitialized()) return Local<Value>();
5653   ON_BAILOUT(isolate, "v8::Debug::Call()", return Local<Value>());
5654   ENTER_V8(isolate);
5655   i::Handle<i::Object> result;
5656   EXCEPTION_PREAMBLE(isolate);
5657   if (data.IsEmpty()) {
5658     result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5659                                        isolate->factory()->undefined_value(),
5660                                        &has_pending_exception);
5661   } else {
5662     result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5663                                        Utils::OpenHandle(*data),
5664                                        &has_pending_exception);
5665   }
5666   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5667   return Utils::ToLocal(result);
5668 }
5669
5670
5671 Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
5672   i::Isolate* isolate = i::Isolate::Current();
5673   if (!isolate->IsInitialized()) return Local<Value>();
5674   ON_BAILOUT(isolate, "v8::Debug::GetMirror()", return Local<Value>());
5675   ENTER_V8(isolate);
5676   v8::HandleScope scope;
5677   i::Debug* isolate_debug = isolate->debug();
5678   isolate_debug->Load();
5679   i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global());
5680   i::Handle<i::String> name =
5681       isolate->factory()->LookupAsciiSymbol("MakeMirror");
5682   i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
5683   i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
5684   v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
5685   const int kArgc = 1;
5686   v8::Handle<v8::Value> argv[kArgc] = { obj };
5687   EXCEPTION_PREAMBLE(isolate);
5688   v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
5689                                               kArgc,
5690                                               argv);
5691   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5692   return scope.Close(result);
5693 }
5694
5695
5696 bool Debug::EnableAgent(const char* name, int port, bool wait_for_connection) {
5697   return i::Isolate::Current()->debugger()->StartAgent(name, port,
5698                                                        wait_for_connection);
5699 }
5700
5701
5702 void Debug::DisableAgent() {
5703   return i::Isolate::Current()->debugger()->StopAgent();
5704 }
5705
5706
5707 void Debug::ProcessDebugMessages() {
5708   i::Execution::ProcessDebugMesssages(true);
5709 }
5710
5711 Local<Context> Debug::GetDebugContext() {
5712   i::Isolate* isolate = i::Isolate::Current();
5713   EnsureInitializedForIsolate(isolate, "v8::Debug::GetDebugContext()");
5714   ENTER_V8(isolate);
5715   return Utils::ToLocal(i::Isolate::Current()->debugger()->GetDebugContext());
5716 }
5717
5718 #endif  // ENABLE_DEBUGGER_SUPPORT
5719
5720
5721 Handle<String> CpuProfileNode::GetFunctionName() const {
5722   i::Isolate* isolate = i::Isolate::Current();
5723   IsDeadCheck(isolate, "v8::CpuProfileNode::GetFunctionName");
5724   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5725   const i::CodeEntry* entry = node->entry();
5726   if (!entry->has_name_prefix()) {
5727     return Handle<String>(ToApi<String>(
5728         isolate->factory()->LookupAsciiSymbol(entry->name())));
5729   } else {
5730     return Handle<String>(ToApi<String>(isolate->factory()->NewConsString(
5731         isolate->factory()->LookupAsciiSymbol(entry->name_prefix()),
5732         isolate->factory()->LookupAsciiSymbol(entry->name()))));
5733   }
5734 }
5735
5736
5737 Handle<String> CpuProfileNode::GetScriptResourceName() const {
5738   i::Isolate* isolate = i::Isolate::Current();
5739   IsDeadCheck(isolate, "v8::CpuProfileNode::GetScriptResourceName");
5740   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5741   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5742       node->entry()->resource_name())));
5743 }
5744
5745
5746 int CpuProfileNode::GetLineNumber() const {
5747   i::Isolate* isolate = i::Isolate::Current();
5748   IsDeadCheck(isolate, "v8::CpuProfileNode::GetLineNumber");
5749   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
5750 }
5751
5752
5753 double CpuProfileNode::GetTotalTime() const {
5754   i::Isolate* isolate = i::Isolate::Current();
5755   IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalTime");
5756   return reinterpret_cast<const i::ProfileNode*>(this)->GetTotalMillis();
5757 }
5758
5759
5760 double CpuProfileNode::GetSelfTime() const {
5761   i::Isolate* isolate = i::Isolate::Current();
5762   IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfTime");
5763   return reinterpret_cast<const i::ProfileNode*>(this)->GetSelfMillis();
5764 }
5765
5766
5767 double CpuProfileNode::GetTotalSamplesCount() const {
5768   i::Isolate* isolate = i::Isolate::Current();
5769   IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalSamplesCount");
5770   return reinterpret_cast<const i::ProfileNode*>(this)->total_ticks();
5771 }
5772
5773
5774 double CpuProfileNode::GetSelfSamplesCount() const {
5775   i::Isolate* isolate = i::Isolate::Current();
5776   IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfSamplesCount");
5777   return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
5778 }
5779
5780
5781 unsigned CpuProfileNode::GetCallUid() const {
5782   i::Isolate* isolate = i::Isolate::Current();
5783   IsDeadCheck(isolate, "v8::CpuProfileNode::GetCallUid");
5784   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->GetCallUid();
5785 }
5786
5787
5788 int CpuProfileNode::GetChildrenCount() const {
5789   i::Isolate* isolate = i::Isolate::Current();
5790   IsDeadCheck(isolate, "v8::CpuProfileNode::GetChildrenCount");
5791   return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
5792 }
5793
5794
5795 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
5796   i::Isolate* isolate = i::Isolate::Current();
5797   IsDeadCheck(isolate, "v8::CpuProfileNode::GetChild");
5798   const i::ProfileNode* child =
5799       reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
5800   return reinterpret_cast<const CpuProfileNode*>(child);
5801 }
5802
5803
5804 void CpuProfile::Delete() {
5805   i::Isolate* isolate = i::Isolate::Current();
5806   IsDeadCheck(isolate, "v8::CpuProfile::Delete");
5807   i::CpuProfiler::DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
5808   if (i::CpuProfiler::GetProfilesCount() == 0 &&
5809       !i::CpuProfiler::HasDetachedProfiles()) {
5810     // If this was the last profile, clean up all accessory data as well.
5811     i::CpuProfiler::DeleteAllProfiles();
5812   }
5813 }
5814
5815
5816 unsigned CpuProfile::GetUid() const {
5817   i::Isolate* isolate = i::Isolate::Current();
5818   IsDeadCheck(isolate, "v8::CpuProfile::GetUid");
5819   return reinterpret_cast<const i::CpuProfile*>(this)->uid();
5820 }
5821
5822
5823 Handle<String> CpuProfile::GetTitle() const {
5824   i::Isolate* isolate = i::Isolate::Current();
5825   IsDeadCheck(isolate, "v8::CpuProfile::GetTitle");
5826   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5827   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5828       profile->title())));
5829 }
5830
5831
5832 const CpuProfileNode* CpuProfile::GetBottomUpRoot() const {
5833   i::Isolate* isolate = i::Isolate::Current();
5834   IsDeadCheck(isolate, "v8::CpuProfile::GetBottomUpRoot");
5835   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5836   return reinterpret_cast<const CpuProfileNode*>(profile->bottom_up()->root());
5837 }
5838
5839
5840 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
5841   i::Isolate* isolate = i::Isolate::Current();
5842   IsDeadCheck(isolate, "v8::CpuProfile::GetTopDownRoot");
5843   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5844   return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
5845 }
5846
5847
5848 int CpuProfiler::GetProfilesCount() {
5849   i::Isolate* isolate = i::Isolate::Current();
5850   IsDeadCheck(isolate, "v8::CpuProfiler::GetProfilesCount");
5851   return i::CpuProfiler::GetProfilesCount();
5852 }
5853
5854
5855 const CpuProfile* CpuProfiler::GetProfile(int index,
5856                                           Handle<Value> security_token) {
5857   i::Isolate* isolate = i::Isolate::Current();
5858   IsDeadCheck(isolate, "v8::CpuProfiler::GetProfile");
5859   return reinterpret_cast<const CpuProfile*>(
5860       i::CpuProfiler::GetProfile(
5861           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5862           index));
5863 }
5864
5865
5866 const CpuProfile* CpuProfiler::FindProfile(unsigned uid,
5867                                            Handle<Value> security_token) {
5868   i::Isolate* isolate = i::Isolate::Current();
5869   IsDeadCheck(isolate, "v8::CpuProfiler::FindProfile");
5870   return reinterpret_cast<const CpuProfile*>(
5871       i::CpuProfiler::FindProfile(
5872           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5873           uid));
5874 }
5875
5876
5877 void CpuProfiler::StartProfiling(Handle<String> title) {
5878   i::Isolate* isolate = i::Isolate::Current();
5879   IsDeadCheck(isolate, "v8::CpuProfiler::StartProfiling");
5880   i::CpuProfiler::StartProfiling(*Utils::OpenHandle(*title));
5881 }
5882
5883
5884 const CpuProfile* CpuProfiler::StopProfiling(Handle<String> title,
5885                                              Handle<Value> security_token) {
5886   i::Isolate* isolate = i::Isolate::Current();
5887   IsDeadCheck(isolate, "v8::CpuProfiler::StopProfiling");
5888   return reinterpret_cast<const CpuProfile*>(
5889       i::CpuProfiler::StopProfiling(
5890           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5891           *Utils::OpenHandle(*title)));
5892 }
5893
5894
5895 void CpuProfiler::DeleteAllProfiles() {
5896   i::Isolate* isolate = i::Isolate::Current();
5897   IsDeadCheck(isolate, "v8::CpuProfiler::DeleteAllProfiles");
5898   i::CpuProfiler::DeleteAllProfiles();
5899 }
5900
5901
5902 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
5903   return const_cast<i::HeapGraphEdge*>(
5904       reinterpret_cast<const i::HeapGraphEdge*>(edge));
5905 }
5906
5907
5908 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
5909   i::Isolate* isolate = i::Isolate::Current();
5910   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetType");
5911   return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
5912 }
5913
5914
5915 Handle<Value> HeapGraphEdge::GetName() const {
5916   i::Isolate* isolate = i::Isolate::Current();
5917   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetName");
5918   i::HeapGraphEdge* edge = ToInternal(this);
5919   switch (edge->type()) {
5920     case i::HeapGraphEdge::kContextVariable:
5921     case i::HeapGraphEdge::kInternal:
5922     case i::HeapGraphEdge::kProperty:
5923     case i::HeapGraphEdge::kShortcut:
5924       return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5925           edge->name())));
5926     case i::HeapGraphEdge::kElement:
5927     case i::HeapGraphEdge::kHidden:
5928       return Handle<Number>(ToApi<Number>(isolate->factory()->NewNumberFromInt(
5929           edge->index())));
5930     default: UNREACHABLE();
5931   }
5932   return v8::Undefined();
5933 }
5934
5935
5936 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
5937   i::Isolate* isolate = i::Isolate::Current();
5938   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetFromNode");
5939   const i::HeapEntry* from = ToInternal(this)->From();
5940   return reinterpret_cast<const HeapGraphNode*>(from);
5941 }
5942
5943
5944 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
5945   i::Isolate* isolate = i::Isolate::Current();
5946   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetToNode");
5947   const i::HeapEntry* to = ToInternal(this)->to();
5948   return reinterpret_cast<const HeapGraphNode*>(to);
5949 }
5950
5951
5952 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
5953   return const_cast<i::HeapEntry*>(
5954       reinterpret_cast<const i::HeapEntry*>(entry));
5955 }
5956
5957
5958 HeapGraphNode::Type HeapGraphNode::GetType() const {
5959   i::Isolate* isolate = i::Isolate::Current();
5960   IsDeadCheck(isolate, "v8::HeapGraphNode::GetType");
5961   return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
5962 }
5963
5964
5965 Handle<String> HeapGraphNode::GetName() const {
5966   i::Isolate* isolate = i::Isolate::Current();
5967   IsDeadCheck(isolate, "v8::HeapGraphNode::GetName");
5968   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5969       ToInternal(this)->name())));
5970 }
5971
5972
5973 uint64_t HeapGraphNode::GetId() const {
5974   i::Isolate* isolate = i::Isolate::Current();
5975   IsDeadCheck(isolate, "v8::HeapGraphNode::GetId");
5976   return ToInternal(this)->id();
5977 }
5978
5979
5980 int HeapGraphNode::GetSelfSize() const {
5981   i::Isolate* isolate = i::Isolate::Current();
5982   IsDeadCheck(isolate, "v8::HeapGraphNode::GetSelfSize");
5983   return ToInternal(this)->self_size();
5984 }
5985
5986
5987 int HeapGraphNode::GetRetainedSize(bool exact) const {
5988   i::Isolate* isolate = i::Isolate::Current();
5989   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainedSize");
5990   return ToInternal(this)->RetainedSize(exact);
5991 }
5992
5993
5994 int HeapGraphNode::GetChildrenCount() const {
5995   i::Isolate* isolate = i::Isolate::Current();
5996   IsDeadCheck(isolate, "v8::HeapSnapshot::GetChildrenCount");
5997   return ToInternal(this)->children().length();
5998 }
5999
6000
6001 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
6002   i::Isolate* isolate = i::Isolate::Current();
6003   IsDeadCheck(isolate, "v8::HeapSnapshot::GetChild");
6004   return reinterpret_cast<const HeapGraphEdge*>(
6005       &ToInternal(this)->children()[index]);
6006 }
6007
6008
6009 int HeapGraphNode::GetRetainersCount() const {
6010   i::Isolate* isolate = i::Isolate::Current();
6011   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainersCount");
6012   return ToInternal(this)->retainers().length();
6013 }
6014
6015
6016 const HeapGraphEdge* HeapGraphNode::GetRetainer(int index) const {
6017   i::Isolate* isolate = i::Isolate::Current();
6018   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainer");
6019   return reinterpret_cast<const HeapGraphEdge*>(
6020       ToInternal(this)->retainers()[index]);
6021 }
6022
6023
6024 const HeapGraphNode* HeapGraphNode::GetDominatorNode() const {
6025   i::Isolate* isolate = i::Isolate::Current();
6026   IsDeadCheck(isolate, "v8::HeapSnapshot::GetDominatorNode");
6027   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->dominator());
6028 }
6029
6030
6031 v8::Handle<v8::Value> HeapGraphNode::GetHeapValue() const {
6032   i::Isolate* isolate = i::Isolate::Current();
6033   IsDeadCheck(isolate, "v8::HeapGraphNode::GetHeapValue");
6034   i::Handle<i::HeapObject> object = ToInternal(this)->GetHeapObject();
6035   return v8::Handle<Value>(!object.is_null() ?
6036                            ToApi<Value>(object) : ToApi<Value>(
6037                                isolate->factory()->undefined_value()));
6038 }
6039
6040
6041 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
6042   return const_cast<i::HeapSnapshot*>(
6043       reinterpret_cast<const i::HeapSnapshot*>(snapshot));
6044 }
6045
6046
6047 void HeapSnapshot::Delete() {
6048   i::Isolate* isolate = i::Isolate::Current();
6049   IsDeadCheck(isolate, "v8::HeapSnapshot::Delete");
6050   if (i::HeapProfiler::GetSnapshotsCount() > 1) {
6051     ToInternal(this)->Delete();
6052   } else {
6053     // If this is the last snapshot, clean up all accessory data as well.
6054     i::HeapProfiler::DeleteAllSnapshots();
6055   }
6056 }
6057
6058
6059 HeapSnapshot::Type HeapSnapshot::GetType() const {
6060   i::Isolate* isolate = i::Isolate::Current();
6061   IsDeadCheck(isolate, "v8::HeapSnapshot::GetType");
6062   return static_cast<HeapSnapshot::Type>(ToInternal(this)->type());
6063 }
6064
6065
6066 unsigned HeapSnapshot::GetUid() const {
6067   i::Isolate* isolate = i::Isolate::Current();
6068   IsDeadCheck(isolate, "v8::HeapSnapshot::GetUid");
6069   return ToInternal(this)->uid();
6070 }
6071
6072
6073 Handle<String> HeapSnapshot::GetTitle() const {
6074   i::Isolate* isolate = i::Isolate::Current();
6075   IsDeadCheck(isolate, "v8::HeapSnapshot::GetTitle");
6076   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
6077       ToInternal(this)->title())));
6078 }
6079
6080
6081 const HeapGraphNode* HeapSnapshot::GetRoot() const {
6082   i::Isolate* isolate = i::Isolate::Current();
6083   IsDeadCheck(isolate, "v8::HeapSnapshot::GetHead");
6084   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
6085 }
6086
6087
6088 const HeapGraphNode* HeapSnapshot::GetNodeById(uint64_t id) const {
6089   i::Isolate* isolate = i::Isolate::Current();
6090   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodeById");
6091   return reinterpret_cast<const HeapGraphNode*>(
6092       ToInternal(this)->GetEntryById(id));
6093 }
6094
6095
6096 int HeapSnapshot::GetNodesCount() const {
6097   i::Isolate* isolate = i::Isolate::Current();
6098   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodesCount");
6099   return ToInternal(this)->entries()->length();
6100 }
6101
6102
6103 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
6104   i::Isolate* isolate = i::Isolate::Current();
6105   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNode");
6106   return reinterpret_cast<const HeapGraphNode*>(
6107       ToInternal(this)->entries()->at(index));
6108 }
6109
6110
6111 void HeapSnapshot::Serialize(OutputStream* stream,
6112                              HeapSnapshot::SerializationFormat format) const {
6113   i::Isolate* isolate = i::Isolate::Current();
6114   IsDeadCheck(isolate, "v8::HeapSnapshot::Serialize");
6115   ApiCheck(format == kJSON,
6116            "v8::HeapSnapshot::Serialize",
6117            "Unknown serialization format");
6118   ApiCheck(stream->GetOutputEncoding() == OutputStream::kAscii,
6119            "v8::HeapSnapshot::Serialize",
6120            "Unsupported output encoding");
6121   ApiCheck(stream->GetChunkSize() > 0,
6122            "v8::HeapSnapshot::Serialize",
6123            "Invalid stream chunk size");
6124   i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
6125   serializer.Serialize(stream);
6126 }
6127
6128
6129 int HeapProfiler::GetSnapshotsCount() {
6130   i::Isolate* isolate = i::Isolate::Current();
6131   IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshotsCount");
6132   return i::HeapProfiler::GetSnapshotsCount();
6133 }
6134
6135
6136 const HeapSnapshot* HeapProfiler::GetSnapshot(int index) {
6137   i::Isolate* isolate = i::Isolate::Current();
6138   IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshot");
6139   return reinterpret_cast<const HeapSnapshot*>(
6140       i::HeapProfiler::GetSnapshot(index));
6141 }
6142
6143
6144 const HeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {
6145   i::Isolate* isolate = i::Isolate::Current();
6146   IsDeadCheck(isolate, "v8::HeapProfiler::FindSnapshot");
6147   return reinterpret_cast<const HeapSnapshot*>(
6148       i::HeapProfiler::FindSnapshot(uid));
6149 }
6150
6151
6152 const HeapSnapshot* HeapProfiler::TakeSnapshot(Handle<String> title,
6153                                                HeapSnapshot::Type type,
6154                                                ActivityControl* control) {
6155   i::Isolate* isolate = i::Isolate::Current();
6156   IsDeadCheck(isolate, "v8::HeapProfiler::TakeSnapshot");
6157   i::HeapSnapshot::Type internal_type = i::HeapSnapshot::kFull;
6158   switch (type) {
6159     case HeapSnapshot::kFull:
6160       internal_type = i::HeapSnapshot::kFull;
6161       break;
6162     default:
6163       UNREACHABLE();
6164   }
6165   return reinterpret_cast<const HeapSnapshot*>(
6166       i::HeapProfiler::TakeSnapshot(
6167           *Utils::OpenHandle(*title), internal_type, control));
6168 }
6169
6170
6171 void HeapProfiler::DeleteAllSnapshots() {
6172   i::Isolate* isolate = i::Isolate::Current();
6173   IsDeadCheck(isolate, "v8::HeapProfiler::DeleteAllSnapshots");
6174   i::HeapProfiler::DeleteAllSnapshots();
6175 }
6176
6177
6178 void HeapProfiler::DefineWrapperClass(uint16_t class_id,
6179                                       WrapperInfoCallback callback) {
6180   i::Isolate::Current()->heap_profiler()->DefineWrapperClass(class_id,
6181                                                              callback);
6182 }
6183
6184
6185
6186 v8::Testing::StressType internal::Testing::stress_type_ =
6187     v8::Testing::kStressTypeOpt;
6188
6189
6190 void Testing::SetStressRunType(Testing::StressType type) {
6191   internal::Testing::set_stress_type(type);
6192 }
6193
6194 int Testing::GetStressRuns() {
6195   if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
6196 #ifdef DEBUG
6197   // In debug mode the code runs much slower so stressing will only make two
6198   // runs.
6199   return 2;
6200 #else
6201   return 5;
6202 #endif
6203 }
6204
6205
6206 static void SetFlagsFromString(const char* flags) {
6207   V8::SetFlagsFromString(flags, i::StrLength(flags));
6208 }
6209
6210
6211 void Testing::PrepareStressRun(int run) {
6212   static const char* kLazyOptimizations =
6213       "--prepare-always-opt --nolimit-inlining "
6214       "--noalways-opt --noopt-eagerly";
6215   static const char* kEagerOptimizations = "--opt-eagerly";
6216   static const char* kForcedOptimizations = "--always-opt";
6217
6218   // If deoptimization stressed turn on frequent deoptimization. If no value
6219   // is spefified through --deopt-every-n-times use a default default value.
6220   static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
6221   if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
6222       internal::FLAG_deopt_every_n_times == 0) {
6223     SetFlagsFromString(kDeoptEvery13Times);
6224   }
6225
6226 #ifdef DEBUG
6227   // As stressing in debug mode only make two runs skip the deopt stressing
6228   // here.
6229   if (run == GetStressRuns() - 1) {
6230     SetFlagsFromString(kForcedOptimizations);
6231   } else {
6232     SetFlagsFromString(kEagerOptimizations);
6233     SetFlagsFromString(kLazyOptimizations);
6234   }
6235 #else
6236   if (run == GetStressRuns() - 1) {
6237     SetFlagsFromString(kForcedOptimizations);
6238   } else if (run == GetStressRuns() - 2) {
6239     SetFlagsFromString(kEagerOptimizations);
6240   } else {
6241     SetFlagsFromString(kLazyOptimizations);
6242   }
6243 #endif
6244 }
6245
6246
6247 void Testing::DeoptimizeAll() {
6248   internal::Deoptimizer::DeoptimizeAll();
6249 }
6250
6251
6252 namespace internal {
6253
6254
6255 void HandleScopeImplementer::FreeThreadResources() {
6256   Free();
6257 }
6258
6259
6260 char* HandleScopeImplementer::ArchiveThread(char* storage) {
6261   v8::ImplementationUtilities::HandleScopeData* current =
6262       isolate_->handle_scope_data();
6263   handle_scope_data_ = *current;
6264   memcpy(storage, this, sizeof(*this));
6265
6266   ResetAfterArchive();
6267   current->Initialize();
6268
6269   return storage + ArchiveSpacePerThread();
6270 }
6271
6272
6273 int HandleScopeImplementer::ArchiveSpacePerThread() {
6274   return sizeof(HandleScopeImplementer);
6275 }
6276
6277
6278 char* HandleScopeImplementer::RestoreThread(char* storage) {
6279   memcpy(this, storage, sizeof(*this));
6280   *isolate_->handle_scope_data() = handle_scope_data_;
6281   return storage + ArchiveSpacePerThread();
6282 }
6283
6284
6285 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
6286   // Iterate over all handles in the blocks except for the last.
6287   for (int i = blocks()->length() - 2; i >= 0; --i) {
6288     Object** block = blocks()->at(i);
6289     v->VisitPointers(block, &block[kHandleBlockSize]);
6290   }
6291
6292   // Iterate over live handles in the last block (if any).
6293   if (!blocks()->is_empty()) {
6294     v->VisitPointers(blocks()->last(), handle_scope_data_.next);
6295   }
6296
6297   if (!saved_contexts_.is_empty()) {
6298     Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
6299     v->VisitPointers(start, start + saved_contexts_.length());
6300   }
6301 }
6302
6303
6304 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
6305   v8::ImplementationUtilities::HandleScopeData* current =
6306       isolate_->handle_scope_data();
6307   handle_scope_data_ = *current;
6308   IterateThis(v);
6309 }
6310
6311
6312 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
6313   HandleScopeImplementer* scope_implementer =
6314       reinterpret_cast<HandleScopeImplementer*>(storage);
6315   scope_implementer->IterateThis(v);
6316   return storage + ArchiveSpacePerThread();
6317 }
6318
6319 } }  // namespace v8::internal