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