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