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