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