Updated V8 from git://github.com/v8/v8.git to 06e55bc22bcb8ddb0a602e54e11971576f2d9d8a
[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 int String::WriteUtf8(char* buffer,
3637                       int capacity,
3638                       int* nchars_ref,
3639                       int options) const {
3640   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3641   if (IsDeadCheck(isolate, "v8::String::WriteUtf8()")) return 0;
3642   LOG_API(isolate, "String::WriteUtf8");
3643   ENTER_V8(isolate);
3644   i::Handle<i::String> str = Utils::OpenHandle(this);
3645   if (str->IsAsciiRepresentation()) {
3646     int len;
3647     if (capacity == -1) {
3648       capacity = str->length() + 1;
3649       len = str->length();
3650     } else {
3651       len = i::Min(capacity, str->length());
3652     }
3653     i::String::WriteToFlat(*str, buffer, 0, len);
3654     if (nchars_ref != NULL) *nchars_ref = len;
3655     if (!(options & NO_NULL_TERMINATION) && capacity > len) {
3656       buffer[len] = '\0';
3657       return len + 1;
3658     }
3659     return len;
3660   }
3661
3662   i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3663   isolate->string_tracker()->RecordWrite(str);
3664   if (options & HINT_MANY_WRITES_EXPECTED) {
3665     // Flatten the string for efficiency.  This applies whether we are
3666     // using StringInputBuffer or Get(i) to access the characters.
3667     FlattenString(str);
3668   }
3669   write_input_buffer.Reset(0, *str);
3670   int len = str->length();
3671   // Encode the first K - 3 bytes directly into the buffer since we
3672   // know there's room for them.  If no capacity is given we copy all
3673   // of them here.
3674   int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
3675   int i;
3676   int pos = 0;
3677   int nchars = 0;
3678   for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
3679     i::uc32 c = write_input_buffer.GetNext();
3680     int written = unibrow::Utf8::Encode(buffer + pos, c);
3681     pos += written;
3682     nchars++;
3683   }
3684   if (i < len) {
3685     // For the last characters we need to check the length for each one
3686     // because they may be longer than the remaining space in the
3687     // buffer.
3688     char intermediate[unibrow::Utf8::kMaxEncodedSize];
3689     for (; i < len && pos < capacity; i++) {
3690       i::uc32 c = write_input_buffer.GetNext();
3691       int written = unibrow::Utf8::Encode(intermediate, c);
3692       if (pos + written <= capacity) {
3693         for (int j = 0; j < written; j++)
3694           buffer[pos + j] = intermediate[j];
3695         pos += written;
3696         nchars++;
3697       } else {
3698         // We've reached the end of the buffer
3699         break;
3700       }
3701     }
3702   }
3703   if (nchars_ref != NULL) *nchars_ref = nchars;
3704   if (!(options & NO_NULL_TERMINATION) &&
3705       (i == len && (capacity == -1 || pos < capacity)))
3706     buffer[pos++] = '\0';
3707   return pos;
3708 }
3709
3710
3711 int String::WriteAscii(char* buffer,
3712                        int start,
3713                        int length,
3714                        int options) const {
3715   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3716   if (IsDeadCheck(isolate, "v8::String::WriteAscii()")) return 0;
3717   LOG_API(isolate, "String::WriteAscii");
3718   ENTER_V8(isolate);
3719   i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3720   ASSERT(start >= 0 && length >= -1);
3721   i::Handle<i::String> str = Utils::OpenHandle(this);
3722   isolate->string_tracker()->RecordWrite(str);
3723   if (options & HINT_MANY_WRITES_EXPECTED) {
3724     // Flatten the string for efficiency.  This applies whether we are
3725     // using StringInputBuffer or Get(i) to access the characters.
3726     str->TryFlatten();
3727   }
3728   int end = length;
3729   if ( (length == -1) || (length > str->length() - start) )
3730     end = str->length() - start;
3731   if (end < 0) return 0;
3732   write_input_buffer.Reset(start, *str);
3733   int i;
3734   for (i = 0; i < end; i++) {
3735     char c = static_cast<char>(write_input_buffer.GetNext());
3736     if (c == '\0') c = ' ';
3737     buffer[i] = c;
3738   }
3739   if (!(options & NO_NULL_TERMINATION) && (length == -1 || i < length))
3740     buffer[i] = '\0';
3741   return i;
3742 }
3743
3744
3745 int String::Write(uint16_t* buffer,
3746                   int start,
3747                   int length,
3748                   int options) const {
3749   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3750   if (IsDeadCheck(isolate, "v8::String::Write()")) return 0;
3751   LOG_API(isolate, "String::Write");
3752   ENTER_V8(isolate);
3753   ASSERT(start >= 0 && length >= -1);
3754   i::Handle<i::String> str = Utils::OpenHandle(this);
3755   isolate->string_tracker()->RecordWrite(str);
3756   if (options & HINT_MANY_WRITES_EXPECTED) {
3757     // Flatten the string for efficiency.  This applies whether we are
3758     // using StringInputBuffer or Get(i) to access the characters.
3759     str->TryFlatten();
3760   }
3761   int end = start + length;
3762   if ((length == -1) || (length > str->length() - start) )
3763     end = str->length();
3764   if (end < 0) return 0;
3765   i::String::WriteToFlat(*str, buffer, start, end);
3766   if (!(options & NO_NULL_TERMINATION) &&
3767       (length == -1 || end - start < length)) {
3768     buffer[end - start] = '\0';
3769   }
3770   return end - start;
3771 }
3772
3773
3774 bool v8::String::IsExternal() const {
3775   i::Handle<i::String> str = Utils::OpenHandle(this);
3776   if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternal()")) {
3777     return false;
3778   }
3779   EnsureInitializedForIsolate(str->GetIsolate(), "v8::String::IsExternal()");
3780   return i::StringShape(*str).IsExternalTwoByte();
3781 }
3782
3783
3784 bool v8::String::IsExternalAscii() const {
3785   i::Handle<i::String> str = Utils::OpenHandle(this);
3786   if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternalAscii()")) {
3787     return false;
3788   }
3789   return i::StringShape(*str).IsExternalAscii();
3790 }
3791
3792
3793 void v8::String::VerifyExternalStringResource(
3794     v8::String::ExternalStringResource* value) const {
3795   i::Handle<i::String> str = Utils::OpenHandle(this);
3796   const v8::String::ExternalStringResource* expected;
3797   if (i::StringShape(*str).IsExternalTwoByte()) {
3798     const void* resource =
3799         i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
3800     expected = reinterpret_cast<const ExternalStringResource*>(resource);
3801   } else {
3802     expected = NULL;
3803   }
3804   CHECK_EQ(expected, value);
3805 }
3806
3807
3808 const v8::String::ExternalAsciiStringResource*
3809       v8::String::GetExternalAsciiStringResource() const {
3810   i::Handle<i::String> str = Utils::OpenHandle(this);
3811   if (IsDeadCheck(str->GetIsolate(),
3812                   "v8::String::GetExternalAsciiStringResource()")) {
3813     return NULL;
3814   }
3815   if (i::StringShape(*str).IsExternalAscii()) {
3816     const void* resource =
3817         i::Handle<i::ExternalAsciiString>::cast(str)->resource();
3818     return reinterpret_cast<const ExternalAsciiStringResource*>(resource);
3819   } else {
3820     return NULL;
3821   }
3822 }
3823
3824
3825 double Number::Value() const {
3826   if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Value()")) return 0;
3827   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3828   return obj->Number();
3829 }
3830
3831
3832 bool Boolean::Value() const {
3833   if (IsDeadCheck(i::Isolate::Current(), "v8::Boolean::Value()")) return false;
3834   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3835   return obj->IsTrue();
3836 }
3837
3838
3839 int64_t Integer::Value() const {
3840   if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Value()")) return 0;
3841   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3842   if (obj->IsSmi()) {
3843     return i::Smi::cast(*obj)->value();
3844   } else {
3845     return static_cast<int64_t>(obj->Number());
3846   }
3847 }
3848
3849
3850 int32_t Int32::Value() const {
3851   if (IsDeadCheck(i::Isolate::Current(), "v8::Int32::Value()")) return 0;
3852   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3853   if (obj->IsSmi()) {
3854     return i::Smi::cast(*obj)->value();
3855   } else {
3856     return static_cast<int32_t>(obj->Number());
3857   }
3858 }
3859
3860
3861 uint32_t Uint32::Value() const {
3862   if (IsDeadCheck(i::Isolate::Current(), "v8::Uint32::Value()")) return 0;
3863   i::Handle<i::Object> obj = Utils::OpenHandle(this);
3864   if (obj->IsSmi()) {
3865     return i::Smi::cast(*obj)->value();
3866   } else {
3867     return static_cast<uint32_t>(obj->Number());
3868   }
3869 }
3870
3871
3872 int v8::Object::InternalFieldCount() {
3873   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3874   if (IsDeadCheck(obj->GetIsolate(), "v8::Object::InternalFieldCount()")) {
3875     return 0;
3876   }
3877   return obj->GetInternalFieldCount();
3878 }
3879
3880
3881 Local<Value> v8::Object::CheckedGetInternalField(int index) {
3882   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3883   if (IsDeadCheck(obj->GetIsolate(), "v8::Object::GetInternalField()")) {
3884     return Local<Value>();
3885   }
3886   if (!ApiCheck(index < obj->GetInternalFieldCount(),
3887                 "v8::Object::GetInternalField()",
3888                 "Reading internal field out of bounds")) {
3889     return Local<Value>();
3890   }
3891   i::Handle<i::Object> value(obj->GetInternalField(index));
3892   Local<Value> result = Utils::ToLocal(value);
3893 #ifdef DEBUG
3894   Local<Value> unchecked = UncheckedGetInternalField(index);
3895   ASSERT(unchecked.IsEmpty() || (unchecked == result));
3896 #endif
3897   return result;
3898 }
3899
3900
3901 void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
3902   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3903   i::Isolate* isolate = obj->GetIsolate();
3904   if (IsDeadCheck(isolate, "v8::Object::SetInternalField()")) {
3905     return;
3906   }
3907   if (!ApiCheck(index < obj->GetInternalFieldCount(),
3908                 "v8::Object::SetInternalField()",
3909                 "Writing internal field out of bounds")) {
3910     return;
3911   }
3912   ENTER_V8(isolate);
3913   i::Handle<i::Object> val = Utils::OpenHandle(*value);
3914   obj->SetInternalField(index, *val);
3915 }
3916
3917
3918 static bool CanBeEncodedAsSmi(void* ptr) {
3919   const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
3920   return ((address & i::kEncodablePointerMask) == 0);
3921 }
3922
3923
3924 static i::Smi* EncodeAsSmi(void* ptr) {
3925   ASSERT(CanBeEncodedAsSmi(ptr));
3926   const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
3927   i::Smi* result = reinterpret_cast<i::Smi*>(address << i::kPointerToSmiShift);
3928   ASSERT(i::Internals::HasSmiTag(result));
3929   ASSERT_EQ(result, i::Smi::FromInt(result->value()));
3930   ASSERT_EQ(ptr, i::Internals::GetExternalPointerFromSmi(result));
3931   return result;
3932 }
3933
3934
3935 void v8::Object::SetPointerInInternalField(int index, void* value) {
3936   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3937   ENTER_V8(isolate);
3938   if (CanBeEncodedAsSmi(value)) {
3939     Utils::OpenHandle(this)->SetInternalField(index, EncodeAsSmi(value));
3940   } else {
3941     HandleScope scope;
3942     i::Handle<i::Foreign> foreign =
3943         isolate->factory()->NewForeign(
3944             reinterpret_cast<i::Address>(value), i::TENURED);
3945     if (!foreign.is_null())
3946         Utils::OpenHandle(this)->SetInternalField(index, *foreign);
3947   }
3948   ASSERT_EQ(value, GetPointerFromInternalField(index));
3949 }
3950
3951
3952 // --- E n v i r o n m e n t ---
3953
3954
3955 bool v8::V8::Initialize() {
3956   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
3957   if (isolate != NULL && isolate->IsInitialized()) {
3958     return true;
3959   }
3960   return InitializeHelper();
3961 }
3962
3963
3964 void v8::V8::SetEntropySource(EntropySource source) {
3965   i::V8::SetEntropySource(source);
3966 }
3967
3968
3969 bool v8::V8::Dispose() {
3970   i::Isolate* isolate = i::Isolate::Current();
3971   if (!ApiCheck(isolate != NULL && isolate->IsDefaultIsolate(),
3972                 "v8::V8::Dispose()",
3973                 "Use v8::Isolate::Dispose() for a non-default isolate.")) {
3974     return false;
3975   }
3976   i::V8::TearDown();
3977   return true;
3978 }
3979
3980
3981 HeapStatistics::HeapStatistics(): total_heap_size_(0),
3982                                   total_heap_size_executable_(0),
3983                                   used_heap_size_(0),
3984                                   heap_size_limit_(0) { }
3985
3986
3987 void v8::V8::GetHeapStatistics(HeapStatistics* heap_statistics) {
3988   if (!i::Isolate::Current()->IsInitialized()) {
3989     // Isolate is unitialized thus heap is not configured yet.
3990     heap_statistics->set_total_heap_size(0);
3991     heap_statistics->set_total_heap_size_executable(0);
3992     heap_statistics->set_used_heap_size(0);
3993     heap_statistics->set_heap_size_limit(0);
3994     return;
3995   }
3996
3997   i::Heap* heap = i::Isolate::Current()->heap();
3998   heap_statistics->set_total_heap_size(heap->CommittedMemory());
3999   heap_statistics->set_total_heap_size_executable(
4000       heap->CommittedMemoryExecutable());
4001   heap_statistics->set_used_heap_size(heap->SizeOfObjects());
4002   heap_statistics->set_heap_size_limit(heap->MaxReserved());
4003 }
4004
4005
4006 bool v8::V8::IdleNotification() {
4007   // Returning true tells the caller that it need not
4008   // continue to call IdleNotification.
4009   i::Isolate* isolate = i::Isolate::Current();
4010   if (isolate == NULL || !isolate->IsInitialized()) return true;
4011   return i::V8::IdleNotification();
4012 }
4013
4014
4015 void v8::V8::LowMemoryNotification() {
4016   i::Isolate* isolate = i::Isolate::Current();
4017   if (isolate == NULL || !isolate->IsInitialized()) return;
4018   isolate->heap()->CollectAllAvailableGarbage();
4019 }
4020
4021
4022 int v8::V8::ContextDisposedNotification() {
4023   i::Isolate* isolate = i::Isolate::Current();
4024   if (!isolate->IsInitialized()) return 0;
4025   return isolate->heap()->NotifyContextDisposed();
4026 }
4027
4028
4029 const char* v8::V8::GetVersion() {
4030   return i::Version::GetVersion();
4031 }
4032
4033
4034 static i::Handle<i::FunctionTemplateInfo>
4035     EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
4036   if (templ->constructor()->IsUndefined()) {
4037     Local<FunctionTemplate> constructor = FunctionTemplate::New();
4038     Utils::OpenHandle(*constructor)->set_instance_template(*templ);
4039     templ->set_constructor(*Utils::OpenHandle(*constructor));
4040   }
4041   return i::Handle<i::FunctionTemplateInfo>(
4042     i::FunctionTemplateInfo::cast(templ->constructor()));
4043 }
4044
4045
4046 Persistent<Context> v8::Context::New(
4047     v8::ExtensionConfiguration* extensions,
4048     v8::Handle<ObjectTemplate> global_template,
4049     v8::Handle<Value> global_object) {
4050   i::Isolate* isolate = i::Isolate::Current();
4051   EnsureInitializedForIsolate(isolate, "v8::Context::New()");
4052   LOG_API(isolate, "Context::New");
4053   ON_BAILOUT(isolate, "v8::Context::New()", return Persistent<Context>());
4054
4055   // Enter V8 via an ENTER_V8 scope.
4056   i::Handle<i::Context> env;
4057   {
4058     ENTER_V8(isolate);
4059     v8::Handle<ObjectTemplate> proxy_template = global_template;
4060     i::Handle<i::FunctionTemplateInfo> proxy_constructor;
4061     i::Handle<i::FunctionTemplateInfo> global_constructor;
4062
4063     if (!global_template.IsEmpty()) {
4064       // Make sure that the global_template has a constructor.
4065       global_constructor =
4066           EnsureConstructor(Utils::OpenHandle(*global_template));
4067
4068       // Create a fresh template for the global proxy object.
4069       proxy_template = ObjectTemplate::New();
4070       proxy_constructor =
4071           EnsureConstructor(Utils::OpenHandle(*proxy_template));
4072
4073       // Set the global template to be the prototype template of
4074       // global proxy template.
4075       proxy_constructor->set_prototype_template(
4076           *Utils::OpenHandle(*global_template));
4077
4078       // Migrate security handlers from global_template to
4079       // proxy_template.  Temporarily removing access check
4080       // information from the global template.
4081       if (!global_constructor->access_check_info()->IsUndefined()) {
4082         proxy_constructor->set_access_check_info(
4083             global_constructor->access_check_info());
4084         proxy_constructor->set_needs_access_check(
4085             global_constructor->needs_access_check());
4086         global_constructor->set_needs_access_check(false);
4087         global_constructor->set_access_check_info(
4088             isolate->heap()->undefined_value());
4089       }
4090     }
4091
4092     // Create the environment.
4093     env = isolate->bootstrapper()->CreateEnvironment(
4094         isolate,
4095         Utils::OpenHandle(*global_object),
4096         proxy_template,
4097         extensions);
4098
4099     // Restore the access check info on the global template.
4100     if (!global_template.IsEmpty()) {
4101       ASSERT(!global_constructor.is_null());
4102       ASSERT(!proxy_constructor.is_null());
4103       global_constructor->set_access_check_info(
4104           proxy_constructor->access_check_info());
4105       global_constructor->set_needs_access_check(
4106           proxy_constructor->needs_access_check());
4107     }
4108     isolate->runtime_profiler()->Reset();
4109   }
4110   // Leave V8.
4111
4112   if (env.is_null()) {
4113     return Persistent<Context>();
4114   }
4115   return Persistent<Context>(Utils::ToLocal(env));
4116 }
4117
4118
4119 void v8::Context::SetSecurityToken(Handle<Value> token) {
4120   i::Isolate* isolate = i::Isolate::Current();
4121   if (IsDeadCheck(isolate, "v8::Context::SetSecurityToken()")) {
4122     return;
4123   }
4124   ENTER_V8(isolate);
4125   i::Handle<i::Context> env = Utils::OpenHandle(this);
4126   i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
4127   env->set_security_token(*token_handle);
4128 }
4129
4130
4131 void v8::Context::UseDefaultSecurityToken() {
4132   i::Isolate* isolate = i::Isolate::Current();
4133   if (IsDeadCheck(isolate,
4134                   "v8::Context::UseDefaultSecurityToken()")) {
4135     return;
4136   }
4137   ENTER_V8(isolate);
4138   i::Handle<i::Context> env = Utils::OpenHandle(this);
4139   env->set_security_token(env->global());
4140 }
4141
4142
4143 Handle<Value> v8::Context::GetSecurityToken() {
4144   i::Isolate* isolate = i::Isolate::Current();
4145   if (IsDeadCheck(isolate, "v8::Context::GetSecurityToken()")) {
4146     return Handle<Value>();
4147   }
4148   i::Handle<i::Context> env = Utils::OpenHandle(this);
4149   i::Object* security_token = env->security_token();
4150   i::Handle<i::Object> token_handle(security_token);
4151   return Utils::ToLocal(token_handle);
4152 }
4153
4154
4155 bool Context::HasOutOfMemoryException() {
4156   i::Handle<i::Context> env = Utils::OpenHandle(this);
4157   return env->has_out_of_memory();
4158 }
4159
4160
4161 bool Context::InContext() {
4162   return i::Isolate::Current()->context() != NULL;
4163 }
4164
4165
4166 v8::Local<v8::Context> Context::GetEntered() {
4167   i::Isolate* isolate = i::Isolate::Current();
4168   if (!EnsureInitializedForIsolate(isolate, "v8::Context::GetEntered()")) {
4169     return Local<Context>();
4170   }
4171   i::Handle<i::Object> last =
4172       isolate->handle_scope_implementer()->LastEnteredContext();
4173   if (last.is_null()) return Local<Context>();
4174   i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
4175   return Utils::ToLocal(context);
4176 }
4177
4178
4179 v8::Local<v8::Context> Context::GetCurrent() {
4180   i::Isolate* isolate = i::Isolate::Current();
4181   if (IsDeadCheck(isolate, "v8::Context::GetCurrent()")) {
4182     return Local<Context>();
4183   }
4184   i::Handle<i::Object> current = isolate->global_context();
4185   if (current.is_null()) return Local<Context>();
4186   i::Handle<i::Context> context = i::Handle<i::Context>::cast(current);
4187   return Utils::ToLocal(context);
4188 }
4189
4190
4191 v8::Local<v8::Context> Context::GetCalling() {
4192   i::Isolate* isolate = i::Isolate::Current();
4193   if (IsDeadCheck(isolate, "v8::Context::GetCalling()")) {
4194     return Local<Context>();
4195   }
4196   i::Handle<i::Object> calling =
4197       isolate->GetCallingGlobalContext();
4198   if (calling.is_null()) return Local<Context>();
4199   i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
4200   return Utils::ToLocal(context);
4201 }
4202
4203
4204 v8::Local<v8::Object> Context::Global() {
4205   if (IsDeadCheck(i::Isolate::Current(), "v8::Context::Global()")) {
4206     return Local<v8::Object>();
4207   }
4208   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4209   i::Handle<i::Context> context =
4210       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4211   i::Handle<i::Object> global(context->global_proxy());
4212   return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
4213 }
4214
4215
4216 void Context::DetachGlobal() {
4217   i::Isolate* isolate = i::Isolate::Current();
4218   if (IsDeadCheck(isolate, "v8::Context::DetachGlobal()")) return;
4219   ENTER_V8(isolate);
4220   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4221   i::Handle<i::Context> context =
4222       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4223   isolate->bootstrapper()->DetachGlobal(context);
4224 }
4225
4226
4227 void Context::ReattachGlobal(Handle<Object> global_object) {
4228   i::Isolate* isolate = i::Isolate::Current();
4229   if (IsDeadCheck(isolate, "v8::Context::ReattachGlobal()")) return;
4230   ENTER_V8(isolate);
4231   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4232   i::Handle<i::Context> context =
4233       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4234   isolate->bootstrapper()->ReattachGlobal(
4235       context,
4236       Utils::OpenHandle(*global_object));
4237 }
4238
4239
4240 void Context::AllowCodeGenerationFromStrings(bool allow) {
4241   i::Isolate* isolate = i::Isolate::Current();
4242   if (IsDeadCheck(isolate, "v8::Context::AllowCodeGenerationFromStrings()")) {
4243     return;
4244   }
4245   ENTER_V8(isolate);
4246   i::Object** ctx = reinterpret_cast<i::Object**>(this);
4247   i::Handle<i::Context> context =
4248       i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4249   context->set_allow_code_gen_from_strings(
4250       allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
4251 }
4252
4253
4254 void V8::SetWrapperClassId(i::Object** global_handle, uint16_t class_id) {
4255   i::GlobalHandles::SetWrapperClassId(global_handle, class_id);
4256 }
4257
4258
4259 Local<v8::Object> ObjectTemplate::NewInstance() {
4260   i::Isolate* isolate = i::Isolate::Current();
4261   ON_BAILOUT(isolate, "v8::ObjectTemplate::NewInstance()",
4262              return Local<v8::Object>());
4263   LOG_API(isolate, "ObjectTemplate::NewInstance");
4264   ENTER_V8(isolate);
4265   EXCEPTION_PREAMBLE(isolate);
4266   i::Handle<i::Object> obj =
4267       i::Execution::InstantiateObject(Utils::OpenHandle(this),
4268                                       &has_pending_exception);
4269   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
4270   return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
4271 }
4272
4273
4274 Local<v8::Function> FunctionTemplate::GetFunction() {
4275   i::Isolate* isolate = i::Isolate::Current();
4276   ON_BAILOUT(isolate, "v8::FunctionTemplate::GetFunction()",
4277              return Local<v8::Function>());
4278   LOG_API(isolate, "FunctionTemplate::GetFunction");
4279   ENTER_V8(isolate);
4280   EXCEPTION_PREAMBLE(isolate);
4281   i::Handle<i::Object> obj =
4282       i::Execution::InstantiateFunction(Utils::OpenHandle(this),
4283                                         &has_pending_exception);
4284   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Function>());
4285   return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
4286 }
4287
4288
4289 bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
4290   ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
4291              return false);
4292   i::Object* obj = *Utils::OpenHandle(*value);
4293   return obj->IsInstanceOf(*Utils::OpenHandle(this));
4294 }
4295
4296
4297 static Local<External> ExternalNewImpl(void* data) {
4298   return Utils::ToLocal(FACTORY->NewForeign(static_cast<i::Address>(data)));
4299 }
4300
4301 static void* ExternalValueImpl(i::Handle<i::Object> obj) {
4302   return reinterpret_cast<void*>(i::Foreign::cast(*obj)->foreign_address());
4303 }
4304
4305
4306 Local<Value> v8::External::Wrap(void* data) {
4307   i::Isolate* isolate = i::Isolate::Current();
4308   STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4309   EnsureInitializedForIsolate(isolate, "v8::External::Wrap()");
4310   LOG_API(isolate, "External::Wrap");
4311   ENTER_V8(isolate);
4312
4313   v8::Local<v8::Value> result = CanBeEncodedAsSmi(data)
4314       ? Utils::ToLocal(i::Handle<i::Object>(EncodeAsSmi(data)))
4315       : v8::Local<v8::Value>(ExternalNewImpl(data));
4316
4317   ASSERT_EQ(data, Unwrap(result));
4318   return result;
4319 }
4320
4321
4322 void* v8::Object::SlowGetPointerFromInternalField(int index) {
4323   i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4324   i::Object* value = obj->GetInternalField(index);
4325   if (value->IsSmi()) {
4326     return i::Internals::GetExternalPointerFromSmi(value);
4327   } else if (value->IsForeign()) {
4328     return reinterpret_cast<void*>(i::Foreign::cast(value)->foreign_address());
4329   } else {
4330     return NULL;
4331   }
4332 }
4333
4334
4335 void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
4336   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Unwrap()")) return 0;
4337   i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
4338   void* result;
4339   if (obj->IsSmi()) {
4340     result = i::Internals::GetExternalPointerFromSmi(*obj);
4341   } else if (obj->IsForeign()) {
4342     result = ExternalValueImpl(obj);
4343   } else {
4344     result = NULL;
4345   }
4346   ASSERT_EQ(result, QuickUnwrap(wrapper));
4347   return result;
4348 }
4349
4350
4351 Local<External> v8::External::New(void* data) {
4352   STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4353   i::Isolate* isolate = i::Isolate::Current();
4354   EnsureInitializedForIsolate(isolate, "v8::External::New()");
4355   LOG_API(isolate, "External::New");
4356   ENTER_V8(isolate);
4357   return ExternalNewImpl(data);
4358 }
4359
4360
4361 void* External::Value() const {
4362   if (IsDeadCheck(i::Isolate::Current(), "v8::External::Value()")) return 0;
4363   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4364   return ExternalValueImpl(obj);
4365 }
4366
4367
4368 Local<String> v8::String::Empty() {
4369   i::Isolate* isolate = i::Isolate::Current();
4370   EnsureInitializedForIsolate(isolate, "v8::String::Empty()");
4371   LOG_API(isolate, "String::Empty()");
4372   return Utils::ToLocal(isolate->factory()->empty_symbol());
4373 }
4374
4375
4376 Local<String> v8::String::New(const char* data, int length) {
4377   i::Isolate* isolate = i::Isolate::Current();
4378   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4379   LOG_API(isolate, "String::New(char)");
4380   if (length == 0) return Empty();
4381   ENTER_V8(isolate);
4382   if (length == -1) length = i::StrLength(data);
4383   i::Handle<i::String> result =
4384       isolate->factory()->NewStringFromUtf8(
4385           i::Vector<const char>(data, length));
4386   return Utils::ToLocal(result);
4387 }
4388
4389
4390 Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
4391   i::Handle<i::String> left_string = Utils::OpenHandle(*left);
4392   i::Isolate* isolate = left_string->GetIsolate();
4393   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4394   LOG_API(isolate, "String::New(char)");
4395   ENTER_V8(isolate);
4396   i::Handle<i::String> right_string = Utils::OpenHandle(*right);
4397   i::Handle<i::String> result = isolate->factory()->NewConsString(left_string,
4398                                                                   right_string);
4399   return Utils::ToLocal(result);
4400 }
4401
4402
4403 Local<String> v8::String::NewUndetectable(const char* data, int length) {
4404   i::Isolate* isolate = i::Isolate::Current();
4405   EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4406   LOG_API(isolate, "String::NewUndetectable(char)");
4407   ENTER_V8(isolate);
4408   if (length == -1) length = i::StrLength(data);
4409   i::Handle<i::String> result =
4410       isolate->factory()->NewStringFromUtf8(
4411           i::Vector<const char>(data, length));
4412   result->MarkAsUndetectable();
4413   return Utils::ToLocal(result);
4414 }
4415
4416
4417 static int TwoByteStringLength(const uint16_t* data) {
4418   int length = 0;
4419   while (data[length] != '\0') length++;
4420   return length;
4421 }
4422
4423
4424 Local<String> v8::String::New(const uint16_t* data, int length) {
4425   i::Isolate* isolate = i::Isolate::Current();
4426   EnsureInitializedForIsolate(isolate, "v8::String::New()");
4427   LOG_API(isolate, "String::New(uint16_)");
4428   if (length == 0) return Empty();
4429   ENTER_V8(isolate);
4430   if (length == -1) length = TwoByteStringLength(data);
4431   i::Handle<i::String> result =
4432       isolate->factory()->NewStringFromTwoByte(
4433           i::Vector<const uint16_t>(data, length));
4434   return Utils::ToLocal(result);
4435 }
4436
4437
4438 Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
4439   i::Isolate* isolate = i::Isolate::Current();
4440   EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4441   LOG_API(isolate, "String::NewUndetectable(uint16_)");
4442   ENTER_V8(isolate);
4443   if (length == -1) length = TwoByteStringLength(data);
4444   i::Handle<i::String> result =
4445       isolate->factory()->NewStringFromTwoByte(
4446           i::Vector<const uint16_t>(data, length));
4447   result->MarkAsUndetectable();
4448   return Utils::ToLocal(result);
4449 }
4450
4451
4452 i::Handle<i::String> NewExternalStringHandle(i::Isolate* isolate,
4453       v8::String::ExternalStringResource* resource) {
4454   i::Handle<i::String> result =
4455       isolate->factory()->NewExternalStringFromTwoByte(resource);
4456   return result;
4457 }
4458
4459
4460 i::Handle<i::String> NewExternalAsciiStringHandle(i::Isolate* isolate,
4461       v8::String::ExternalAsciiStringResource* resource) {
4462   i::Handle<i::String> result =
4463       isolate->factory()->NewExternalStringFromAscii(resource);
4464   return result;
4465 }
4466
4467
4468 Local<String> v8::String::NewExternal(
4469       v8::String::ExternalStringResource* resource) {
4470   i::Isolate* isolate = i::Isolate::Current();
4471   EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4472   LOG_API(isolate, "String::NewExternal");
4473   ENTER_V8(isolate);
4474   i::Handle<i::String> result = NewExternalStringHandle(isolate, resource);
4475   isolate->heap()->external_string_table()->AddString(*result);
4476   return Utils::ToLocal(result);
4477 }
4478
4479
4480 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
4481   i::Handle<i::String> obj = Utils::OpenHandle(this);
4482   i::Isolate* isolate = obj->GetIsolate();
4483   if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4484   if (i::StringShape(*obj).IsExternalTwoByte()) {
4485     return false;  // Already an external string.
4486   }
4487   ENTER_V8(isolate);
4488   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4489     return false;
4490   }
4491   if (isolate->heap()->IsInGCPostProcessing()) {
4492     return false;
4493   }
4494   bool result = obj->MakeExternal(resource);
4495   if (result && !obj->IsSymbol()) {
4496     isolate->heap()->external_string_table()->AddString(*obj);
4497   }
4498   return result;
4499 }
4500
4501
4502 Local<String> v8::String::NewExternal(
4503       v8::String::ExternalAsciiStringResource* resource) {
4504   i::Isolate* isolate = i::Isolate::Current();
4505   EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4506   LOG_API(isolate, "String::NewExternal");
4507   ENTER_V8(isolate);
4508   i::Handle<i::String> result = NewExternalAsciiStringHandle(isolate, resource);
4509   isolate->heap()->external_string_table()->AddString(*result);
4510   return Utils::ToLocal(result);
4511 }
4512
4513
4514 bool v8::String::MakeExternal(
4515     v8::String::ExternalAsciiStringResource* resource) {
4516   i::Handle<i::String> obj = Utils::OpenHandle(this);
4517   i::Isolate* isolate = obj->GetIsolate();
4518   if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4519   if (i::StringShape(*obj).IsExternalTwoByte()) {
4520     return false;  // Already an external string.
4521   }
4522   ENTER_V8(isolate);
4523   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4524     return false;
4525   }
4526   if (isolate->heap()->IsInGCPostProcessing()) {
4527     return false;
4528   }
4529   bool result = obj->MakeExternal(resource);
4530   if (result && !obj->IsSymbol()) {
4531     isolate->heap()->external_string_table()->AddString(*obj);
4532   }
4533   return result;
4534 }
4535
4536
4537 bool v8::String::CanMakeExternal() {
4538   if (!internal::FLAG_clever_optimizations) return false;
4539   i::Handle<i::String> obj = Utils::OpenHandle(this);
4540   i::Isolate* isolate = obj->GetIsolate();
4541   if (IsDeadCheck(isolate, "v8::String::CanMakeExternal()")) return false;
4542   if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4543     return false;
4544   }
4545   int size = obj->Size();  // Byte size of the original string.
4546   if (size < i::ExternalString::kSize)
4547     return false;
4548   i::StringShape shape(*obj);
4549   return !shape.IsExternal();
4550 }
4551
4552
4553 Local<v8::Object> v8::Object::New() {
4554   i::Isolate* isolate = i::Isolate::Current();
4555   EnsureInitializedForIsolate(isolate, "v8::Object::New()");
4556   LOG_API(isolate, "Object::New");
4557   ENTER_V8(isolate);
4558   i::Handle<i::JSObject> obj =
4559       isolate->factory()->NewJSObject(isolate->object_function());
4560   return Utils::ToLocal(obj);
4561 }
4562
4563
4564 Local<v8::Value> v8::NumberObject::New(double value) {
4565   i::Isolate* isolate = i::Isolate::Current();
4566   EnsureInitializedForIsolate(isolate, "v8::NumberObject::New()");
4567   LOG_API(isolate, "NumberObject::New");
4568   ENTER_V8(isolate);
4569   i::Handle<i::Object> number = isolate->factory()->NewNumber(value);
4570   i::Handle<i::Object> obj = isolate->factory()->ToObject(number);
4571   return Utils::ToLocal(obj);
4572 }
4573
4574
4575 double v8::NumberObject::NumberValue() const {
4576   i::Isolate* isolate = i::Isolate::Current();
4577   if (IsDeadCheck(isolate, "v8::NumberObject::NumberValue()")) return 0;
4578   LOG_API(isolate, "NumberObject::NumberValue");
4579   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4580   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4581   return jsvalue->value()->Number();
4582 }
4583
4584
4585 Local<v8::Value> v8::BooleanObject::New(bool value) {
4586   i::Isolate* isolate = i::Isolate::Current();
4587   EnsureInitializedForIsolate(isolate, "v8::BooleanObject::New()");
4588   LOG_API(isolate, "BooleanObject::New");
4589   ENTER_V8(isolate);
4590   i::Handle<i::Object> boolean(value ? isolate->heap()->true_value()
4591                                      : isolate->heap()->false_value());
4592   i::Handle<i::Object> obj = isolate->factory()->ToObject(boolean);
4593   return Utils::ToLocal(obj);
4594 }
4595
4596
4597 bool v8::BooleanObject::BooleanValue() const {
4598   i::Isolate* isolate = i::Isolate::Current();
4599   if (IsDeadCheck(isolate, "v8::BooleanObject::BooleanValue()")) return 0;
4600   LOG_API(isolate, "BooleanObject::BooleanValue");
4601   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4602   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4603   return jsvalue->value()->IsTrue();
4604 }
4605
4606
4607 Local<v8::Value> v8::StringObject::New(Handle<String> value) {
4608   i::Isolate* isolate = i::Isolate::Current();
4609   EnsureInitializedForIsolate(isolate, "v8::StringObject::New()");
4610   LOG_API(isolate, "StringObject::New");
4611   ENTER_V8(isolate);
4612   i::Handle<i::Object> obj =
4613       isolate->factory()->ToObject(Utils::OpenHandle(*value));
4614   return Utils::ToLocal(obj);
4615 }
4616
4617
4618 Local<v8::String> v8::StringObject::StringValue() const {
4619   i::Isolate* isolate = i::Isolate::Current();
4620   if (IsDeadCheck(isolate, "v8::StringObject::StringValue()")) {
4621     return Local<v8::String>();
4622   }
4623   LOG_API(isolate, "StringObject::StringValue");
4624   i::Handle<i::Object> obj = Utils::OpenHandle(this);
4625   i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4626   return Utils::ToLocal(
4627       i::Handle<i::String>(i::String::cast(jsvalue->value())));
4628 }
4629
4630
4631 Local<v8::Value> v8::Date::New(double time) {
4632   i::Isolate* isolate = i::Isolate::Current();
4633   EnsureInitializedForIsolate(isolate, "v8::Date::New()");
4634   LOG_API(isolate, "Date::New");
4635   if (isnan(time)) {
4636     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4637     time = i::OS::nan_value();
4638   }
4639   ENTER_V8(isolate);
4640   EXCEPTION_PREAMBLE(isolate);
4641   i::Handle<i::Object> obj =
4642       i::Execution::NewDate(time, &has_pending_exception);
4643   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Value>());
4644   return Utils::ToLocal(obj);
4645 }
4646
4647
4648 double v8::Date::NumberValue() const {
4649   i::Isolate* isolate = i::Isolate::Current();
4650   if (IsDeadCheck(isolate, "v8::Date::NumberValue()")) return 0;
4651   LOG_API(isolate, "Date::NumberValue");
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()->Number();
4655 }
4656
4657
4658 void v8::Date::DateTimeConfigurationChangeNotification() {
4659   i::Isolate* isolate = i::Isolate::Current();
4660   ON_BAILOUT(isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
4661              return);
4662   LOG_API(isolate, "Date::DateTimeConfigurationChangeNotification");
4663   ENTER_V8(isolate);
4664
4665   i::HandleScope scope(isolate);
4666   // Get the function ResetDateCache (defined in date-delay.js).
4667   i::Handle<i::String> func_name_str =
4668       isolate->factory()->LookupAsciiSymbol("ResetDateCache");
4669   i::MaybeObject* result =
4670       isolate->js_builtins_object()->GetProperty(*func_name_str);
4671   i::Object* object_func;
4672   if (!result->ToObject(&object_func)) {
4673     return;
4674   }
4675
4676   if (object_func->IsJSFunction()) {
4677     i::Handle<i::JSFunction> func =
4678         i::Handle<i::JSFunction>(i::JSFunction::cast(object_func));
4679
4680     // Call ResetDateCache(0 but expect no exceptions:
4681     bool caught_exception = false;
4682     i::Execution::TryCall(func,
4683                           isolate->js_builtins_object(),
4684                           0,
4685                           NULL,
4686                           &caught_exception);
4687   }
4688 }
4689
4690
4691 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
4692   char flags_buf[3];
4693   int num_flags = 0;
4694   if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
4695   if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
4696   if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
4697   ASSERT(num_flags <= static_cast<int>(ARRAY_SIZE(flags_buf)));
4698   return FACTORY->LookupSymbol(
4699       i::Vector<const char>(flags_buf, num_flags));
4700 }
4701
4702
4703 Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
4704                                   Flags flags) {
4705   i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
4706   EnsureInitializedForIsolate(isolate, "v8::RegExp::New()");
4707   LOG_API(isolate, "RegExp::New");
4708   ENTER_V8(isolate);
4709   EXCEPTION_PREAMBLE(isolate);
4710   i::Handle<i::JSRegExp> obj = i::Execution::NewJSRegExp(
4711       Utils::OpenHandle(*pattern),
4712       RegExpFlagsToString(flags),
4713       &has_pending_exception);
4714   EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::RegExp>());
4715   return Utils::ToLocal(i::Handle<i::JSRegExp>::cast(obj));
4716 }
4717
4718
4719 Local<v8::String> v8::RegExp::GetSource() const {
4720   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4721   if (IsDeadCheck(isolate, "v8::RegExp::GetSource()")) {
4722     return Local<v8::String>();
4723   }
4724   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4725   return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
4726 }
4727
4728
4729 // Assert that the static flags cast in GetFlags is valid.
4730 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag)        \
4731   STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) ==     \
4732                 static_cast<int>(i::JSRegExp::internal_flag))
4733 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
4734 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
4735 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
4736 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
4737 #undef REGEXP_FLAG_ASSERT_EQ
4738
4739 v8::RegExp::Flags v8::RegExp::GetFlags() const {
4740   if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::GetFlags()")) {
4741     return v8::RegExp::kNone;
4742   }
4743   i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4744   return static_cast<RegExp::Flags>(obj->GetFlags().value());
4745 }
4746
4747
4748 Local<v8::Array> v8::Array::New(int length) {
4749   i::Isolate* isolate = i::Isolate::Current();
4750   EnsureInitializedForIsolate(isolate, "v8::Array::New()");
4751   LOG_API(isolate, "Array::New");
4752   ENTER_V8(isolate);
4753   int real_length = length > 0 ? length : 0;
4754   i::Handle<i::JSArray> obj = isolate->factory()->NewJSArray(real_length);
4755   i::Handle<i::Object> length_obj =
4756       isolate->factory()->NewNumberFromInt(real_length);
4757   obj->set_length(*length_obj);
4758   return Utils::ToLocal(obj);
4759 }
4760
4761
4762 uint32_t v8::Array::Length() const {
4763   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4764   if (IsDeadCheck(isolate, "v8::Array::Length()")) return 0;
4765   i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
4766   i::Object* length = obj->length();
4767   if (length->IsSmi()) {
4768     return i::Smi::cast(length)->value();
4769   } else {
4770     return static_cast<uint32_t>(length->Number());
4771   }
4772 }
4773
4774
4775 Local<Object> Array::CloneElementAt(uint32_t index) {
4776   i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4777   ON_BAILOUT(isolate, "v8::Array::CloneElementAt()", return Local<Object>());
4778   i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4779   if (!self->HasFastElements()) {
4780     return Local<Object>();
4781   }
4782   i::FixedArray* elms = i::FixedArray::cast(self->elements());
4783   i::Object* paragon = elms->get(index);
4784   if (!paragon->IsJSObject()) {
4785     return Local<Object>();
4786   }
4787   i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
4788   EXCEPTION_PREAMBLE(isolate);
4789   ENTER_V8(isolate);
4790   i::Handle<i::JSObject> result = i::Copy(paragon_handle);
4791   has_pending_exception = result.is_null();
4792   EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
4793   return Utils::ToLocal(result);
4794 }
4795
4796
4797 Local<String> v8::String::NewSymbol(const char* data, int length) {
4798   i::Isolate* isolate = i::Isolate::Current();
4799   EnsureInitializedForIsolate(isolate, "v8::String::NewSymbol()");
4800   LOG_API(isolate, "String::NewSymbol(char)");
4801   ENTER_V8(isolate);
4802   if (length == -1) length = i::StrLength(data);
4803   i::Handle<i::String> result =
4804       isolate->factory()->LookupSymbol(i::Vector<const char>(data, length));
4805   return Utils::ToLocal(result);
4806 }
4807
4808
4809 Local<Number> v8::Number::New(double value) {
4810   i::Isolate* isolate = i::Isolate::Current();
4811   EnsureInitializedForIsolate(isolate, "v8::Number::New()");
4812   if (isnan(value)) {
4813     // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4814     value = i::OS::nan_value();
4815   }
4816   ENTER_V8(isolate);
4817   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4818   return Utils::NumberToLocal(result);
4819 }
4820
4821
4822 Local<Integer> v8::Integer::New(int32_t value) {
4823   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4824   EnsureInitializedForIsolate(isolate, "v8::Integer::New()");
4825   if (i::Smi::IsValid(value)) {
4826     return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
4827                                                       isolate));
4828   }
4829   ENTER_V8(isolate);
4830   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4831   return Utils::IntegerToLocal(result);
4832 }
4833
4834
4835 Local<Integer> Integer::NewFromUnsigned(uint32_t value) {
4836   bool fits_into_int32_t = (value & (1 << 31)) == 0;
4837   if (fits_into_int32_t) {
4838     return Integer::New(static_cast<int32_t>(value));
4839   }
4840   i::Isolate* isolate = i::Isolate::Current();
4841   ENTER_V8(isolate);
4842   i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4843   return Utils::IntegerToLocal(result);
4844 }
4845
4846
4847 void V8::IgnoreOutOfMemoryException() {
4848   EnterIsolateIfNeeded()->set_ignore_out_of_memory(true);
4849 }
4850
4851
4852 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
4853   i::Isolate* isolate = i::Isolate::Current();
4854   EnsureInitializedForIsolate(isolate, "v8::V8::AddMessageListener()");
4855   ON_BAILOUT(isolate, "v8::V8::AddMessageListener()", return false);
4856   ENTER_V8(isolate);
4857   i::HandleScope scope(isolate);
4858   NeanderArray listeners(isolate->factory()->message_listeners());
4859   NeanderObject obj(2);
4860   obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
4861   obj.set(1, data.IsEmpty() ?
4862              isolate->heap()->undefined_value() :
4863              *Utils::OpenHandle(*data));
4864   listeners.add(obj.value());
4865   return true;
4866 }
4867
4868
4869 void V8::RemoveMessageListeners(MessageCallback that) {
4870   i::Isolate* isolate = i::Isolate::Current();
4871   EnsureInitializedForIsolate(isolate, "v8::V8::RemoveMessageListener()");
4872   ON_BAILOUT(isolate, "v8::V8::RemoveMessageListeners()", return);
4873   ENTER_V8(isolate);
4874   i::HandleScope scope(isolate);
4875   NeanderArray listeners(isolate->factory()->message_listeners());
4876   for (int i = 0; i < listeners.length(); i++) {
4877     if (listeners.get(i)->IsUndefined()) continue;  // skip deleted ones
4878
4879     NeanderObject listener(i::JSObject::cast(listeners.get(i)));
4880     i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
4881     if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
4882       listeners.set(i, isolate->heap()->undefined_value());
4883     }
4884   }
4885 }
4886
4887
4888 void V8::SetCaptureStackTraceForUncaughtExceptions(
4889       bool capture,
4890       int frame_limit,
4891       StackTrace::StackTraceOptions options) {
4892   i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
4893       capture,
4894       frame_limit,
4895       options);
4896 }
4897
4898
4899 void V8::SetCounterFunction(CounterLookupCallback callback) {
4900   i::Isolate* isolate = EnterIsolateIfNeeded();
4901   if (IsDeadCheck(isolate, "v8::V8::SetCounterFunction()")) return;
4902   isolate->stats_table()->SetCounterFunction(callback);
4903 }
4904
4905 void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
4906   i::Isolate* isolate = EnterIsolateIfNeeded();
4907   if (IsDeadCheck(isolate, "v8::V8::SetCreateHistogramFunction()")) return;
4908   isolate->stats_table()->SetCreateHistogramFunction(callback);
4909 }
4910
4911 void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
4912   i::Isolate* isolate = EnterIsolateIfNeeded();
4913   if (IsDeadCheck(isolate, "v8::V8::SetAddHistogramSampleFunction()")) return;
4914   isolate->stats_table()->
4915       SetAddHistogramSampleFunction(callback);
4916 }
4917
4918 void V8::EnableSlidingStateWindow() {
4919   i::Isolate* isolate = i::Isolate::Current();
4920   if (IsDeadCheck(isolate, "v8::V8::EnableSlidingStateWindow()")) return;
4921   isolate->logger()->EnableSlidingStateWindow();
4922 }
4923
4924
4925 void V8::SetFailedAccessCheckCallbackFunction(
4926       FailedAccessCheckCallback callback) {
4927   i::Isolate* isolate = i::Isolate::Current();
4928   if (IsDeadCheck(isolate, "v8::V8::SetFailedAccessCheckCallbackFunction()")) {
4929     return;
4930   }
4931   isolate->SetFailedAccessCheckCallback(callback);
4932 }
4933
4934 void V8::AddObjectGroup(Persistent<Value>* objects,
4935                         size_t length,
4936                         RetainedObjectInfo* info) {
4937   i::Isolate* isolate = i::Isolate::Current();
4938   if (IsDeadCheck(isolate, "v8::V8::AddObjectGroup()")) return;
4939   STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
4940   isolate->global_handles()->AddObjectGroup(
4941       reinterpret_cast<i::Object***>(objects), length, info);
4942 }
4943
4944
4945 void V8::AddImplicitReferences(Persistent<Object> parent,
4946                                Persistent<Value>* children,
4947                                size_t length) {
4948   i::Isolate* isolate = i::Isolate::Current();
4949   if (IsDeadCheck(isolate, "v8::V8::AddImplicitReferences()")) return;
4950   STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
4951   isolate->global_handles()->AddImplicitReferences(
4952       i::Handle<i::HeapObject>::cast(Utils::OpenHandle(*parent)).location(),
4953       reinterpret_cast<i::Object***>(children), length);
4954 }
4955
4956
4957 int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
4958   i::Isolate* isolate = i::Isolate::Current();
4959   if (IsDeadCheck(isolate, "v8::V8::AdjustAmountOfExternalAllocatedMemory()")) {
4960     return 0;
4961   }
4962   return isolate->heap()->AdjustAmountOfExternalAllocatedMemory(
4963       change_in_bytes);
4964 }
4965
4966
4967 void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
4968   i::Isolate* isolate = i::Isolate::Current();
4969   if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCPrologueCallback()")) return;
4970   isolate->heap()->SetGlobalGCPrologueCallback(callback);
4971 }
4972
4973
4974 void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
4975   i::Isolate* isolate = i::Isolate::Current();
4976   if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCEpilogueCallback()")) return;
4977   isolate->heap()->SetGlobalGCEpilogueCallback(callback);
4978 }
4979
4980
4981 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
4982   i::Isolate* isolate = i::Isolate::Current();
4983   if (IsDeadCheck(isolate, "v8::V8::AddGCPrologueCallback()")) return;
4984   isolate->heap()->AddGCPrologueCallback(callback, gc_type);
4985 }
4986
4987
4988 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
4989   i::Isolate* isolate = i::Isolate::Current();
4990   if (IsDeadCheck(isolate, "v8::V8::RemoveGCPrologueCallback()")) return;
4991   isolate->heap()->RemoveGCPrologueCallback(callback);
4992 }
4993
4994
4995 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
4996   i::Isolate* isolate = i::Isolate::Current();
4997   if (IsDeadCheck(isolate, "v8::V8::AddGCEpilogueCallback()")) return;
4998   isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
4999 }
5000
5001
5002 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5003   i::Isolate* isolate = i::Isolate::Current();
5004   if (IsDeadCheck(isolate, "v8::V8::RemoveGCEpilogueCallback()")) return;
5005   isolate->heap()->RemoveGCEpilogueCallback(callback);
5006 }
5007
5008
5009 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5010                                      ObjectSpace space,
5011                                      AllocationAction action) {
5012   i::Isolate* isolate = i::Isolate::Current();
5013   if (IsDeadCheck(isolate, "v8::V8::AddMemoryAllocationCallback()")) return;
5014   isolate->memory_allocator()->AddMemoryAllocationCallback(
5015       callback, space, action);
5016 }
5017
5018
5019 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
5020   i::Isolate* isolate = i::Isolate::Current();
5021   if (IsDeadCheck(isolate, "v8::V8::RemoveMemoryAllocationCallback()")) return;
5022   isolate->memory_allocator()->RemoveMemoryAllocationCallback(
5023       callback);
5024 }
5025
5026
5027 void V8::PauseProfiler() {
5028   i::Isolate* isolate = i::Isolate::Current();
5029   isolate->logger()->PauseProfiler();
5030 }
5031
5032
5033 void V8::ResumeProfiler() {
5034   i::Isolate* isolate = i::Isolate::Current();
5035   isolate->logger()->ResumeProfiler();
5036 }
5037
5038
5039 bool V8::IsProfilerPaused() {
5040   i::Isolate* isolate = i::Isolate::Current();
5041   return isolate->logger()->IsProfilerPaused();
5042 }
5043
5044
5045 int V8::GetCurrentThreadId() {
5046   i::Isolate* isolate = i::Isolate::Current();
5047   EnsureInitializedForIsolate(isolate, "V8::GetCurrentThreadId()");
5048   return isolate->thread_id().ToInteger();
5049 }
5050
5051
5052 void V8::TerminateExecution(int thread_id) {
5053   i::Isolate* isolate = i::Isolate::Current();
5054   if (!isolate->IsInitialized()) return;
5055   API_ENTRY_CHECK(isolate, "V8::TerminateExecution()");
5056   // If the thread_id identifies the current thread just terminate
5057   // execution right away.  Otherwise, ask the thread manager to
5058   // terminate the thread with the given id if any.
5059   i::ThreadId internal_tid = i::ThreadId::FromInteger(thread_id);
5060   if (isolate->thread_id().Equals(internal_tid)) {
5061     isolate->stack_guard()->TerminateExecution();
5062   } else {
5063     isolate->thread_manager()->TerminateExecution(internal_tid);
5064   }
5065 }
5066
5067
5068 void V8::TerminateExecution(Isolate* isolate) {
5069   // If no isolate is supplied, use the default isolate.
5070   if (isolate != NULL) {
5071     reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->TerminateExecution();
5072   } else {
5073     i::Isolate::GetDefaultIsolateStackGuard()->TerminateExecution();
5074   }
5075 }
5076
5077
5078 bool V8::IsExecutionTerminating(Isolate* isolate) {
5079   i::Isolate* i_isolate = isolate != NULL ?
5080       reinterpret_cast<i::Isolate*>(isolate) : i::Isolate::Current();
5081   return IsExecutionTerminatingCheck(i_isolate);
5082 }
5083
5084
5085 Isolate* Isolate::GetCurrent() {
5086   i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5087   return reinterpret_cast<Isolate*>(isolate);
5088 }
5089
5090
5091 Isolate* Isolate::New() {
5092   i::Isolate* isolate = new i::Isolate();
5093   return reinterpret_cast<Isolate*>(isolate);
5094 }
5095
5096
5097 void Isolate::Dispose() {
5098   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5099   if (!ApiCheck(!isolate->IsInUse(),
5100                 "v8::Isolate::Dispose()",
5101                 "Disposing the isolate that is entered by a thread.")) {
5102     return;
5103   }
5104   isolate->TearDown();
5105 }
5106
5107
5108 void Isolate::Enter() {
5109   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5110   isolate->Enter();
5111 }
5112
5113
5114 void Isolate::Exit() {
5115   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5116   isolate->Exit();
5117 }
5118
5119
5120 void Isolate::SetData(void* data) {
5121   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5122   isolate->SetData(data);
5123 }
5124
5125 void* Isolate::GetData() {
5126   i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5127   return isolate->GetData();
5128 }
5129
5130
5131 String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj)
5132     : str_(NULL), length_(0) {
5133   i::Isolate* isolate = i::Isolate::Current();
5134   if (IsDeadCheck(isolate, "v8::String::Utf8Value::Utf8Value()")) return;
5135   if (obj.IsEmpty()) return;
5136   ENTER_V8(isolate);
5137   i::HandleScope scope(isolate);
5138   TryCatch try_catch;
5139   Handle<String> str = obj->ToString();
5140   if (str.IsEmpty()) return;
5141   length_ = str->Utf8Length();
5142   str_ = i::NewArray<char>(length_ + 1);
5143   str->WriteUtf8(str_);
5144 }
5145
5146
5147 String::Utf8Value::~Utf8Value() {
5148   i::DeleteArray(str_);
5149 }
5150
5151
5152 String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj)
5153     : str_(NULL), length_(0) {
5154   i::Isolate* isolate = i::Isolate::Current();
5155   if (IsDeadCheck(isolate, "v8::String::AsciiValue::AsciiValue()")) return;
5156   if (obj.IsEmpty()) return;
5157   ENTER_V8(isolate);
5158   i::HandleScope scope(isolate);
5159   TryCatch try_catch;
5160   Handle<String> str = obj->ToString();
5161   if (str.IsEmpty()) return;
5162   length_ = str->Length();
5163   str_ = i::NewArray<char>(length_ + 1);
5164   str->WriteAscii(str_);
5165 }
5166
5167
5168 String::AsciiValue::~AsciiValue() {
5169   i::DeleteArray(str_);
5170 }
5171
5172
5173 String::Value::Value(v8::Handle<v8::Value> obj)
5174     : str_(NULL), length_(0) {
5175   i::Isolate* isolate = i::Isolate::Current();
5176   if (IsDeadCheck(isolate, "v8::String::Value::Value()")) return;
5177   if (obj.IsEmpty()) return;
5178   ENTER_V8(isolate);
5179   i::HandleScope scope(isolate);
5180   TryCatch try_catch;
5181   Handle<String> str = obj->ToString();
5182   if (str.IsEmpty()) return;
5183   length_ = str->Length();
5184   str_ = i::NewArray<uint16_t>(length_ + 1);
5185   str->Write(str_);
5186 }
5187
5188
5189 String::Value::~Value() {
5190   i::DeleteArray(str_);
5191 }
5192
5193 Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
5194   i::Isolate* isolate = i::Isolate::Current();
5195   LOG_API(isolate, "RangeError");
5196   ON_BAILOUT(isolate, "v8::Exception::RangeError()", return Local<Value>());
5197   ENTER_V8(isolate);
5198   i::Object* error;
5199   {
5200     i::HandleScope scope(isolate);
5201     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5202     i::Handle<i::Object> result = isolate->factory()->NewRangeError(message);
5203     error = *result;
5204   }
5205   i::Handle<i::Object> result(error);
5206   return Utils::ToLocal(result);
5207 }
5208
5209 Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
5210   i::Isolate* isolate = i::Isolate::Current();
5211   LOG_API(isolate, "ReferenceError");
5212   ON_BAILOUT(isolate, "v8::Exception::ReferenceError()", return Local<Value>());
5213   ENTER_V8(isolate);
5214   i::Object* error;
5215   {
5216     i::HandleScope scope(isolate);
5217     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5218     i::Handle<i::Object> result =
5219         isolate->factory()->NewReferenceError(message);
5220     error = *result;
5221   }
5222   i::Handle<i::Object> result(error);
5223   return Utils::ToLocal(result);
5224 }
5225
5226 Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
5227   i::Isolate* isolate = i::Isolate::Current();
5228   LOG_API(isolate, "SyntaxError");
5229   ON_BAILOUT(isolate, "v8::Exception::SyntaxError()", return Local<Value>());
5230   ENTER_V8(isolate);
5231   i::Object* error;
5232   {
5233     i::HandleScope scope(isolate);
5234     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5235     i::Handle<i::Object> result = isolate->factory()->NewSyntaxError(message);
5236     error = *result;
5237   }
5238   i::Handle<i::Object> result(error);
5239   return Utils::ToLocal(result);
5240 }
5241
5242 Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
5243   i::Isolate* isolate = i::Isolate::Current();
5244   LOG_API(isolate, "TypeError");
5245   ON_BAILOUT(isolate, "v8::Exception::TypeError()", return Local<Value>());
5246   ENTER_V8(isolate);
5247   i::Object* error;
5248   {
5249     i::HandleScope scope(isolate);
5250     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5251     i::Handle<i::Object> result = isolate->factory()->NewTypeError(message);
5252     error = *result;
5253   }
5254   i::Handle<i::Object> result(error);
5255   return Utils::ToLocal(result);
5256 }
5257
5258 Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
5259   i::Isolate* isolate = i::Isolate::Current();
5260   LOG_API(isolate, "Error");
5261   ON_BAILOUT(isolate, "v8::Exception::Error()", return Local<Value>());
5262   ENTER_V8(isolate);
5263   i::Object* error;
5264   {
5265     i::HandleScope scope(isolate);
5266     i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5267     i::Handle<i::Object> result = isolate->factory()->NewError(message);
5268     error = *result;
5269   }
5270   i::Handle<i::Object> result(error);
5271   return Utils::ToLocal(result);
5272 }
5273
5274
5275 // --- D e b u g   S u p p o r t ---
5276
5277 #ifdef ENABLE_DEBUGGER_SUPPORT
5278
5279 static void EventCallbackWrapper(const v8::Debug::EventDetails& event_details) {
5280   i::Isolate* isolate = i::Isolate::Current();
5281   if (isolate->debug_event_callback() != NULL) {
5282     isolate->debug_event_callback()(event_details.GetEvent(),
5283                                     event_details.GetExecutionState(),
5284                                     event_details.GetEventData(),
5285                                     event_details.GetCallbackData());
5286   }
5287 }
5288
5289
5290 bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
5291   i::Isolate* isolate = i::Isolate::Current();
5292   EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener()");
5293   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5294   ENTER_V8(isolate);
5295
5296   isolate->set_debug_event_callback(that);
5297
5298   i::HandleScope scope(isolate);
5299   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5300   if (that != NULL) {
5301     foreign =
5302         isolate->factory()->NewForeign(FUNCTION_ADDR(EventCallbackWrapper));
5303   }
5304   isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5305   return true;
5306 }
5307
5308
5309 bool Debug::SetDebugEventListener2(EventCallback2 that, Handle<Value> data) {
5310   i::Isolate* isolate = i::Isolate::Current();
5311   EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener2()");
5312   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener2()", return false);
5313   ENTER_V8(isolate);
5314   i::HandleScope scope(isolate);
5315   i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5316   if (that != NULL) {
5317     foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
5318   }
5319   isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5320   return true;
5321 }
5322
5323
5324 bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
5325                                   Handle<Value> data) {
5326   i::Isolate* isolate = i::Isolate::Current();
5327   ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5328   ENTER_V8(isolate);
5329   isolate->debugger()->SetEventListener(Utils::OpenHandle(*that),
5330                                                       Utils::OpenHandle(*data));
5331   return true;
5332 }
5333
5334
5335 void Debug::DebugBreak(Isolate* isolate) {
5336   // If no isolate is supplied, use the default isolate.
5337   if (isolate != NULL) {
5338     reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->DebugBreak();
5339   } else {
5340     i::Isolate::GetDefaultIsolateStackGuard()->DebugBreak();
5341   }
5342 }
5343
5344
5345 void Debug::CancelDebugBreak(Isolate* isolate) {
5346   // If no isolate is supplied, use the default isolate.
5347   if (isolate != NULL) {
5348     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5349     internal_isolate->stack_guard()->Continue(i::DEBUGBREAK);
5350   } else {
5351     i::Isolate::GetDefaultIsolateStackGuard()->Continue(i::DEBUGBREAK);
5352   }
5353 }
5354
5355
5356 void Debug::DebugBreakForCommand(ClientData* data, Isolate* isolate) {
5357   // If no isolate is supplied, use the default isolate.
5358   if (isolate != NULL) {
5359     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5360     internal_isolate->debugger()->EnqueueDebugCommand(data);
5361   } else {
5362     i::Isolate::GetDefaultIsolateDebugger()->EnqueueDebugCommand(data);
5363   }
5364 }
5365
5366
5367 static void MessageHandlerWrapper(const v8::Debug::Message& message) {
5368   i::Isolate* isolate = i::Isolate::Current();
5369   if (isolate->message_handler()) {
5370     v8::String::Value json(message.GetJSON());
5371     (isolate->message_handler())(*json, json.length(), message.GetClientData());
5372   }
5373 }
5374
5375
5376 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
5377                               bool message_handler_thread) {
5378   i::Isolate* isolate = i::Isolate::Current();
5379   EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5380   ENTER_V8(isolate);
5381
5382   // Message handler thread not supported any more. Parameter temporally left in
5383   // the API for client compatibility reasons.
5384   CHECK(!message_handler_thread);
5385
5386   // TODO(sgjesse) support the old message handler API through a simple wrapper.
5387   isolate->set_message_handler(handler);
5388   if (handler != NULL) {
5389     isolate->debugger()->SetMessageHandler(MessageHandlerWrapper);
5390   } else {
5391     isolate->debugger()->SetMessageHandler(NULL);
5392   }
5393 }
5394
5395
5396 void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
5397   i::Isolate* isolate = i::Isolate::Current();
5398   EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5399   ENTER_V8(isolate);
5400   isolate->debugger()->SetMessageHandler(handler);
5401 }
5402
5403
5404 void Debug::SendCommand(const uint16_t* command, int length,
5405                         ClientData* client_data,
5406                         Isolate* isolate) {
5407   // If no isolate is supplied, use the default isolate.
5408   if (isolate != NULL) {
5409     i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5410     internal_isolate->debugger()->ProcessCommand(
5411         i::Vector<const uint16_t>(command, length), client_data);
5412   } else {
5413     i::Isolate::GetDefaultIsolateDebugger()->ProcessCommand(
5414         i::Vector<const uint16_t>(command, length), client_data);
5415   }
5416 }
5417
5418
5419 void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
5420                                    int period) {
5421   i::Isolate* isolate = i::Isolate::Current();
5422   EnsureInitializedForIsolate(isolate, "v8::Debug::SetHostDispatchHandler");
5423   ENTER_V8(isolate);
5424   isolate->debugger()->SetHostDispatchHandler(handler, period);
5425 }
5426
5427
5428 void Debug::SetDebugMessageDispatchHandler(
5429     DebugMessageDispatchHandler handler, bool provide_locker) {
5430   i::Isolate* isolate = i::Isolate::Current();
5431   EnsureInitializedForIsolate(isolate,
5432                               "v8::Debug::SetDebugMessageDispatchHandler");
5433   ENTER_V8(isolate);
5434   isolate->debugger()->SetDebugMessageDispatchHandler(
5435       handler, provide_locker);
5436 }
5437
5438
5439 Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
5440                          v8::Handle<v8::Value> data) {
5441   i::Isolate* isolate = i::Isolate::Current();
5442   if (!isolate->IsInitialized()) return Local<Value>();
5443   ON_BAILOUT(isolate, "v8::Debug::Call()", return Local<Value>());
5444   ENTER_V8(isolate);
5445   i::Handle<i::Object> result;
5446   EXCEPTION_PREAMBLE(isolate);
5447   if (data.IsEmpty()) {
5448     result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5449                                        isolate->factory()->undefined_value(),
5450                                        &has_pending_exception);
5451   } else {
5452     result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5453                                        Utils::OpenHandle(*data),
5454                                        &has_pending_exception);
5455   }
5456   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5457   return Utils::ToLocal(result);
5458 }
5459
5460
5461 Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
5462   i::Isolate* isolate = i::Isolate::Current();
5463   if (!isolate->IsInitialized()) return Local<Value>();
5464   ON_BAILOUT(isolate, "v8::Debug::GetMirror()", return Local<Value>());
5465   ENTER_V8(isolate);
5466   v8::HandleScope scope;
5467   i::Debug* isolate_debug = isolate->debug();
5468   isolate_debug->Load();
5469   i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global());
5470   i::Handle<i::String> name =
5471       isolate->factory()->LookupAsciiSymbol("MakeMirror");
5472   i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
5473   i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
5474   v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
5475   const int kArgc = 1;
5476   v8::Handle<v8::Value> argv[kArgc] = { obj };
5477   EXCEPTION_PREAMBLE(isolate);
5478   v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
5479                                               kArgc,
5480                                               argv);
5481   EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5482   return scope.Close(result);
5483 }
5484
5485
5486 bool Debug::EnableAgent(const char* name, int port, bool wait_for_connection) {
5487   return i::Isolate::Current()->debugger()->StartAgent(name, port,
5488                                                        wait_for_connection);
5489 }
5490
5491
5492 void Debug::DisableAgent() {
5493   return i::Isolate::Current()->debugger()->StopAgent();
5494 }
5495
5496
5497 void Debug::ProcessDebugMessages() {
5498   i::Execution::ProcessDebugMesssages(true);
5499 }
5500
5501 Local<Context> Debug::GetDebugContext() {
5502   i::Isolate* isolate = i::Isolate::Current();
5503   EnsureInitializedForIsolate(isolate, "v8::Debug::GetDebugContext()");
5504   ENTER_V8(isolate);
5505   return Utils::ToLocal(i::Isolate::Current()->debugger()->GetDebugContext());
5506 }
5507
5508 #endif  // ENABLE_DEBUGGER_SUPPORT
5509
5510
5511 Handle<String> CpuProfileNode::GetFunctionName() const {
5512   i::Isolate* isolate = i::Isolate::Current();
5513   IsDeadCheck(isolate, "v8::CpuProfileNode::GetFunctionName");
5514   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5515   const i::CodeEntry* entry = node->entry();
5516   if (!entry->has_name_prefix()) {
5517     return Handle<String>(ToApi<String>(
5518         isolate->factory()->LookupAsciiSymbol(entry->name())));
5519   } else {
5520     return Handle<String>(ToApi<String>(isolate->factory()->NewConsString(
5521         isolate->factory()->LookupAsciiSymbol(entry->name_prefix()),
5522         isolate->factory()->LookupAsciiSymbol(entry->name()))));
5523   }
5524 }
5525
5526
5527 Handle<String> CpuProfileNode::GetScriptResourceName() const {
5528   i::Isolate* isolate = i::Isolate::Current();
5529   IsDeadCheck(isolate, "v8::CpuProfileNode::GetScriptResourceName");
5530   const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5531   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5532       node->entry()->resource_name())));
5533 }
5534
5535
5536 int CpuProfileNode::GetLineNumber() const {
5537   i::Isolate* isolate = i::Isolate::Current();
5538   IsDeadCheck(isolate, "v8::CpuProfileNode::GetLineNumber");
5539   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
5540 }
5541
5542
5543 double CpuProfileNode::GetTotalTime() const {
5544   i::Isolate* isolate = i::Isolate::Current();
5545   IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalTime");
5546   return reinterpret_cast<const i::ProfileNode*>(this)->GetTotalMillis();
5547 }
5548
5549
5550 double CpuProfileNode::GetSelfTime() const {
5551   i::Isolate* isolate = i::Isolate::Current();
5552   IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfTime");
5553   return reinterpret_cast<const i::ProfileNode*>(this)->GetSelfMillis();
5554 }
5555
5556
5557 double CpuProfileNode::GetTotalSamplesCount() const {
5558   i::Isolate* isolate = i::Isolate::Current();
5559   IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalSamplesCount");
5560   return reinterpret_cast<const i::ProfileNode*>(this)->total_ticks();
5561 }
5562
5563
5564 double CpuProfileNode::GetSelfSamplesCount() const {
5565   i::Isolate* isolate = i::Isolate::Current();
5566   IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfSamplesCount");
5567   return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
5568 }
5569
5570
5571 unsigned CpuProfileNode::GetCallUid() const {
5572   i::Isolate* isolate = i::Isolate::Current();
5573   IsDeadCheck(isolate, "v8::CpuProfileNode::GetCallUid");
5574   return reinterpret_cast<const i::ProfileNode*>(this)->entry()->GetCallUid();
5575 }
5576
5577
5578 int CpuProfileNode::GetChildrenCount() const {
5579   i::Isolate* isolate = i::Isolate::Current();
5580   IsDeadCheck(isolate, "v8::CpuProfileNode::GetChildrenCount");
5581   return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
5582 }
5583
5584
5585 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
5586   i::Isolate* isolate = i::Isolate::Current();
5587   IsDeadCheck(isolate, "v8::CpuProfileNode::GetChild");
5588   const i::ProfileNode* child =
5589       reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
5590   return reinterpret_cast<const CpuProfileNode*>(child);
5591 }
5592
5593
5594 void CpuProfile::Delete() {
5595   i::Isolate* isolate = i::Isolate::Current();
5596   IsDeadCheck(isolate, "v8::CpuProfile::Delete");
5597   i::CpuProfiler::DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
5598   if (i::CpuProfiler::GetProfilesCount() == 0 &&
5599       !i::CpuProfiler::HasDetachedProfiles()) {
5600     // If this was the last profile, clean up all accessory data as well.
5601     i::CpuProfiler::DeleteAllProfiles();
5602   }
5603 }
5604
5605
5606 unsigned CpuProfile::GetUid() const {
5607   i::Isolate* isolate = i::Isolate::Current();
5608   IsDeadCheck(isolate, "v8::CpuProfile::GetUid");
5609   return reinterpret_cast<const i::CpuProfile*>(this)->uid();
5610 }
5611
5612
5613 Handle<String> CpuProfile::GetTitle() const {
5614   i::Isolate* isolate = i::Isolate::Current();
5615   IsDeadCheck(isolate, "v8::CpuProfile::GetTitle");
5616   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5617   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5618       profile->title())));
5619 }
5620
5621
5622 const CpuProfileNode* CpuProfile::GetBottomUpRoot() const {
5623   i::Isolate* isolate = i::Isolate::Current();
5624   IsDeadCheck(isolate, "v8::CpuProfile::GetBottomUpRoot");
5625   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5626   return reinterpret_cast<const CpuProfileNode*>(profile->bottom_up()->root());
5627 }
5628
5629
5630 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
5631   i::Isolate* isolate = i::Isolate::Current();
5632   IsDeadCheck(isolate, "v8::CpuProfile::GetTopDownRoot");
5633   const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5634   return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
5635 }
5636
5637
5638 int CpuProfiler::GetProfilesCount() {
5639   i::Isolate* isolate = i::Isolate::Current();
5640   IsDeadCheck(isolate, "v8::CpuProfiler::GetProfilesCount");
5641   return i::CpuProfiler::GetProfilesCount();
5642 }
5643
5644
5645 const CpuProfile* CpuProfiler::GetProfile(int index,
5646                                           Handle<Value> security_token) {
5647   i::Isolate* isolate = i::Isolate::Current();
5648   IsDeadCheck(isolate, "v8::CpuProfiler::GetProfile");
5649   return reinterpret_cast<const CpuProfile*>(
5650       i::CpuProfiler::GetProfile(
5651           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5652           index));
5653 }
5654
5655
5656 const CpuProfile* CpuProfiler::FindProfile(unsigned uid,
5657                                            Handle<Value> security_token) {
5658   i::Isolate* isolate = i::Isolate::Current();
5659   IsDeadCheck(isolate, "v8::CpuProfiler::FindProfile");
5660   return reinterpret_cast<const CpuProfile*>(
5661       i::CpuProfiler::FindProfile(
5662           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5663           uid));
5664 }
5665
5666
5667 void CpuProfiler::StartProfiling(Handle<String> title) {
5668   i::Isolate* isolate = i::Isolate::Current();
5669   IsDeadCheck(isolate, "v8::CpuProfiler::StartProfiling");
5670   i::CpuProfiler::StartProfiling(*Utils::OpenHandle(*title));
5671 }
5672
5673
5674 const CpuProfile* CpuProfiler::StopProfiling(Handle<String> title,
5675                                              Handle<Value> security_token) {
5676   i::Isolate* isolate = i::Isolate::Current();
5677   IsDeadCheck(isolate, "v8::CpuProfiler::StopProfiling");
5678   return reinterpret_cast<const CpuProfile*>(
5679       i::CpuProfiler::StopProfiling(
5680           security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5681           *Utils::OpenHandle(*title)));
5682 }
5683
5684
5685 void CpuProfiler::DeleteAllProfiles() {
5686   i::Isolate* isolate = i::Isolate::Current();
5687   IsDeadCheck(isolate, "v8::CpuProfiler::DeleteAllProfiles");
5688   i::CpuProfiler::DeleteAllProfiles();
5689 }
5690
5691
5692 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
5693   return const_cast<i::HeapGraphEdge*>(
5694       reinterpret_cast<const i::HeapGraphEdge*>(edge));
5695 }
5696
5697
5698 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
5699   i::Isolate* isolate = i::Isolate::Current();
5700   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetType");
5701   return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
5702 }
5703
5704
5705 Handle<Value> HeapGraphEdge::GetName() const {
5706   i::Isolate* isolate = i::Isolate::Current();
5707   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetName");
5708   i::HeapGraphEdge* edge = ToInternal(this);
5709   switch (edge->type()) {
5710     case i::HeapGraphEdge::kContextVariable:
5711     case i::HeapGraphEdge::kInternal:
5712     case i::HeapGraphEdge::kProperty:
5713     case i::HeapGraphEdge::kShortcut:
5714       return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5715           edge->name())));
5716     case i::HeapGraphEdge::kElement:
5717     case i::HeapGraphEdge::kHidden:
5718       return Handle<Number>(ToApi<Number>(isolate->factory()->NewNumberFromInt(
5719           edge->index())));
5720     default: UNREACHABLE();
5721   }
5722   return v8::Undefined();
5723 }
5724
5725
5726 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
5727   i::Isolate* isolate = i::Isolate::Current();
5728   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetFromNode");
5729   const i::HeapEntry* from = ToInternal(this)->From();
5730   return reinterpret_cast<const HeapGraphNode*>(from);
5731 }
5732
5733
5734 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
5735   i::Isolate* isolate = i::Isolate::Current();
5736   IsDeadCheck(isolate, "v8::HeapGraphEdge::GetToNode");
5737   const i::HeapEntry* to = ToInternal(this)->to();
5738   return reinterpret_cast<const HeapGraphNode*>(to);
5739 }
5740
5741
5742 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
5743   return const_cast<i::HeapEntry*>(
5744       reinterpret_cast<const i::HeapEntry*>(entry));
5745 }
5746
5747
5748 HeapGraphNode::Type HeapGraphNode::GetType() const {
5749   i::Isolate* isolate = i::Isolate::Current();
5750   IsDeadCheck(isolate, "v8::HeapGraphNode::GetType");
5751   return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
5752 }
5753
5754
5755 Handle<String> HeapGraphNode::GetName() const {
5756   i::Isolate* isolate = i::Isolate::Current();
5757   IsDeadCheck(isolate, "v8::HeapGraphNode::GetName");
5758   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5759       ToInternal(this)->name())));
5760 }
5761
5762
5763 uint64_t HeapGraphNode::GetId() const {
5764   i::Isolate* isolate = i::Isolate::Current();
5765   IsDeadCheck(isolate, "v8::HeapGraphNode::GetId");
5766   return ToInternal(this)->id();
5767 }
5768
5769
5770 int HeapGraphNode::GetSelfSize() const {
5771   i::Isolate* isolate = i::Isolate::Current();
5772   IsDeadCheck(isolate, "v8::HeapGraphNode::GetSelfSize");
5773   return ToInternal(this)->self_size();
5774 }
5775
5776
5777 int HeapGraphNode::GetRetainedSize(bool exact) const {
5778   i::Isolate* isolate = i::Isolate::Current();
5779   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainedSize");
5780   return ToInternal(this)->RetainedSize(exact);
5781 }
5782
5783
5784 int HeapGraphNode::GetChildrenCount() const {
5785   i::Isolate* isolate = i::Isolate::Current();
5786   IsDeadCheck(isolate, "v8::HeapSnapshot::GetChildrenCount");
5787   return ToInternal(this)->children().length();
5788 }
5789
5790
5791 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
5792   i::Isolate* isolate = i::Isolate::Current();
5793   IsDeadCheck(isolate, "v8::HeapSnapshot::GetChild");
5794   return reinterpret_cast<const HeapGraphEdge*>(
5795       &ToInternal(this)->children()[index]);
5796 }
5797
5798
5799 int HeapGraphNode::GetRetainersCount() const {
5800   i::Isolate* isolate = i::Isolate::Current();
5801   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainersCount");
5802   return ToInternal(this)->retainers().length();
5803 }
5804
5805
5806 const HeapGraphEdge* HeapGraphNode::GetRetainer(int index) const {
5807   i::Isolate* isolate = i::Isolate::Current();
5808   IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainer");
5809   return reinterpret_cast<const HeapGraphEdge*>(
5810       ToInternal(this)->retainers()[index]);
5811 }
5812
5813
5814 const HeapGraphNode* HeapGraphNode::GetDominatorNode() const {
5815   i::Isolate* isolate = i::Isolate::Current();
5816   IsDeadCheck(isolate, "v8::HeapSnapshot::GetDominatorNode");
5817   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->dominator());
5818 }
5819
5820
5821 v8::Handle<v8::Value> HeapGraphNode::GetHeapValue() const {
5822   i::Isolate* isolate = i::Isolate::Current();
5823   IsDeadCheck(isolate, "v8::HeapGraphNode::GetHeapValue");
5824   i::Handle<i::HeapObject> object = ToInternal(this)->GetHeapObject();
5825   return v8::Handle<Value>(!object.is_null() ?
5826                            ToApi<Value>(object) : ToApi<Value>(
5827                                isolate->factory()->undefined_value()));
5828 }
5829
5830
5831 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
5832   return const_cast<i::HeapSnapshot*>(
5833       reinterpret_cast<const i::HeapSnapshot*>(snapshot));
5834 }
5835
5836
5837 void HeapSnapshot::Delete() {
5838   i::Isolate* isolate = i::Isolate::Current();
5839   IsDeadCheck(isolate, "v8::HeapSnapshot::Delete");
5840   if (i::HeapProfiler::GetSnapshotsCount() > 1) {
5841     ToInternal(this)->Delete();
5842   } else {
5843     // If this is the last snapshot, clean up all accessory data as well.
5844     i::HeapProfiler::DeleteAllSnapshots();
5845   }
5846 }
5847
5848
5849 HeapSnapshot::Type HeapSnapshot::GetType() const {
5850   i::Isolate* isolate = i::Isolate::Current();
5851   IsDeadCheck(isolate, "v8::HeapSnapshot::GetType");
5852   return static_cast<HeapSnapshot::Type>(ToInternal(this)->type());
5853 }
5854
5855
5856 unsigned HeapSnapshot::GetUid() const {
5857   i::Isolate* isolate = i::Isolate::Current();
5858   IsDeadCheck(isolate, "v8::HeapSnapshot::GetUid");
5859   return ToInternal(this)->uid();
5860 }
5861
5862
5863 Handle<String> HeapSnapshot::GetTitle() const {
5864   i::Isolate* isolate = i::Isolate::Current();
5865   IsDeadCheck(isolate, "v8::HeapSnapshot::GetTitle");
5866   return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5867       ToInternal(this)->title())));
5868 }
5869
5870
5871 const HeapGraphNode* HeapSnapshot::GetRoot() const {
5872   i::Isolate* isolate = i::Isolate::Current();
5873   IsDeadCheck(isolate, "v8::HeapSnapshot::GetHead");
5874   return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
5875 }
5876
5877
5878 const HeapGraphNode* HeapSnapshot::GetNodeById(uint64_t id) const {
5879   i::Isolate* isolate = i::Isolate::Current();
5880   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodeById");
5881   return reinterpret_cast<const HeapGraphNode*>(
5882       ToInternal(this)->GetEntryById(id));
5883 }
5884
5885
5886 int HeapSnapshot::GetNodesCount() const {
5887   i::Isolate* isolate = i::Isolate::Current();
5888   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodesCount");
5889   return ToInternal(this)->entries()->length();
5890 }
5891
5892
5893 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
5894   i::Isolate* isolate = i::Isolate::Current();
5895   IsDeadCheck(isolate, "v8::HeapSnapshot::GetNode");
5896   return reinterpret_cast<const HeapGraphNode*>(
5897       ToInternal(this)->entries()->at(index));
5898 }
5899
5900
5901 void HeapSnapshot::Serialize(OutputStream* stream,
5902                              HeapSnapshot::SerializationFormat format) const {
5903   i::Isolate* isolate = i::Isolate::Current();
5904   IsDeadCheck(isolate, "v8::HeapSnapshot::Serialize");
5905   ApiCheck(format == kJSON,
5906            "v8::HeapSnapshot::Serialize",
5907            "Unknown serialization format");
5908   ApiCheck(stream->GetOutputEncoding() == OutputStream::kAscii,
5909            "v8::HeapSnapshot::Serialize",
5910            "Unsupported output encoding");
5911   ApiCheck(stream->GetChunkSize() > 0,
5912            "v8::HeapSnapshot::Serialize",
5913            "Invalid stream chunk size");
5914   i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
5915   serializer.Serialize(stream);
5916 }
5917
5918
5919 int HeapProfiler::GetSnapshotsCount() {
5920   i::Isolate* isolate = i::Isolate::Current();
5921   IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshotsCount");
5922   return i::HeapProfiler::GetSnapshotsCount();
5923 }
5924
5925
5926 const HeapSnapshot* HeapProfiler::GetSnapshot(int index) {
5927   i::Isolate* isolate = i::Isolate::Current();
5928   IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshot");
5929   return reinterpret_cast<const HeapSnapshot*>(
5930       i::HeapProfiler::GetSnapshot(index));
5931 }
5932
5933
5934 const HeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {
5935   i::Isolate* isolate = i::Isolate::Current();
5936   IsDeadCheck(isolate, "v8::HeapProfiler::FindSnapshot");
5937   return reinterpret_cast<const HeapSnapshot*>(
5938       i::HeapProfiler::FindSnapshot(uid));
5939 }
5940
5941
5942 const HeapSnapshot* HeapProfiler::TakeSnapshot(Handle<String> title,
5943                                                HeapSnapshot::Type type,
5944                                                ActivityControl* control) {
5945   i::Isolate* isolate = i::Isolate::Current();
5946   IsDeadCheck(isolate, "v8::HeapProfiler::TakeSnapshot");
5947   i::HeapSnapshot::Type internal_type = i::HeapSnapshot::kFull;
5948   switch (type) {
5949     case HeapSnapshot::kFull:
5950       internal_type = i::HeapSnapshot::kFull;
5951       break;
5952     default:
5953       UNREACHABLE();
5954   }
5955   return reinterpret_cast<const HeapSnapshot*>(
5956       i::HeapProfiler::TakeSnapshot(
5957           *Utils::OpenHandle(*title), internal_type, control));
5958 }
5959
5960
5961 void HeapProfiler::DeleteAllSnapshots() {
5962   i::Isolate* isolate = i::Isolate::Current();
5963   IsDeadCheck(isolate, "v8::HeapProfiler::DeleteAllSnapshots");
5964   i::HeapProfiler::DeleteAllSnapshots();
5965 }
5966
5967
5968 void HeapProfiler::DefineWrapperClass(uint16_t class_id,
5969                                       WrapperInfoCallback callback) {
5970   i::Isolate::Current()->heap_profiler()->DefineWrapperClass(class_id,
5971                                                              callback);
5972 }
5973
5974
5975
5976 v8::Testing::StressType internal::Testing::stress_type_ =
5977     v8::Testing::kStressTypeOpt;
5978
5979
5980 void Testing::SetStressRunType(Testing::StressType type) {
5981   internal::Testing::set_stress_type(type);
5982 }
5983
5984 int Testing::GetStressRuns() {
5985   if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
5986 #ifdef DEBUG
5987   // In debug mode the code runs much slower so stressing will only make two
5988   // runs.
5989   return 2;
5990 #else
5991   return 5;
5992 #endif
5993 }
5994
5995
5996 static void SetFlagsFromString(const char* flags) {
5997   V8::SetFlagsFromString(flags, i::StrLength(flags));
5998 }
5999
6000
6001 void Testing::PrepareStressRun(int run) {
6002   static const char* kLazyOptimizations =
6003       "--prepare-always-opt --nolimit-inlining "
6004       "--noalways-opt --noopt-eagerly";
6005   static const char* kEagerOptimizations = "--opt-eagerly";
6006   static const char* kForcedOptimizations = "--always-opt";
6007
6008   // If deoptimization stressed turn on frequent deoptimization. If no value
6009   // is spefified through --deopt-every-n-times use a default default value.
6010   static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
6011   if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
6012       internal::FLAG_deopt_every_n_times == 0) {
6013     SetFlagsFromString(kDeoptEvery13Times);
6014   }
6015
6016 #ifdef DEBUG
6017   // As stressing in debug mode only make two runs skip the deopt stressing
6018   // here.
6019   if (run == GetStressRuns() - 1) {
6020     SetFlagsFromString(kForcedOptimizations);
6021   } else {
6022     SetFlagsFromString(kEagerOptimizations);
6023     SetFlagsFromString(kLazyOptimizations);
6024   }
6025 #else
6026   if (run == GetStressRuns() - 1) {
6027     SetFlagsFromString(kForcedOptimizations);
6028   } else if (run == GetStressRuns() - 2) {
6029     SetFlagsFromString(kEagerOptimizations);
6030   } else {
6031     SetFlagsFromString(kLazyOptimizations);
6032   }
6033 #endif
6034 }
6035
6036
6037 void Testing::DeoptimizeAll() {
6038   internal::Deoptimizer::DeoptimizeAll();
6039 }
6040
6041
6042 namespace internal {
6043
6044
6045 void HandleScopeImplementer::FreeThreadResources() {
6046   Free();
6047 }
6048
6049
6050 char* HandleScopeImplementer::ArchiveThread(char* storage) {
6051   v8::ImplementationUtilities::HandleScopeData* current =
6052       isolate_->handle_scope_data();
6053   handle_scope_data_ = *current;
6054   memcpy(storage, this, sizeof(*this));
6055
6056   ResetAfterArchive();
6057   current->Initialize();
6058
6059   return storage + ArchiveSpacePerThread();
6060 }
6061
6062
6063 int HandleScopeImplementer::ArchiveSpacePerThread() {
6064   return sizeof(HandleScopeImplementer);
6065 }
6066
6067
6068 char* HandleScopeImplementer::RestoreThread(char* storage) {
6069   memcpy(this, storage, sizeof(*this));
6070   *isolate_->handle_scope_data() = handle_scope_data_;
6071   return storage + ArchiveSpacePerThread();
6072 }
6073
6074
6075 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
6076   // Iterate over all handles in the blocks except for the last.
6077   for (int i = blocks()->length() - 2; i >= 0; --i) {
6078     Object** block = blocks()->at(i);
6079     v->VisitPointers(block, &block[kHandleBlockSize]);
6080   }
6081
6082   // Iterate over live handles in the last block (if any).
6083   if (!blocks()->is_empty()) {
6084     v->VisitPointers(blocks()->last(), handle_scope_data_.next);
6085   }
6086
6087   if (!saved_contexts_.is_empty()) {
6088     Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
6089     v->VisitPointers(start, start + saved_contexts_.length());
6090   }
6091 }
6092
6093
6094 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
6095   v8::ImplementationUtilities::HandleScopeData* current =
6096       isolate_->handle_scope_data();
6097   handle_scope_data_ = *current;
6098   IterateThis(v);
6099 }
6100
6101
6102 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
6103   HandleScopeImplementer* scope_implementer =
6104       reinterpret_cast<HandleScopeImplementer*>(storage);
6105   scope_implementer->IterateThis(v);
6106   return storage + ArchiveSpacePerThread();
6107 }
6108
6109 } }  // namespace v8::internal