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