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