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