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