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