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
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.
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.
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"
37 #include "conversions-inl.h"
40 #include "deoptimizer.h"
41 #include "execution.h"
42 #include "global-handles.h"
43 #include "heap-profiler.h"
45 #ifdef COMPRESS_STARTUP_DATA_BZ2
50 #include "profile-generator-inl.h"
51 #include "property-details.h"
53 #include "runtime-profiler.h"
54 #include "scanner-character-streams.h"
56 #include "unicode-inl.h"
57 #include "v8threads.h"
59 #include "vm-state-inl.h"
62 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
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)
72 #define ON_BAILOUT(isolate, location, code) \
73 if (IsDeadCheck(isolate, location) || \
74 IsExecutionTerminatingCheck(isolate)) { \
80 #define EXCEPTION_PREAMBLE(isolate) \
81 (isolate)->handle_scope_implementer()->IncrementCallDepth(); \
82 ASSERT(!(isolate)->external_caught_exception()); \
83 bool has_pending_exception = false
86 #define EXCEPTION_BAILOUT_CHECK_GENERIC(isolate, value, do_callback) \
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); \
97 bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero(); \
98 (isolate)->OptionalRescheduleException(call_depth_is_zero); \
106 #define EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, value) \
107 EXCEPTION_BAILOUT_CHECK_GENERIC( \
108 isolate, value, i::V8::FireCallCompletedCallback(isolate);)
111 #define EXCEPTION_BAILOUT_CHECK(isolate, value) \
112 EXCEPTION_BAILOUT_CHECK_GENERIC(isolate, value, ;)
115 #define API_ENTRY_CHECK(isolate, msg) \
117 if (v8::Locker::IsActive()) { \
118 ApiCheck(isolate->thread_manager()->IsLockedByCurrentThread(), \
120 "Entering the V8 API without proper locking in place"); \
125 // --- E x c e p t i o n B e h a v i o r ---
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);
135 static FatalErrorCallback GetFatalErrorHandler() {
136 i::Isolate* isolate = i::Isolate::Current();
137 if (isolate->exception_behavior() == NULL) {
138 isolate->set_exception_behavior(DefaultFatalErrorHandler);
140 return isolate->exception_behavior();
144 void i::FatalProcessOutOfMemory(const char* location) {
145 i::V8::FatalProcessOutOfMemory(location, false);
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;
154 heap_stats.start_marker = &start_marker;
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;
200 heap_stats.os_error = &os_error;
202 heap_stats.end_marker = &end_marker;
203 i::Isolate* isolate = i::Isolate::Current();
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();
212 callback(location, "Allocation failed - process out of memory");
214 // If the callback returns, we stop execution.
219 bool Utils::ReportApiFailure(const char* location, const char* message) {
220 FatalErrorCallback callback = GetFatalErrorHandler();
221 callback(location, message);
222 i::V8::SetFatalError();
228 return i::V8::IsDead();
232 static inline bool ApiCheck(bool condition,
233 const char* location,
234 const char* message) {
235 return condition ? true : Utils::ReportApiFailure(location, message);
239 static bool ReportV8Dead(const char* location) {
240 FatalErrorCallback callback = GetFatalErrorHandler();
241 callback(location, "V8 is no longer usable");
246 static bool ReportEmptyHandle(const char* location) {
247 FatalErrorCallback callback = GetFatalErrorHandler();
248 callback(location, "Reading from empty handle");
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
265 static inline bool IsDeadCheck(i::Isolate* isolate, const char* location) {
266 return !isolate->IsInitialized()
267 && i::V8::IsDead() ? ReportV8Dead(location) : false;
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();
281 static inline bool EmptyCheck(const char* location, v8::Handle<v8::Data> obj) {
282 return obj.IsEmpty() ? ReportEmptyHandle(location) : false;
286 static inline bool EmptyCheck(const char* location, const v8::Data* obj) {
287 return (obj == 0) ? ReportEmptyHandle(location) : false;
290 // --- S t a t i c s ---
293 static bool InitializeHelper() {
294 if (i::Snapshot::Initialize()) return true;
295 return i::V8::Initialize(NULL);
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;
305 ASSERT(isolate == i::Isolate::Current());
306 return ApiCheck(InitializeHelper(), location, "Error initializing V8");
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();
321 i::Isolate::EnterDefaultIsolate();
322 isolate = i::Isolate::Current();
327 StartupDataDecompressor::StartupDataDecompressor()
328 : raw_data(i::NewArray<char*>(V8::GetCompressedStartupDataCount())) {
329 for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
335 StartupDataDecompressor::~StartupDataDecompressor() {
336 for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
337 i::DeleteArray(raw_data[i]);
339 i::DeleteArray(raw_data);
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;
358 ASSERT_EQ(0, compressed_data[i].raw_size);
360 compressed_data[i].data = decompressed;
362 V8::SetDecompressedStartupData(compressed_data);
363 i::DeleteArray(compressed_data);
368 StartupData::CompressionAlgorithm V8::GetCompressedStartupDataAlgorithm() {
369 #ifdef COMPRESS_STARTUP_DATA_BZ2
370 return StartupData::kBZip2;
372 return StartupData::kUncompressed;
377 enum CompressedStartupDataItems {
381 kExperimentalLibraries,
382 kCompressedStartupDataCount
385 int V8::GetCompressedStartupDataCount() {
386 #ifdef COMPRESS_STARTUP_DATA_BZ2
387 return kCompressedStartupDataCount;
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();
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();
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();
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();
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));
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));
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);
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);
454 void V8::SetFatalErrorHandler(FatalErrorCallback that) {
455 i::Isolate* isolate = EnterIsolateIfNeeded();
456 isolate->set_exception_behavior(that);
460 void V8::SetAllowCodeGenerationFromStringsCallback(
461 AllowCodeGenerationFromStringsCallback callback) {
462 i::Isolate* isolate = EnterIsolateIfNeeded();
463 isolate->set_allow_code_gen_callback(callback);
468 void ImplementationUtilities::ZapHandleRange(i::Object** begin,
470 i::HandleScope::ZapRange(begin, end);
475 void V8::SetFlagsFromString(const char* str, int length) {
476 i::FlagList::SetFlagsFromString(str, length);
480 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
481 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
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>();
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());
496 isolate->ScheduleThrow(*Utils::OpenHandle(*value));
498 return v8::Undefined();
502 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
505 RegisteredExtension::RegisteredExtension(Extension* extension)
506 : extension_(extension) { }
509 void RegisteredExtension::Register(RegisteredExtension* that) {
510 that->next_ = first_extension_;
511 first_extension_ = that;
515 void RegisteredExtension::UnregisterAll() {
516 RegisteredExtension* re = first_extension_;
518 RegisteredExtension* next = re->next();
525 void RegisterExtension(Extension* that) {
526 RegisteredExtension* extension = new RegisteredExtension(that);
527 RegisteredExtension::Register(extension);
531 Extension::Extension(const char* name,
537 source_length_(source_length >= 0 ?
539 (source ? static_cast<int>(strlen(source)) : 0)),
540 source_(source, source_length_),
541 dep_count_(dep_count),
543 auto_enable_(false) { }
546 v8::Handle<Primitive> Undefined() {
547 i::Isolate* isolate = i::Isolate::Current();
548 if (!EnsureInitializedForIsolate(isolate, "v8::Undefined()")) {
549 return v8::Handle<v8::Primitive>();
551 return v8::Handle<Primitive>(ToApi<Primitive>(
552 isolate->factory()->undefined_value()));
556 v8::Handle<Primitive> Null() {
557 i::Isolate* isolate = i::Isolate::Current();
558 if (!EnsureInitializedForIsolate(isolate, "v8::Null()")) {
559 return v8::Handle<v8::Primitive>();
561 return v8::Handle<Primitive>(
562 ToApi<Primitive>(isolate->factory()->null_value()));
566 v8::Handle<Boolean> True() {
567 i::Isolate* isolate = i::Isolate::Current();
568 if (!EnsureInitializedForIsolate(isolate, "v8::True()")) {
569 return v8::Handle<Boolean>();
571 return v8::Handle<Boolean>(
572 ToApi<Boolean>(isolate->factory()->true_value()));
576 v8::Handle<Boolean> False() {
577 i::Isolate* isolate = i::Isolate::Current();
578 if (!EnsureInitializedForIsolate(isolate, "v8::False()")) {
579 return v8::Handle<Boolean>();
581 return v8::Handle<Boolean>(
582 ToApi<Boolean>(isolate->factory()->false_value()));
586 ResourceConstraints::ResourceConstraints()
587 : max_young_space_size_(0),
588 max_old_space_size_(0),
589 max_executable_size_(0),
590 stack_limit_(NULL) { }
593 bool SetResourceConstraints(ResourceConstraints* constraints) {
594 i::Isolate* isolate = EnterIsolateIfNeeded();
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,
604 max_executable_size);
605 if (!result) return false;
607 if (constraints->stack_limit() != NULL) {
608 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints->stack_limit());
609 isolate->stack_guard()->SetStackLimit(limit);
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();
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,
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);
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);
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);
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);
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);
671 // --- H a n d l e s ---
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();
680 prev_next_ = current->next;
681 prev_limit_ = current->limit;
687 HandleScope::~HandleScope() {
694 void HandleScope::Leave() {
695 ASSERT(isolate_ == i::Isolate::Current());
696 v8::ImplementationUtilities::HandleScopeData* current =
697 isolate_->handle_scope_data();
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_);
707 i::HandleScope::ZapRange(prev_next_, prev_limit_);
712 int HandleScope::NumberOfHandles() {
713 EnsureInitializedForIsolate(
714 i::Isolate::Current(), "HandleScope::NumberOfHandles");
715 return i::HandleScope::NumberOfHandles();
719 i::Object** HandleScope::CreateHandle(i::Object* value) {
720 return i::HandleScope::CreateHandle(value, i::Isolate::Current());
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()));
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;
737 isolate->handle_scope_implementer()->EnterContext(env);
739 isolate->handle_scope_implementer()->SaveContext(isolate->context());
740 isolate->set_context(*env);
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
748 i::Isolate* isolate = i::Isolate::Current();
749 if (!isolate->IsInitialized()) return;
751 if (!ApiCheck(isolate->handle_scope_implementer()->LeaveLastContext(),
752 "v8::Context::Exit()",
753 "Cannot exit non-entered context")) {
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);
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);
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>();
783 i::Object* raw_result = NULL;
784 ASSERT(env->IsGlobalContext());
785 if (env->IsGlobalContext()) {
786 raw_result = env->data();
788 return Local<Value>();
790 i::Handle<i::Object> result(raw_result, isolate);
791 return Utils::ToLocal(result);
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")) {
801 LOG_API(isolate_, "CloseHandleScope");
803 // Read the result before popping the handle block.
804 i::Object* result = NULL;
815 // Allocate a new handle on the previous handle block.
816 i::Handle<i::Object> handle(result);
817 return handle.location();
821 // --- N e a n d e r ---
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");
833 value_ = isolate->factory()->NewNeanderObject();
834 i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
835 value_->set_elements(*elements);
839 int NeanderObject::size() {
840 return i::FixedArray::cast(value_->elements())->length();
844 NeanderArray::NeanderArray() : obj_(2) {
845 obj_.set(0, i::Smi::FromInt(0));
849 int NeanderArray::length() {
850 return i::Smi::cast(obj_.get(0))->value();
854 i::Object* NeanderArray::get(int offset) {
856 ASSERT(offset < length());
857 return obj_.get(offset + 1);
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
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);
875 obj_.set(length + 1, *value);
876 obj_.set(0, i::Smi::FromInt(length + 1));
880 void NeanderArray::set(int index, i::Object* value) {
881 if (index < 0 || index >= this->length()) return;
882 obj_.set(index + 1, value);
886 // --- T e m p l a t e ---
889 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
890 that->set_tag(i::Smi::FromInt(type));
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;
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);
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)));
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));
920 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
921 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
922 if (IsDeadCheck(isolate, "v8::FunctionTemplate::PrototypeTemplate()")) {
923 return Local<ObjectTemplate>();
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);
931 return Local<ObjectTemplate>(ToApi<ObjectTemplate>(result));
935 void FunctionTemplate::Inherit(v8::Handle<FunctionTemplate> value) {
936 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
937 if (IsDeadCheck(isolate, "v8::FunctionTemplate::Inherit()")) return;
939 Utils::OpenHandle(this)->set_parent_template(*Utils::OpenHandle(*value));
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");
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));
958 if (data.IsEmpty()) data = v8::Undefined();
959 Utils::ToLocal(obj)->SetCallHandler(callback, data);
961 obj->set_undetectable(false);
962 obj->set_needs_access_check(false);
964 if (!signature.IsEmpty())
965 obj->set_signature(*Utils::OpenHandle(*signature));
966 return Utils::ToLocal(obj);
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");
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));
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]));
987 obj->set_args(*args);
989 return Utils::ToLocal(obj);
993 Local<TypeSwitch> TypeSwitch::New(Handle<FunctionTemplate> type) {
994 Handle<FunctionTemplate> types[1] = { type };
995 return TypeSwitch::New(1, types);
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");
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);
1016 int TypeSwitch::match(v8::Handle<Value> value) {
1017 i::Isolate* isolate = i::Isolate::Current();
1018 LOG_API(isolate, "TypeSwitch::match");
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))))
1031 #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \
1032 i::Handle<i::Object> foreign = FromCData(cdata); \
1033 (obj)->setter(*foreign); \
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;
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);
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));
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()")) {
1089 i::HandleScope scope(isolate);
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);
1099 NeanderArray array(list);
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>();
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));
1115 i::Handle<i::ObjectTemplateInfo> result(i::ObjectTemplateInfo::cast(
1116 Utils::OpenHandle(this)->instance_template()));
1117 return Utils::ToLocal(result);
1121 void FunctionTemplate::SetClassName(Handle<String> name) {
1122 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1123 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetClassName()")) return;
1125 Utils::OpenHandle(this)->set_class_name(*Utils::OpenHandle(*name));
1129 void FunctionTemplate::SetHiddenPrototype(bool value) {
1130 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1131 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetHiddenPrototype()")) {
1135 Utils::OpenHandle(this)->set_hidden_prototype(value);
1139 void FunctionTemplate::ReadOnlyPrototype() {
1140 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1141 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetPrototypeAttributes()")) {
1145 Utils::OpenHandle(this)->set_read_only_prototype(true);
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()")) {
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);
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);
1174 if (data.IsEmpty()) data = v8::Undefined();
1175 obj->set_data(*Utils::OpenHandle(*data));
1176 Utils::OpenHandle(this)->set_named_property_handler(*obj);
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()")) {
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);
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);
1205 if (data.IsEmpty()) data = v8::Undefined();
1206 obj->set_data(*Utils::OpenHandle(*data));
1207 Utils::OpenHandle(this)->set_indexed_property_handler(*obj);
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()")) {
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);
1232 // --- O b j e c t T e m p l a t e ---
1235 Local<ObjectTemplate> ObjectTemplate::New() {
1236 return New(Local<FunctionTemplate>());
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>();
1246 EnsureInitializedForIsolate(isolate, "v8::ObjectTemplate::New()");
1247 LOG_API(isolate, "ObjectTemplate::New");
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);
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);
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;
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,
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()")) {
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,
1321 void ObjectTemplate::MarkAsUndetectable() {
1322 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1323 if (IsDeadCheck(isolate, "v8::ObjectTemplate::MarkAsUndetectable()")) return;
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);
1334 void ObjectTemplate::SetAccessCheckCallbacks(
1335 NamedSecurityCallback named_callback,
1336 IndexedSecurityCallback indexed_callback,
1338 bool turned_on_by_default) {
1339 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1340 if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetAccessCheckCallbacks()")) {
1344 i::HandleScope scope(isolate);
1345 EnsureConstructor(this);
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);
1352 SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
1353 SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
1355 if (data.IsEmpty()) data = v8::Undefined();
1356 info->set_data(*Utils::OpenHandle(*data));
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);
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()")) {
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,
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()")) {
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);
1409 int ObjectTemplate::InternalFieldCount() {
1410 if (IsDeadCheck(Utils::OpenHandle(this)->GetIsolate(),
1411 "v8::ObjectTemplate::InternalFieldCount()")) {
1414 return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1418 void ObjectTemplate::SetInternalFieldCount(int value) {
1419 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1420 if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetInternalFieldCount()")) {
1423 if (!ApiCheck(i::Smi::IsValid(value),
1424 "v8::ObjectTemplate::SetInternalFieldCount()",
1425 "Invalid internal field count")) {
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);
1435 Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1439 // --- S c r i p t D a t a ---
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);
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);
1456 i::GenericStringUtf16CharacterStream stream(str, 0, str->length());
1457 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
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();
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);
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);
1478 return new i::ScriptDataImpl(
1479 i::Vector<unsigned>(deserialized_data, deserialized_data_length));
1483 // --- S c r i p t ---
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");
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());
1504 if (!origin->ResourceLineOffset().IsEmpty()) {
1505 line_offset = static_cast<int>(origin->ResourceLineOffset()->Value());
1507 if (!origin->ResourceColumnOffset().IsEmpty()) {
1509 static_cast<int>(origin->ResourceColumnOffset()->Value());
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;
1522 i::Handle<i::SharedFunctionInfo> result =
1523 i::Compiler::Compile(str,
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;
1535 i::Handle<i::SharedFunctionInfo> result(raw_result, isolate);
1536 return Local<Script>(ToApi<Script>(result));
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);
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");
1555 Local<Script> generic = New(source, origin, pre_data, script_data);
1556 if (generic.IsEmpty())
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(
1564 isolate->global_context());
1565 return Local<Script>(ToApi<Script>(result));
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);
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");
1582 i::Object* raw_result = NULL;
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());
1593 fun = i::Handle<i::JSFunction>(i::JSFunction::cast(*obj), isolate);
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;
1603 i::Handle<i::Object> result(raw_result, isolate);
1604 return Utils::ToLocal(result);
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()) {
1613 i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1616 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared());
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;
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());
1634 i::Handle<i::Object> id(raw_id);
1635 return Utils::ToLocal(id);
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");
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);
1653 // --- E x c e p t i o n s ---
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)),
1662 can_continue_(true),
1663 capture_message_(true),
1665 isolate_->RegisterTryCatchHandler(this);
1669 v8::TryCatch::~TryCatch() {
1670 ASSERT(isolate_ == i::Isolate::Current());
1672 v8::HandleScope scope;
1673 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(Exception());
1674 isolate_->UnregisterTryCatchHandler(this);
1675 v8::ThrowException(exc);
1677 isolate_->UnregisterTryCatchHandler(this);
1682 bool v8::TryCatch::HasCaught() const {
1683 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
1687 bool v8::TryCatch::CanContinue() const {
1688 return can_continue_;
1692 v8::Handle<v8::Value> v8::TryCatch::ReThrow() {
1693 if (!HasCaught()) return v8::Local<v8::Value>();
1695 return v8::Undefined();
1699 v8::Local<Value> v8::TryCatch::Exception() const {
1700 ASSERT(isolate_ == i::Isolate::Current());
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_));
1706 return v8::Local<Value>();
1711 v8::Local<Value> v8::TryCatch::StackTrace() const {
1712 ASSERT(isolate_ == i::Isolate::Current());
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));
1724 return v8::Local<Value>();
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_));
1735 return v8::Local<v8::Message>();
1740 void v8::TryCatch::Reset() {
1741 ASSERT(isolate_ == i::Isolate::Current());
1742 exception_ = isolate_->heap()->the_hole_value();
1743 message_ = i::Smi::FromInt(0);
1747 void v8::TryCatch::SetVerbose(bool value) {
1748 is_verbose_ = value;
1752 void v8::TryCatch::SetCaptureMessage(bool value) {
1753 capture_message_ = value;
1757 // --- M e s s a g e ---
1760 Local<String> Message::Get() const {
1761 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1762 ON_BAILOUT(isolate, "v8::Message::Get()", return Local<String>());
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);
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>();
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));
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>();
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));
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>();
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));
1823 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1824 i::Handle<i::Object> recv,
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);
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(),
1848 has_pending_exception);
1852 int Message::GetLineNumber() const {
1853 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1854 ON_BAILOUT(isolate, "v8::Message::GetLineNumber()", return kNoLineNumberInfo);
1856 i::HandleScope scope(isolate);
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());
1867 int Message::GetStartPosition() const {
1868 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1869 if (IsDeadCheck(isolate, "v8::Message::GetStartPosition()")) return 0;
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();
1878 int Message::GetEndPosition() const {
1879 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1880 if (IsDeadCheck(isolate, "v8::Message::GetEndPosition()")) return 0;
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();
1889 int Message::GetStartColumn() const {
1890 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1891 if (IsDeadCheck(isolate, "v8::Message::GetStartColumn()")) {
1892 return kNoColumnInfo;
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",
1901 &has_pending_exception);
1902 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1903 return static_cast<int>(start_col_obj->Number());
1907 int Message::GetEndColumn() const {
1908 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1909 if (IsDeadCheck(isolate, "v8::Message::GetEndColumn()")) return kNoColumnInfo;
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",
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);
1927 Local<String> Message::GetSourceLine() const {
1928 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1929 ON_BAILOUT(isolate, "v8::Message::GetSourceLine()", return Local<String>());
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)));
1940 return Local<String>();
1945 void Message::PrintCurrentStackTrace(FILE* out) {
1946 i::Isolate* isolate = i::Isolate::Current();
1947 if (IsDeadCheck(isolate, "v8::Message::PrintCurrentStackTrace()")) return;
1949 isolate->PrintCurrentStackTrace(out);
1953 // --- S t a c k T r a c e ---
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>();
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));
1969 int StackTrace::GetFrameCount() const {
1970 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1971 if (IsDeadCheck(isolate, "v8::StackTrace::GetFrameCount()")) return -1;
1973 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
1977 Local<Array> StackTrace::AsArray() {
1978 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1979 if (IsDeadCheck(isolate, "v8::StackTrace::AsArray()")) Local<Array>();
1981 return Utils::ToLocal(Utils::OpenHandle(this));
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>();
1992 i::Handle<i::JSArray> stackTrace =
1993 isolate->CaptureCurrentStackTrace(frame_limit, options);
1994 return Utils::StackTraceToLocal(stackTrace);
1998 // --- S t a c k F r a m e ---
2000 int StackFrame::GetLineNumber() const {
2001 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2002 if (IsDeadCheck(isolate, "v8::StackFrame::GetLineNumber()")) {
2003 return Message::kNoLineNumberInfo;
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;
2012 return i::Smi::cast(*line)->value();
2016 int StackFrame::GetColumn() const {
2017 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2018 if (IsDeadCheck(isolate, "v8::StackFrame::GetColumn()")) {
2019 return Message::kNoColumnInfo;
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;
2028 return i::Smi::cast(*column)->value();
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>();
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>();
2044 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
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>();
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>();
2060 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
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>();
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>();
2076 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2080 bool StackFrame::IsEval() const {
2081 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2082 if (IsDeadCheck(isolate, "v8::StackFrame::IsEval()")) return false;
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();
2091 bool StackFrame::IsConstructor() const {
2092 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2093 if (IsDeadCheck(isolate, "v8::StackFrame::IsConstructor()")) return false;
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();
2104 bool Value::IsUndefined() const {
2105 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUndefined()")) {
2108 return Utils::OpenHandle(this)->IsUndefined();
2112 bool Value::IsNull() const {
2113 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNull()")) return false;
2114 return Utils::OpenHandle(this)->IsNull();
2118 bool Value::IsTrue() const {
2119 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsTrue()")) return false;
2120 return Utils::OpenHandle(this)->IsTrue();
2124 bool Value::IsFalse() const {
2125 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFalse()")) return false;
2126 return Utils::OpenHandle(this)->IsFalse();
2130 bool Value::IsFunction() const {
2131 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFunction()")) {
2134 return Utils::OpenHandle(this)->IsJSFunction();
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());
2146 bool Value::IsArray() const {
2147 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsArray()")) return false;
2148 return Utils::OpenHandle(this)->IsJSArray();
2152 bool Value::IsObject() const {
2153 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsObject()")) return false;
2154 return Utils::OpenHandle(this)->IsJSObject();
2158 bool Value::IsNumber() const {
2159 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNumber()")) return false;
2160 return Utils::OpenHandle(this)->IsNumber();
2164 bool Value::IsBoolean() const {
2165 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsBoolean()")) {
2168 return Utils::OpenHandle(this)->IsBoolean();
2172 bool Value::IsExternal() const {
2173 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsExternal()")) {
2176 return Utils::OpenHandle(this)->IsForeign();
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) {
2191 return i::FastI2D(i::FastD2I(value)) == value;
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) {
2208 return i::FastUI2D(i::FastD2UI(value)) == value;
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());
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());
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());
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);
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);
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");
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());
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();
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()) {
2294 i::Isolate* isolate = i::Isolate::Current();
2295 if (IsDeadCheck(isolate, "v8::Value::ToString()")) {
2296 return Local<String>();
2298 LOG_API(isolate, "ToString");
2300 EXCEPTION_PREAMBLE(isolate);
2301 str = i::Execution::ToString(obj, &has_pending_exception);
2302 EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2304 return Local<String>(ToApi<String>(str));
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()) {
2314 i::Isolate* isolate = i::Isolate::Current();
2315 if (IsDeadCheck(isolate, "v8::Value::ToDetailString()")) {
2316 return Local<String>();
2318 LOG_API(isolate, "ToDetailString");
2320 EXCEPTION_PREAMBLE(isolate);
2321 str = i::Execution::ToDetailString(obj, &has_pending_exception);
2322 EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2324 return Local<String>(ToApi<String>(str));
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()) {
2334 i::Isolate* isolate = i::Isolate::Current();
2335 if (IsDeadCheck(isolate, "v8::Value::ToObject()")) {
2336 return Local<v8::Object>();
2338 LOG_API(isolate, "ToObject");
2340 EXCEPTION_PREAMBLE(isolate);
2341 val = i::Execution::ToObject(obj, &has_pending_exception);
2342 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
2344 return Local<v8::Object>(ToApi<Object>(val));
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));
2353 i::Isolate* isolate = i::Isolate::Current();
2354 if (IsDeadCheck(isolate, "v8::Value::ToBoolean()")) {
2355 return Local<Boolean>();
2357 LOG_API(isolate, "ToBoolean");
2359 i::Handle<i::Object> val = i::Execution::ToBoolean(obj);
2360 return Local<Boolean>(ToApi<Boolean>(val));
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()) {
2371 i::Isolate* isolate = i::Isolate::Current();
2372 if (IsDeadCheck(isolate, "v8::Value::ToNumber()")) {
2373 return Local<Number>();
2375 LOG_API(isolate, "ToNumber");
2377 EXCEPTION_PREAMBLE(isolate);
2378 num = i::Execution::ToNumber(obj, &has_pending_exception);
2379 EXCEPTION_BAILOUT_CHECK(isolate, Local<Number>());
2381 return Local<Number>(ToApi<Number>(num));
2385 Local<Integer> Value::ToInteger() const {
2386 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2387 i::Handle<i::Object> num;
2391 i::Isolate* isolate = i::Isolate::Current();
2392 if (IsDeadCheck(isolate, "v8::Value::ToInteger()")) return Local<Integer>();
2393 LOG_API(isolate, "ToInteger");
2395 EXCEPTION_PREAMBLE(isolate);
2396 num = i::Execution::ToInteger(obj, &has_pending_exception);
2397 EXCEPTION_BAILOUT_CHECK(isolate, Local<Integer>());
2399 return Local<Integer>(ToApi<Integer>(num));
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");
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");
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");
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");
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");
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");
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");
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()),
2472 "Could not convert to date");
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");
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");
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");
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");
2515 bool Value::BooleanValue() const {
2516 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2517 if (obj->IsBoolean()) {
2518 return obj->IsTrue();
2520 i::Isolate* isolate = i::Isolate::Current();
2521 if (IsDeadCheck(isolate, "v8::Value::BooleanValue()")) return false;
2522 LOG_API(isolate, "BooleanValue");
2524 i::Handle<i::Object> value = i::Execution::ToBoolean(obj);
2525 return value->IsTrue();
2530 double Value::NumberValue() const {
2531 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2532 i::Handle<i::Object> num;
2533 if (obj->IsNumber()) {
2536 i::Isolate* isolate = i::Isolate::Current();
2537 if (IsDeadCheck(isolate, "v8::Value::NumberValue()")) {
2538 return i::OS::nan_value();
2540 LOG_API(isolate, "NumberValue");
2542 EXCEPTION_PREAMBLE(isolate);
2543 num = i::Execution::ToNumber(obj, &has_pending_exception);
2544 EXCEPTION_BAILOUT_CHECK(isolate, i::OS::nan_value());
2546 return num->Number();
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()) {
2556 i::Isolate* isolate = i::Isolate::Current();
2557 if (IsDeadCheck(isolate, "v8::Value::IntegerValue()")) return 0;
2558 LOG_API(isolate, "IntegerValue");
2560 EXCEPTION_PREAMBLE(isolate);
2561 num = i::Execution::ToInteger(obj, &has_pending_exception);
2562 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2565 return i::Smi::cast(*num)->value();
2567 return static_cast<int64_t>(num->Number());
2572 Local<Int32> Value::ToInt32() const {
2573 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2574 i::Handle<i::Object> num;
2578 i::Isolate* isolate = i::Isolate::Current();
2579 if (IsDeadCheck(isolate, "v8::Value::ToInt32()")) return Local<Int32>();
2580 LOG_API(isolate, "ToInt32");
2582 EXCEPTION_PREAMBLE(isolate);
2583 num = i::Execution::ToInt32(obj, &has_pending_exception);
2584 EXCEPTION_BAILOUT_CHECK(isolate, Local<Int32>());
2586 return Local<Int32>(ToApi<Int32>(num));
2590 Local<Uint32> Value::ToUint32() const {
2591 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2592 i::Handle<i::Object> num;
2596 i::Isolate* isolate = i::Isolate::Current();
2597 if (IsDeadCheck(isolate, "v8::Value::ToUint32()")) return Local<Uint32>();
2598 LOG_API(isolate, "ToUInt32");
2600 EXCEPTION_PREAMBLE(isolate);
2601 num = i::Execution::ToUint32(obj, &has_pending_exception);
2602 EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2604 return Local<Uint32>(ToApi<Uint32>(num));
2608 Local<Uint32> Value::ToArrayIndex() const {
2609 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2611 if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
2612 return Local<Uint32>();
2614 i::Isolate* isolate = i::Isolate::Current();
2615 if (IsDeadCheck(isolate, "v8::Value::ToArrayIndex()")) return Local<Uint32>();
2616 LOG_API(isolate, "ToArrayIndex");
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);
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));
2629 value = isolate->factory()->NewNumber(index);
2631 return Utils::Uint32ToLocal(value);
2633 return Local<Uint32>();
2637 int32_t Value::Int32Value() const {
2638 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2640 return i::Smi::cast(*obj)->value();
2642 i::Isolate* isolate = i::Isolate::Current();
2643 if (IsDeadCheck(isolate, "v8::Value::Int32Value()")) return 0;
2644 LOG_API(isolate, "Int32Value (slow)");
2646 EXCEPTION_PREAMBLE(isolate);
2647 i::Handle<i::Object> num =
2648 i::Execution::ToInt32(obj, &has_pending_exception);
2649 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2651 return i::Smi::cast(*num)->value();
2653 return static_cast<int32_t>(num->Number());
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)) {
2666 LOG_API(isolate, "Equals");
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;
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);
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)) {
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.
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();
2718 uint32_t Value::Uint32Value() const {
2719 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2721 return i::Smi::cast(*obj)->value();
2723 i::Isolate* isolate = i::Isolate::Current();
2724 if (IsDeadCheck(isolate, "v8::Value::Uint32Value()")) return 0;
2725 LOG_API(isolate, "Uint32Value");
2727 EXCEPTION_PREAMBLE(isolate);
2728 i::Handle<i::Object> num =
2729 i::Execution::ToUint32(obj, &has_pending_exception);
2730 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2732 return i::Smi::cast(*num)->value();
2734 return static_cast<uint32_t>(num->Number());
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);
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(
2754 static_cast<PropertyAttributes>(attribs),
2756 has_pending_exception = obj.is_null();
2757 EXCEPTION_BAILOUT_CHECK(isolate, false);
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);
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(
2776 has_pending_exception = obj.is_null();
2777 EXCEPTION_BAILOUT_CHECK(isolate, false);
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);
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(
2797 static_cast<PropertyAttributes>(attribs));
2798 has_pending_exception = obj.is_null();
2799 EXCEPTION_BAILOUT_CHECK(isolate, false);
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);
2808 i::HandleScope scope(isolate);
2809 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2810 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
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);
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();
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>());
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);
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>());
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);
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));
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));
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);
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>());
2876 i::Handle<i::Object> self = Utils::OpenHandle(this);
2877 i::Handle<i::Object> result(self->GetPrototype());
2878 return Utils::ToLocal(result);
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);
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.
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);
2899 Local<Object> v8::Object::FindInstanceInPrototypeChain(
2900 v8::Handle<FunctionTemplate> tmpl) {
2901 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2903 "v8::Object::FindInstanceInPrototypeChain()",
2904 return Local<v8::Object>());
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);
2913 return Utils::ToLocal(i::Handle<i::JSObject>(object));
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>());
2922 i::HandleScope scope(isolate);
2923 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
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));
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>());
2943 i::HandleScope scope(isolate);
2944 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
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));
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>());
2964 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2966 i::Handle<i::Object> name(self->class_name());
2968 // Native implementation of Object.prototype.toString (v8natives.js):
2969 // var c = %ClassOf(this);
2970 // if (c === 'Arguments') c = 'Object';
2971 // return "[object " + c + "]";
2973 if (!name->IsString()) {
2974 return v8::String::New("[object ]");
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]");
2982 const char* prefix = "[object ";
2983 Local<String> str = Utils::ToLocal(class_name);
2984 const char* postfix = "]";
2986 int prefix_len = i::StrLength(prefix);
2987 int str_len = str->Length();
2988 int postfix_len = i::StrLength(postfix);
2990 int buf_len = prefix_len + str_len + postfix_len;
2991 i::ScopedVector<char> buf(buf_len);
2994 char* ptr = buf.start();
2995 memcpy(ptr, prefix, prefix_len * v8::internal::kCharSize);
2998 // Write real content.
2999 str->WriteAscii(ptr, 0, str_len);
3003 memcpy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3005 // Copy the buffer into a heap-allocated string and return it.
3006 Local<String> result = v8::String::New(buf.start(), buf_len);
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>());
3018 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3019 i::Handle<i::String> name(self->constructor_name());
3020 return Utils::ToLocal(name);
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);
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();
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);
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);
3045 bool v8::Object::Delete(uint32_t index) {
3046 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3047 ON_BAILOUT(isolate, "v8::Object::DeleteProperty()",
3051 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3052 return i::JSObject::DeleteElement(self, index)->IsTrue();
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);
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);
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);
3085 bool v8::Object::HasOwnProperty(Handle<String> key) {
3086 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3087 ON_BAILOUT(isolate, "v8::Object::HasOwnProperty()",
3089 return Utils::OpenHandle(this)->HasLocalProperty(
3090 *Utils::OpenHandle(*key));
3094 bool v8::Object::HasRealNamedProperty(Handle<String> key) {
3095 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3096 ON_BAILOUT(isolate, "v8::Object::HasRealNamedProperty()",
3098 return Utils::OpenHandle(this)->HasRealNamedProperty(
3099 *Utils::OpenHandle(*key));
3103 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
3104 ON_BAILOUT(Utils::OpenHandle(this)->GetIsolate(),
3105 "v8::Object::HasRealIndexedProperty()",
3107 return Utils::OpenHandle(this)->HasRealElementProperty(index);
3111 bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
3112 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3114 "v8::Object::HasRealNamedCallbackProperty()",
3117 return Utils::OpenHandle(this)->HasRealNamedCallbackProperty(
3118 *Utils::OpenHandle(*key));
3122 bool v8::Object::HasNamedLookupInterceptor() {
3123 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3124 ON_BAILOUT(isolate, "v8::Object::HasNamedLookupInterceptor()",
3126 return Utils::OpenHandle(this)->HasNamedInterceptor();
3130 bool v8::Object::HasIndexedLookupInterceptor() {
3131 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3132 ON_BAILOUT(isolate, "v8::Object::HasIndexedLookupInterceptor()",
3134 return Utils::OpenHandle(this)->HasIndexedInterceptor();
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>();
3147 // If the property being looked up is a callback, it can throw
3149 EXCEPTION_PREAMBLE(isolate);
3150 PropertyAttributes ignored;
3151 i::Handle<i::Object> result =
3152 i::Object::GetProperty(receiver, receiver, lookup, name,
3154 has_pending_exception = result.is_null();
3155 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3157 return Utils::ToLocal(result);
3161 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
3162 Handle<String> key) {
3163 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3165 "v8::Object::GetRealNamedPropertyInPrototypeChain()",
3166 return Local<Value>());
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);
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>());
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);
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);
3196 i::HandleScope scope(isolate);
3197 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
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);
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);
3210 bool v8::Object::IsDirty() {
3211 return Utils::OpenHandle(this)->IsDirty();
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>());
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);
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);
3237 function = i::JSFunction::cast(constructor);
3239 return function->context()->global_context();
3243 Local<v8::Context> v8::Object::CreationContext() {
3244 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3246 "v8::Object::CreationContext()", return Local<v8::Context>());
3248 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3249 i::Context* context = GetCreationContext(*self);
3250 return Utils::ToLocal(i::Handle<i::Context>(context));
3254 int v8::Object::GetIdentityHash() {
3255 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3256 ON_BAILOUT(isolate, "v8::Object::GetIdentityHash()", return 0);
3258 i::HandleScope scope(isolate);
3259 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3260 return i::JSObject::GetIdentityHash(self);
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);
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;
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>());
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);
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);
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);
3306 static i::ElementsKind GetElementsKindFromExternalArrayType(
3307 ExternalArrayType array_type) {
3308 switch (array_type) {
3309 case kExternalByteArray:
3310 return i::EXTERNAL_BYTE_ELEMENTS;
3312 case kExternalUnsignedByteArray:
3313 return i::EXTERNAL_UNSIGNED_BYTE_ELEMENTS;
3315 case kExternalShortArray:
3316 return i::EXTERNAL_SHORT_ELEMENTS;
3318 case kExternalUnsignedShortArray:
3319 return i::EXTERNAL_UNSIGNED_SHORT_ELEMENTS;
3321 case kExternalIntArray:
3322 return i::EXTERNAL_INT_ELEMENTS;
3324 case kExternalUnsignedIntArray:
3325 return i::EXTERNAL_UNSIGNED_INT_ELEMENTS;
3327 case kExternalFloatArray:
3328 return i::EXTERNAL_FLOAT_ELEMENTS;
3330 case kExternalDoubleArray:
3331 return i::EXTERNAL_DOUBLE_ELEMENTS;
3333 case kExternalPixelArray:
3334 return i::EXTERNAL_PIXEL_ELEMENTS;
3338 return i::DICTIONARY_ELEMENTS;
3342 void PrepareExternalArrayElements(i::Handle<i::JSObject> object,
3344 ExternalArrayType array_type,
3346 i::Isolate* isolate = object->GetIsolate();
3347 i::Handle<i::ExternalArray> array =
3348 isolate->factory()->NewExternalArray(length, array_type, data);
3350 i::Handle<i::Map> external_array_map =
3351 isolate->factory()->GetElementsTransitionMap(
3353 GetElementsKindFromExternalArrayType(array_type));
3355 object->set_map(*external_array_map);
3356 object->set_elements(*array);
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);
3366 i::HandleScope scope(isolate);
3367 if (!ApiCheck(length <= i::ExternalPixelArray::kMaxLength,
3368 "v8::Object::SetIndexedPropertiesToPixelData()",
3369 "length exceeds max acceptable value")) {
3372 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3373 if (!ApiCheck(!self->IsJSArray(),
3374 "v8::Object::SetIndexedPropertiesToPixelData()",
3375 "JSArray is not supported")) {
3378 PrepareExternalArrayElements(self, data, kExternalPixelArray, length);
3382 bool v8::Object::HasIndexedPropertiesInPixelData() {
3383 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3384 ON_BAILOUT(self->GetIsolate(), "v8::HasIndexedPropertiesInPixelData()",
3386 return self->HasExternalPixelElements();
3390 uint8_t* v8::Object::GetIndexedPropertiesPixelData() {
3391 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3392 ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelData()",
3394 if (self->HasExternalPixelElements()) {
3395 return i::ExternalPixelArray::cast(self->elements())->
3396 external_pixel_pointer();
3403 int v8::Object::GetIndexedPropertiesPixelDataLength() {
3404 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3405 ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelDataLength()",
3407 if (self->HasExternalPixelElements()) {
3408 return i::ExternalPixelArray::cast(self->elements())->length();
3415 void v8::Object::SetIndexedPropertiesToExternalArrayData(
3417 ExternalArrayType array_type,
3419 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3420 ON_BAILOUT(isolate, "v8::SetIndexedPropertiesToExternalArrayData()", return);
3422 i::HandleScope scope(isolate);
3423 if (!ApiCheck(length <= i::ExternalArray::kMaxLength,
3424 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3425 "length exceeds max acceptable value")) {
3428 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3429 if (!ApiCheck(!self->IsJSArray(),
3430 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3431 "JSArray is not supported")) {
3434 PrepareExternalArrayElements(self, data, array_type, length);
3438 bool v8::Object::HasIndexedPropertiesInExternalArrayData() {
3439 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3440 ON_BAILOUT(self->GetIsolate(),
3441 "v8::HasIndexedPropertiesInExternalArrayData()",
3443 return self->HasExternalArrayElements();
3447 void* v8::Object::GetIndexedPropertiesExternalArrayData() {
3448 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3449 ON_BAILOUT(self->GetIsolate(),
3450 "v8::GetIndexedPropertiesExternalArrayData()",
3452 if (self->HasExternalArrayElements()) {
3453 return i::ExternalArray::cast(self->elements())->external_pointer();
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;
3485 return static_cast<ExternalArrayType>(-1);
3490 int v8::Object::GetIndexedPropertiesExternalArrayDataLength() {
3491 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3492 ON_BAILOUT(self->GetIsolate(),
3493 "v8::GetIndexedPropertiesExternalArrayDataLength()",
3495 if (self->HasExternalArrayElements()) {
3496 return i::ExternalArray::cast(self->elements())->length();
3503 bool v8::Object::IsCallable() {
3504 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3505 ON_BAILOUT(isolate, "v8::Object::IsCallable()", return false);
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();
3514 Local<v8::Value> Object::CallAsFunction(v8::Handle<v8::Object> recv,
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");
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);
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);
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));
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");
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)));
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));
3579 return Local<v8::Object>();
3583 Local<v8::Object> Function::NewInstance() const {
3584 return NewInstance(0, NULL);
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");
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)));
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");
3613 i::Object* raw_result = NULL;
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;
3626 i::Handle<i::Object> result(raw_result);
3627 return Utils::ToLocal(result);
3631 void Function::SetName(v8::Handle<v8::String> name) {
3632 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3635 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3636 func->shared()->set_name(*Utils::OpenHandle(*name));
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()));
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()));
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()));
3662 return v8::ScriptOrigin(Handle<Value>());
3666 const int Function::kLineOffsetNotFound = -1;
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());
3675 return kLineOffsetNotFound;
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());
3685 return kLineOffsetNotFound;
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()));
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();
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);
3710 // Will fail with a negative answer if the recursion depth is too high.
3711 static int RecursivelySerializeToUtf8(i::String* string,
3715 int recursion_budget,
3716 int32_t previous_character,
3717 int32_t* last_character) {
3720 if (string->IsAsciiRepresentation()) {
3721 i::String::WriteToFlat(string, buffer, start, end);
3722 *last_character = unibrow::Utf16::kNoPreviousCharacter;
3723 return utf8_bytes + end - start;
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];
3733 unibrow::Utf8::Encode(current, character, previous_character);
3734 previous_character = character;
3736 *last_character = previous_character;
3737 return static_cast<int>(utf8_bytes + current - buffer);
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];
3746 unibrow::Utf8::Encode(current, character, previous_character);
3747 previous_character = character;
3749 *last_character = previous_character;
3750 return static_cast<int>(utf8_bytes + current - buffer);
3752 case i::kSlicedStringTag: {
3753 i::SlicedString* slice = i::SlicedString::cast(string);
3754 unsigned offset = slice->offset();
3755 string = slice->parent();
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) {
3766 string = cons_string->second();
3770 } else if (end <= boundary) {
3774 if (recursion_budget == 0) return -1;
3775 int extra_utf8_bytes =
3776 RecursivelySerializeToUtf8(first,
3780 recursion_budget - 1,
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();
3798 bool String::MayContainNonAscii() const {
3799 i::Handle<i::String> str = Utils::OpenHandle(this);
3800 if (IsDeadCheck(str->GetIsolate(), "v8::String::MayContainNonAscii()")) {
3803 return !str->HasOnlyAsciiChars();
3807 int String::WriteUtf8(char* buffer,
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");
3815 i::Handle<i::String> str = Utils::OpenHandle(this);
3816 int string_length = str->length();
3817 if (str->IsAsciiRepresentation()) {
3819 if (capacity == -1) {
3820 capacity = str->length() + 1;
3821 len = string_length;
3823 len = i::Min(capacity, str->length());
3825 i::String::WriteToFlat(*str, buffer, 0, len);
3826 if (nchars_ref != NULL) *nchars_ref = len;
3827 if (!(options & NO_NULL_TERMINATION) && capacity > len) {
3834 if (capacity == -1 || capacity / 3 >= string_length) {
3835 int32_t previous = unibrow::Utf16::kNoPreviousCharacter;
3836 const int kMaxRecursion = 100;
3838 RecursivelySerializeToUtf8(*str,
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';
3851 if (nchars_ref != NULL) *nchars_ref = string_length;
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
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);
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.
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
3882 int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
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);
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
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);
3914 unibrow::Utf8::Encode(intermediate,
3916 unibrow::Utf16::kNoPreviousCharacter);
3917 if (pos + written <= capacity) {
3918 for (int j = 0; j < written; j++)
3919 buffer[pos + j] = intermediate[j];
3923 // We've reached the end of the buffer
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';
3938 int String::WriteAscii(char* buffer,
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");
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.
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);
3961 for (i = 0; i < end; i++) {
3962 char c = static_cast<char>(write_input_buffer.GetNext());
3963 if (c == '\0') c = ' ';
3966 if (!(options & NO_NULL_TERMINATION) && (length == -1 || i < length))
3972 int String::Write(uint16_t* buffer,
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");
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.
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';
4001 bool v8::String::IsExternal() const {
4002 i::Handle<i::String> str = Utils::OpenHandle(this);
4003 if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternal()")) {
4006 EnsureInitializedForIsolate(str->GetIsolate(), "v8::String::IsExternal()");
4007 return i::StringShape(*str).IsExternalTwoByte();
4011 bool v8::String::IsExternalAscii() const {
4012 i::Handle<i::String> str = Utils::OpenHandle(this);
4013 if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternalAscii()")) {
4016 return i::StringShape(*str).IsExternalAscii();
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);
4031 CHECK_EQ(expected, value);
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()")) {
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);
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();
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();
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);
4070 return i::Smi::cast(*obj)->value();
4072 return static_cast<int64_t>(obj->Number());
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);
4081 return i::Smi::cast(*obj)->value();
4083 return static_cast<int32_t>(obj->Number());
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);
4092 return i::Smi::cast(*obj)->value();
4094 return static_cast<uint32_t>(obj->Number());
4099 int v8::Object::InternalFieldCount() {
4100 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4101 if (IsDeadCheck(obj->GetIsolate(), "v8::Object::InternalFieldCount()")) {
4104 return obj->GetInternalFieldCount();
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>();
4113 if (!ApiCheck(index < obj->GetInternalFieldCount(),
4114 "v8::Object::GetInternalField()",
4115 "Reading internal field out of bounds")) {
4116 return Local<Value>();
4118 i::Handle<i::Object> value(obj->GetInternalField(index));
4119 Local<Value> result = Utils::ToLocal(value);
4121 Local<Value> unchecked = UncheckedGetInternalField(index);
4122 ASSERT(unchecked.IsEmpty() || (unchecked == result));
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()")) {
4134 if (!ApiCheck(index < obj->GetInternalFieldCount(),
4135 "v8::Object::SetInternalField()",
4136 "Writing internal field out of bounds")) {
4140 i::Handle<i::Object> val = Utils::OpenHandle(*value);
4141 obj->SetInternalField(index, *val);
4145 static bool CanBeEncodedAsSmi(void* ptr) {
4146 const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4147 return ((address & i::kEncodablePointerMask) == 0);
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));
4162 void v8::Object::SetPointerInInternalField(int index, void* value) {
4163 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4165 if (CanBeEncodedAsSmi(value)) {
4166 Utils::OpenHandle(this)->SetInternalField(index, EncodeAsSmi(value));
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);
4175 ASSERT_EQ(value, GetPointerFromInternalField(index));
4179 // --- E n v i r o n m e n t ---
4182 bool v8::V8::Initialize() {
4183 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4184 if (isolate != NULL && isolate->IsInitialized()) {
4187 return InitializeHelper();
4191 void v8::V8::SetEntropySource(EntropySource source) {
4192 i::V8::SetEntropySource(source);
4196 void v8::V8::SetReturnAddressLocationResolver(
4197 ReturnAddressLocationResolver return_address_resolver) {
4198 i::V8::SetReturnAddressLocationResolver(return_address_resolver);
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.")) {
4214 HeapStatistics::HeapStatistics(): total_heap_size_(0),
4215 total_heap_size_executable_(0),
4217 heap_size_limit_(0) { }
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);
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());
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);
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);
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");
4262 int v8::V8::ContextDisposedNotification() {
4263 i::Isolate* isolate = i::Isolate::Current();
4264 if (!isolate->IsInitialized()) return 0;
4265 return isolate->heap()->NotifyContextDisposed();
4269 const char* v8::V8::GetVersion() {
4270 return i::Version::GetVersion();
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));
4281 return i::Handle<i::FunctionTemplateInfo>(
4282 i::FunctionTemplateInfo::cast(templ->constructor()));
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>());
4296 // Enter V8 via an ENTER_V8 scope.
4297 i::Handle<i::Context> env;
4300 v8::Handle<ObjectTemplate> proxy_template = global_template;
4301 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
4302 i::Handle<i::FunctionTemplateInfo> global_constructor;
4304 if (!global_template.IsEmpty()) {
4305 // Make sure that the global_template has a constructor.
4306 global_constructor =
4307 EnsureConstructor(Utils::OpenHandle(*global_template));
4309 // Create a fresh template for the global proxy object.
4310 proxy_template = ObjectTemplate::New();
4312 EnsureConstructor(Utils::OpenHandle(*proxy_template));
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));
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());
4333 // Create the environment.
4334 env = isolate->bootstrapper()->CreateEnvironment(
4336 Utils::OpenHandle(*global_object),
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());
4349 isolate->runtime_profiler()->Reset();
4353 if (env.is_null()) {
4354 return Persistent<Context>();
4356 return Persistent<Context>(Utils::ToLocal(env));
4360 void v8::Context::SetSecurityToken(Handle<Value> token) {
4361 i::Isolate* isolate = i::Isolate::Current();
4362 if (IsDeadCheck(isolate, "v8::Context::SetSecurityToken()")) {
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);
4372 void v8::Context::UseDefaultSecurityToken() {
4373 i::Isolate* isolate = i::Isolate::Current();
4374 if (IsDeadCheck(isolate,
4375 "v8::Context::UseDefaultSecurityToken()")) {
4379 i::Handle<i::Context> env = Utils::OpenHandle(this);
4380 env->set_security_token(env->global());
4384 Handle<Value> v8::Context::GetSecurityToken() {
4385 i::Isolate* isolate = i::Isolate::Current();
4386 if (IsDeadCheck(isolate, "v8::Context::GetSecurityToken()")) {
4387 return Handle<Value>();
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);
4396 bool Context::HasOutOfMemoryException() {
4397 i::Handle<i::Context> env = Utils::OpenHandle(this);
4398 return env->has_out_of_memory();
4402 bool Context::InContext() {
4403 return i::Isolate::Current()->context() != NULL;
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>();
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);
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>();
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);
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>();
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);
4445 v8::Local<v8::Object> Context::Global() {
4446 if (IsDeadCheck(i::Isolate::Current(), "v8::Context::Global()")) {
4447 return Local<v8::Object>();
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));
4457 void Context::DetachGlobal() {
4458 i::Isolate* isolate = i::Isolate::Current();
4459 if (IsDeadCheck(isolate, "v8::Context::DetachGlobal()")) return;
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);
4468 void Context::ReattachGlobal(Handle<Object> global_object) {
4469 i::Isolate* isolate = i::Isolate::Current();
4470 if (IsDeadCheck(isolate, "v8::Context::ReattachGlobal()")) return;
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(
4477 Utils::OpenHandle(*global_object));
4481 void Context::AllowCodeGenerationFromStrings(bool allow) {
4482 i::Isolate* isolate = i::Isolate::Current();
4483 if (IsDeadCheck(isolate, "v8::Context::AllowCodeGenerationFromStrings()")) {
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());
4495 bool Context::IsCodeGenerationFromStringsAllowed() {
4496 i::Isolate* isolate = i::Isolate::Current();
4497 if (IsDeadCheck(isolate,
4498 "v8::Context::IsCodeGenerationFromStringsAllowed()")) {
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();
4509 void V8::SetWrapperClassId(i::Object** global_handle, uint16_t class_id) {
4510 i::GlobalHandles::SetWrapperClassId(global_handle, class_id);
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");
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));
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");
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));
4544 bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
4545 ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
4547 i::Object* obj = *Utils::OpenHandle(*value);
4548 return obj->IsInstanceOf(*Utils::OpenHandle(this));
4552 static Local<External> ExternalNewImpl(void* data) {
4553 return Utils::ToLocal(FACTORY->NewForeign(static_cast<i::Address>(data)));
4556 static void* ExternalValueImpl(i::Handle<i::Object> obj) {
4557 return reinterpret_cast<void*>(i::Foreign::cast(*obj)->foreign_address());
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");
4568 v8::Local<v8::Value> result = CanBeEncodedAsSmi(data)
4569 ? Utils::ToLocal(i::Handle<i::Object>(EncodeAsSmi(data)))
4570 : v8::Local<v8::Value>(ExternalNewImpl(data));
4572 ASSERT_EQ(data, Unwrap(result));
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());
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);
4595 result = i::Internals::GetExternalPointerFromSmi(*obj);
4596 } else if (obj->IsForeign()) {
4597 result = ExternalValueImpl(obj);
4601 ASSERT_EQ(result, QuickUnwrap(wrapper));
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");
4612 return ExternalNewImpl(data);
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);
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());
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();
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);
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)");
4651 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
4652 i::Handle<i::String> result = isolate->factory()->NewConsString(left_string,
4654 return Utils::ToLocal(result);
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)");
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);
4672 static int TwoByteStringLength(const uint16_t* data) {
4674 while (data[length] != '\0') length++;
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();
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);
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_)");
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);
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);
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);
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");
4729 i::Handle<i::String> result = NewExternalStringHandle(isolate, resource);
4730 isolate->heap()->external_string_table()->AddString(*result);
4731 return Utils::ToLocal(result);
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.
4743 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4746 if (isolate->heap()->IsInGCPostProcessing()) {
4749 bool result = obj->MakeExternal(resource);
4750 if (result && !obj->IsSymbol()) {
4751 isolate->heap()->external_string_table()->AddString(*obj);
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");
4763 i::Handle<i::String> result = NewExternalAsciiStringHandle(isolate, resource);
4764 isolate->heap()->external_string_table()->AddString(*result);
4765 return Utils::ToLocal(result);
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.
4778 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4781 if (isolate->heap()->IsInGCPostProcessing()) {
4784 bool result = obj->MakeExternal(resource);
4785 if (result && !obj->IsSymbol()) {
4786 isolate->heap()->external_string_table()->AddString(*obj);
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();
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");
4810 i::Handle<i::JSObject> obj =
4811 isolate->factory()->NewJSObject(isolate->object_function());
4812 return Utils::ToLocal(obj);
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");
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);
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();
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");
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);
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();
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");
4864 i::Handle<i::Object> obj =
4865 isolate->factory()->ToObject(Utils::OpenHandle(*value));
4866 return Utils::ToLocal(obj);
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>();
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())));
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");
4888 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4889 time = i::OS::nan_value();
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);
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();
4910 void v8::Date::DateTimeConfigurationChangeNotification() {
4911 i::Isolate* isolate = i::Isolate::Current();
4912 ON_BAILOUT(isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
4914 LOG_API(isolate, "Date::DateTimeConfigurationChangeNotification");
4917 isolate->date_cache()->ResetDateCache();
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)) {
4930 if (object_func->IsJSFunction()) {
4931 i::Handle<i::JSFunction> func =
4932 i::Handle<i::JSFunction>(i::JSFunction::cast(object_func));
4934 // Call ResetDateCache(0 but expect no exceptions:
4935 bool caught_exception = false;
4936 i::Execution::TryCall(func,
4937 isolate->js_builtins_object(),
4945 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
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));
4957 Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
4959 i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
4960 EnsureInitializedForIsolate(isolate, "v8::RegExp::New()");
4961 LOG_API(isolate, "RegExp::New");
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));
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>();
4978 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4979 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
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
4993 v8::RegExp::Flags v8::RegExp::GetFlags() const {
4994 if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::GetFlags()")) {
4995 return v8::RegExp::kNone;
4997 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4998 return static_cast<RegExp::Flags>(obj->GetFlags().value());
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");
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);
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();
5024 return static_cast<uint32_t>(length->Number());
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>();
5036 i::FixedArray* elms = i::FixedArray::cast(self->elements());
5037 i::Object* paragon = elms->get(index);
5038 if (!paragon->IsJSObject()) {
5039 return Local<Object>();
5041 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
5042 EXCEPTION_PREAMBLE(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);
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)");
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);
5063 Local<Number> v8::Number::New(double value) {
5064 i::Isolate* isolate = i::Isolate::Current();
5065 EnsureInitializedForIsolate(isolate, "v8::Number::New()");
5067 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
5068 value = i::OS::nan_value();
5071 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5072 return Utils::NumberToLocal(result);
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),
5084 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5085 return Utils::IntegerToLocal(result);
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));
5094 i::Isolate* isolate = i::Isolate::Current();
5096 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5097 return Utils::IntegerToLocal(result);
5101 void V8::IgnoreOutOfMemoryException() {
5102 EnterIsolateIfNeeded()->set_ignore_out_of_memory(true);
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);
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());
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);
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
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());
5142 void V8::SetCaptureStackTraceForUncaughtExceptions(
5145 StackTrace::StackTraceOptions options) {
5146 i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
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);
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);
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);
5172 void V8::EnableSlidingStateWindow() {
5173 i::Isolate* isolate = i::Isolate::Current();
5174 if (IsDeadCheck(isolate, "v8::V8::EnableSlidingStateWindow()")) return;
5175 isolate->logger()->EnableSlidingStateWindow();
5179 void V8::SetFailedAccessCheckCallbackFunction(
5180 FailedAccessCheckCallback callback) {
5181 i::Isolate* isolate = i::Isolate::Current();
5182 if (IsDeadCheck(isolate, "v8::V8::SetFailedAccessCheckCallbackFunction()")) {
5185 isolate->SetFailedAccessCheckCallback(callback);
5188 void V8::AddObjectGroup(Persistent<Value>* objects,
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);
5199 void V8::AddImplicitReferences(Persistent<Object> parent,
5200 Persistent<Value>* children,
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);
5211 int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
5212 i::Isolate* isolate = i::Isolate::Current();
5213 if (IsDeadCheck(isolate, "v8::V8::AdjustAmountOfExternalAllocatedMemory()")) {
5216 return isolate->heap()->AdjustAmountOfExternalAllocatedMemory(
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);
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);
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);
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);
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);
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);
5263 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
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);
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(
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);
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);
5298 void V8::PauseProfiler() {
5299 i::Isolate* isolate = i::Isolate::Current();
5300 isolate->logger()->PauseProfiler();
5304 void V8::ResumeProfiler() {
5305 i::Isolate* isolate = i::Isolate::Current();
5306 isolate->logger()->ResumeProfiler();
5310 bool V8::IsProfilerPaused() {
5311 i::Isolate* isolate = i::Isolate::Current();
5312 return isolate->logger()->IsProfilerPaused();
5316 int V8::GetCurrentThreadId() {
5317 i::Isolate* isolate = i::Isolate::Current();
5318 EnsureInitializedForIsolate(isolate, "V8::GetCurrentThreadId()");
5319 return isolate->thread_id().ToInteger();
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();
5334 isolate->thread_manager()->TerminateExecution(internal_tid);
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();
5344 i::Isolate::GetDefaultIsolateStackGuard()->TerminateExecution();
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);
5356 Isolate* Isolate::GetCurrent() {
5357 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5358 return reinterpret_cast<Isolate*>(isolate);
5362 Isolate* Isolate::New() {
5363 i::Isolate* isolate = new i::Isolate();
5364 return reinterpret_cast<Isolate*>(isolate);
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.")) {
5375 isolate->TearDown();
5379 void Isolate::Enter() {
5380 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5385 void Isolate::Exit() {
5386 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5391 void Isolate::SetData(void* data) {
5392 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5393 isolate->SetData(data);
5396 void* Isolate::GetData() {
5397 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5398 return isolate->GetData();
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;
5408 i::HandleScope scope(isolate);
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_);
5419 String::Utf8Value::~Utf8Value() {
5420 i::DeleteArray(str_);
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;
5430 i::HandleScope scope(isolate);
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_);
5440 String::AsciiValue::~AsciiValue() {
5441 i::DeleteArray(str_);
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;
5451 i::HandleScope scope(isolate);
5453 Handle<String> str = obj->ToString();
5454 if (str.IsEmpty()) return;
5455 length_ = str->Length();
5456 str_ = i::NewArray<uint16_t>(length_ + 1);
5461 String::Value::~Value() {
5462 i::DeleteArray(str_);
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>());
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);
5477 i::Handle<i::Object> result(error);
5478 return Utils::ToLocal(result);
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>());
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);
5494 i::Handle<i::Object> result(error);
5495 return Utils::ToLocal(result);
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>());
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);
5510 i::Handle<i::Object> result(error);
5511 return Utils::ToLocal(result);
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>());
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);
5526 i::Handle<i::Object> result(error);
5527 return Utils::ToLocal(result);
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>());
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);
5542 i::Handle<i::Object> result(error);
5543 return Utils::ToLocal(result);
5547 // --- D e b u g S u p p o r t ---
5549 #ifdef ENABLE_DEBUGGER_SUPPORT
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());
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);
5568 isolate->set_debug_event_callback(that);
5570 i::HandleScope scope(isolate);
5571 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5574 isolate->factory()->NewForeign(FUNCTION_ADDR(EventCallbackWrapper));
5576 isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
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);
5586 i::HandleScope scope(isolate);
5587 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5589 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
5591 isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
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);
5601 isolate->debugger()->SetEventListener(Utils::OpenHandle(*that),
5602 Utils::OpenHandle(*data));
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();
5612 i::Isolate::GetDefaultIsolateStackGuard()->DebugBreak();
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);
5623 i::Isolate::GetDefaultIsolateStackGuard()->Continue(i::DEBUGBREAK);
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);
5634 i::Isolate::GetDefaultIsolateDebugger()->EnqueueDebugCommand(data);
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());
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");
5654 // Message handler thread not supported any more. Parameter temporally left in
5655 // the API for client compatibility reasons.
5656 CHECK(!message_handler_thread);
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);
5663 isolate->debugger()->SetMessageHandler(NULL);
5668 void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
5669 i::Isolate* isolate = i::Isolate::Current();
5670 EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5672 isolate->debugger()->SetMessageHandler(handler);
5676 void Debug::SendCommand(const uint16_t* command, int length,
5677 ClientData* client_data,
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);
5685 i::Isolate::GetDefaultIsolateDebugger()->ProcessCommand(
5686 i::Vector<const uint16_t>(command, length), client_data);
5691 void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
5693 i::Isolate* isolate = i::Isolate::Current();
5694 EnsureInitializedForIsolate(isolate, "v8::Debug::SetHostDispatchHandler");
5696 isolate->debugger()->SetHostDispatchHandler(handler, period);
5700 void Debug::SetDebugMessageDispatchHandler(
5701 DebugMessageDispatchHandler handler, bool provide_locker) {
5702 i::Isolate* isolate = i::Isolate::Current();
5703 EnsureInitializedForIsolate(isolate,
5704 "v8::Debug::SetDebugMessageDispatchHandler");
5706 isolate->debugger()->SetDebugMessageDispatchHandler(
5707 handler, provide_locker);
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>());
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);
5724 result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5725 Utils::OpenHandle(*data),
5726 &has_pending_exception);
5728 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5729 return Utils::ToLocal(result);
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>());
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),
5753 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5754 return scope.Close(result);
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);
5764 void Debug::DisableAgent() {
5765 return i::Isolate::Current()->debugger()->StopAgent();
5769 void Debug::ProcessDebugMessages() {
5770 i::Execution::ProcessDebugMessages(true);
5773 Local<Context> Debug::GetDebugContext() {
5774 i::Isolate* isolate = i::Isolate::Current();
5775 EnsureInitializedForIsolate(isolate, "v8::Debug::GetDebugContext()");
5777 return Utils::ToLocal(i::Isolate::Current()->debugger()->GetDebugContext());
5780 #endif // ENABLE_DEBUGGER_SUPPORT
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())));
5792 return Handle<String>(ToApi<String>(isolate->factory()->NewConsString(
5793 isolate->factory()->LookupAsciiSymbol(entry->name_prefix()),
5794 isolate->factory()->LookupAsciiSymbol(entry->name()))));
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())));
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();
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();
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();
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();
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();
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();
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();
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);
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();
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();
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())));
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());
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());
5910 int CpuProfiler::GetProfilesCount() {
5911 i::Isolate* isolate = i::Isolate::Current();
5912 IsDeadCheck(isolate, "v8::CpuProfiler::GetProfilesCount");
5913 return i::CpuProfiler::GetProfilesCount();
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),
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),
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));
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)));
5957 void CpuProfiler::DeleteAllProfiles() {
5958 i::Isolate* isolate = i::Isolate::Current();
5959 IsDeadCheck(isolate, "v8::CpuProfiler::DeleteAllProfiles");
5960 i::CpuProfiler::DeleteAllProfiles();
5964 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
5965 return const_cast<i::HeapGraphEdge*>(
5966 reinterpret_cast<const i::HeapGraphEdge*>(edge));
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());
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(
5988 case i::HeapGraphEdge::kElement:
5989 case i::HeapGraphEdge::kHidden:
5990 return Handle<Number>(ToApi<Number>(isolate->factory()->NewNumberFromInt(
5992 default: UNREACHABLE();
5994 return v8::Undefined();
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);
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);
6014 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
6015 return const_cast<i::HeapEntry*>(
6016 reinterpret_cast<const i::HeapEntry*>(entry));
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());
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())));
6035 SnapshotObjectId HeapGraphNode::GetId() const {
6036 i::Isolate* isolate = i::Isolate::Current();
6037 IsDeadCheck(isolate, "v8::HeapGraphNode::GetId");
6038 return ToInternal(this)->id();
6042 int HeapGraphNode::GetSelfSize() const {
6043 i::Isolate* isolate = i::Isolate::Current();
6044 IsDeadCheck(isolate, "v8::HeapGraphNode::GetSelfSize");
6045 return ToInternal(this)->self_size();
6049 int HeapGraphNode::GetRetainedSize() const {
6050 i::Isolate* isolate = i::Isolate::Current();
6051 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainedSize");
6052 return ToInternal(this)->retained_size();
6056 int HeapGraphNode::GetChildrenCount() const {
6057 i::Isolate* isolate = i::Isolate::Current();
6058 IsDeadCheck(isolate, "v8::HeapSnapshot::GetChildrenCount");
6059 return ToInternal(this)->children().length();
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]);
6071 int HeapGraphNode::GetRetainersCount() const {
6072 i::Isolate* isolate = i::Isolate::Current();
6073 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainersCount");
6074 return ToInternal(this)->retainers().length();
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]);
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());
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()));
6103 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
6104 return const_cast<i::HeapSnapshot*>(
6105 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
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();
6115 // If this is the last snapshot, clean up all accessory data as well.
6116 i::HeapProfiler::DeleteAllSnapshots();
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());
6128 unsigned HeapSnapshot::GetUid() const {
6129 i::Isolate* isolate = i::Isolate::Current();
6130 IsDeadCheck(isolate, "v8::HeapSnapshot::GetUid");
6131 return ToInternal(this)->uid();
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())));
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());
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));
6158 int HeapSnapshot::GetNodesCount() const {
6159 i::Isolate* isolate = i::Isolate::Current();
6160 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodesCount");
6161 return ToInternal(this)->entries()->length();
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));
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();
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);
6198 int HeapProfiler::GetSnapshotsCount() {
6199 i::Isolate* isolate = i::Isolate::Current();
6200 IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshotsCount");
6201 return i::HeapProfiler::GetSnapshotsCount();
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));
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));
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;
6228 case HeapSnapshot::kFull:
6229 internal_type = i::HeapSnapshot::kFull;
6234 return reinterpret_cast<const HeapSnapshot*>(
6235 i::HeapProfiler::TakeSnapshot(
6236 *Utils::OpenHandle(*title), internal_type, control));
6240 void HeapProfiler::DeleteAllSnapshots() {
6241 i::Isolate* isolate = i::Isolate::Current();
6242 IsDeadCheck(isolate, "v8::HeapProfiler::DeleteAllSnapshots");
6243 i::HeapProfiler::DeleteAllSnapshots();
6247 void HeapProfiler::DefineWrapperClass(uint16_t class_id,
6248 WrapperInfoCallback callback) {
6249 i::Isolate::Current()->heap_profiler()->DefineWrapperClass(class_id,
6254 int HeapProfiler::GetPersistentHandleCount() {
6255 i::Isolate* isolate = i::Isolate::Current();
6256 return isolate->global_handles()->NumberOfGlobalHandles();
6260 v8::Testing::StressType internal::Testing::stress_type_ =
6261 v8::Testing::kStressTypeOpt;
6264 void Testing::SetStressRunType(Testing::StressType type) {
6265 internal::Testing::set_stress_type(type);
6268 int Testing::GetStressRuns() {
6269 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
6271 // In debug mode the code runs much slower so stressing will only make two
6280 static void SetFlagsFromString(const char* flags) {
6281 V8::SetFlagsFromString(flags, i::StrLength(flags));
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";
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);
6299 // As stressing in debug mode only make two runs skip the deopt stressing
6301 if (run == GetStressRuns() - 1) {
6302 SetFlagsFromString(kForcedOptimizations);
6304 SetFlagsFromString(kLazyOptimizations);
6307 if (run == GetStressRuns() - 1) {
6308 SetFlagsFromString(kForcedOptimizations);
6309 } else if (run != GetStressRuns() - 2) {
6310 SetFlagsFromString(kLazyOptimizations);
6316 void Testing::DeoptimizeAll() {
6317 internal::Deoptimizer::DeoptimizeAll();
6321 namespace internal {
6324 void HandleScopeImplementer::FreeThreadResources() {
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));
6335 ResetAfterArchive();
6336 current->Initialize();
6338 return storage + ArchiveSpacePerThread();
6342 int HandleScopeImplementer::ArchiveSpacePerThread() {
6343 return sizeof(HandleScopeImplementer);
6347 char* HandleScopeImplementer::RestoreThread(char* storage) {
6348 memcpy(this, storage, sizeof(*this));
6349 *isolate_->handle_scope_data() = handle_scope_data_;
6350 return storage + ArchiveSpacePerThread();
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]);
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);
6366 if (!saved_contexts_.is_empty()) {
6367 Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
6368 v->VisitPointers(start, start + saved_contexts_.length());
6373 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
6374 v8::ImplementationUtilities::HandleScopeData* current =
6375 isolate_->handle_scope_data();
6376 handle_scope_data_ = *current;
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();
6388 } } // namespace v8::internal