1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
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.
32 #include "arguments.h"
33 #include "bootstrapper.h"
36 #include "deoptimizer.h"
37 #include "execution.h"
39 #include "global-handles.h"
40 #include "heap-profiler.h"
45 #include "profile-generator-inl.h"
46 #include "runtime-profiler.h"
47 #include "scanner-character-streams.h"
48 #include "serialize.h"
50 #include "v8threads.h"
52 #include "vm-state-inl.h"
54 #include "../include/v8-profiler.h"
55 #include "../include/v8-testing.h"
57 #define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
59 #define ENTER_V8(isolate) \
60 ASSERT((isolate)->IsInitialized()); \
61 i::VMState __state__((isolate), i::OTHER)
62 #define LEAVE_V8(isolate) \
63 i::VMState __state__((isolate), i::EXTERNAL)
67 #define ON_BAILOUT(isolate, location, code) \
68 if (IsDeadCheck(isolate, location) || \
69 IsExecutionTerminatingCheck(isolate)) { \
75 #define EXCEPTION_PREAMBLE(isolate) \
76 (isolate)->handle_scope_implementer()->IncrementCallDepth(); \
77 ASSERT(!(isolate)->external_caught_exception()); \
78 bool has_pending_exception = false
81 #define EXCEPTION_BAILOUT_CHECK(isolate, value) \
83 i::HandleScopeImplementer* handle_scope_implementer = \
84 (isolate)->handle_scope_implementer(); \
85 handle_scope_implementer->DecrementCallDepth(); \
86 if (has_pending_exception) { \
87 if (handle_scope_implementer->CallDepthIsZero() && \
88 (isolate)->is_out_of_memory()) { \
89 if (!(isolate)->ignore_out_of_memory()) \
90 i::V8::FatalProcessOutOfMemory(NULL); \
92 bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero(); \
93 (isolate)->OptionalRescheduleException(call_depth_is_zero); \
99 #define API_ENTRY_CHECK(isolate, msg) \
101 if (v8::Locker::IsActive()) { \
102 ApiCheck(isolate->thread_manager()->IsLockedByCurrentThread(), \
104 "Entering the V8 API without proper locking in place"); \
109 // --- E x c e p t i o n B e h a v i o r ---
112 static void DefaultFatalErrorHandler(const char* location,
113 const char* message) {
114 i::VMState __state__(i::Isolate::Current(), i::OTHER);
115 API_Fatal(location, message);
119 static FatalErrorCallback GetFatalErrorHandler() {
120 i::Isolate* isolate = i::Isolate::Current();
121 if (isolate->exception_behavior() == NULL) {
122 isolate->set_exception_behavior(DefaultFatalErrorHandler);
124 return isolate->exception_behavior();
128 void i::FatalProcessOutOfMemory(const char* location) {
129 i::V8::FatalProcessOutOfMemory(location, false);
133 // When V8 cannot allocated memory FatalProcessOutOfMemory is called.
134 // The default fatal error handler is called and execution is stopped.
135 void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
136 i::HeapStats heap_stats;
138 heap_stats.start_marker = &start_marker;
140 heap_stats.new_space_size = &new_space_size;
141 int new_space_capacity;
142 heap_stats.new_space_capacity = &new_space_capacity;
143 intptr_t old_pointer_space_size;
144 heap_stats.old_pointer_space_size = &old_pointer_space_size;
145 intptr_t old_pointer_space_capacity;
146 heap_stats.old_pointer_space_capacity = &old_pointer_space_capacity;
147 intptr_t old_data_space_size;
148 heap_stats.old_data_space_size = &old_data_space_size;
149 intptr_t old_data_space_capacity;
150 heap_stats.old_data_space_capacity = &old_data_space_capacity;
151 intptr_t code_space_size;
152 heap_stats.code_space_size = &code_space_size;
153 intptr_t code_space_capacity;
154 heap_stats.code_space_capacity = &code_space_capacity;
155 intptr_t map_space_size;
156 heap_stats.map_space_size = &map_space_size;
157 intptr_t map_space_capacity;
158 heap_stats.map_space_capacity = &map_space_capacity;
159 intptr_t cell_space_size;
160 heap_stats.cell_space_size = &cell_space_size;
161 intptr_t cell_space_capacity;
162 heap_stats.cell_space_capacity = &cell_space_capacity;
163 intptr_t lo_space_size;
164 heap_stats.lo_space_size = &lo_space_size;
165 int global_handle_count;
166 heap_stats.global_handle_count = &global_handle_count;
167 int weak_global_handle_count;
168 heap_stats.weak_global_handle_count = &weak_global_handle_count;
169 int pending_global_handle_count;
170 heap_stats.pending_global_handle_count = &pending_global_handle_count;
171 int near_death_global_handle_count;
172 heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
173 int free_global_handle_count;
174 heap_stats.free_global_handle_count = &free_global_handle_count;
175 intptr_t memory_allocator_size;
176 heap_stats.memory_allocator_size = &memory_allocator_size;
177 intptr_t memory_allocator_capacity;
178 heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
179 int objects_per_type[LAST_TYPE + 1] = {0};
180 heap_stats.objects_per_type = objects_per_type;
181 int size_per_type[LAST_TYPE + 1] = {0};
182 heap_stats.size_per_type = size_per_type;
184 heap_stats.os_error = &os_error;
186 heap_stats.end_marker = &end_marker;
187 i::Isolate* isolate = i::Isolate::Current();
189 // Don't use the take_snapshot since we don't support HeapIterator here
190 // without doing a special GC.
191 isolate->heap()->RecordStats(&heap_stats, false);
192 i::V8::SetFatalError();
193 FatalErrorCallback callback = GetFatalErrorHandler();
196 callback(location, "Allocation failed - process out of memory");
198 // If the callback returns, we stop execution.
203 bool Utils::ReportApiFailure(const char* location, const char* message) {
204 FatalErrorCallback callback = GetFatalErrorHandler();
205 callback(location, message);
206 i::V8::SetFatalError();
212 return i::V8::IsDead();
216 static inline bool ApiCheck(bool condition,
217 const char* location,
218 const char* message) {
219 return condition ? true : Utils::ReportApiFailure(location, message);
223 static bool ReportV8Dead(const char* location) {
224 FatalErrorCallback callback = GetFatalErrorHandler();
225 callback(location, "V8 is no longer usable");
230 static bool ReportEmptyHandle(const char* location) {
231 FatalErrorCallback callback = GetFatalErrorHandler();
232 callback(location, "Reading from empty handle");
238 * IsDeadCheck checks that the vm is usable. If, for instance, the vm has been
239 * out of memory at some point this check will fail. It should be called on
240 * entry to all methods that touch anything in the heap, except destructors
241 * which you sometimes can't avoid calling after the vm has crashed. Functions
242 * that call EnsureInitialized or ON_BAILOUT don't have to also call
243 * IsDeadCheck. ON_BAILOUT has the advantage over EnsureInitialized that you
244 * can arrange to return if the VM is dead. This is needed to ensure that no VM
245 * heap allocations are attempted on a dead VM. EnsureInitialized has the
246 * advantage over ON_BAILOUT that it actually initializes the VM if this has not
249 static inline bool IsDeadCheck(i::Isolate* isolate, const char* location) {
250 return !isolate->IsInitialized()
251 && i::V8::IsDead() ? ReportV8Dead(location) : false;
255 static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
256 if (!isolate->IsInitialized()) return false;
257 if (isolate->has_scheduled_exception()) {
258 return isolate->scheduled_exception() ==
259 isolate->heap()->termination_exception();
265 static inline bool EmptyCheck(const char* location, v8::Handle<v8::Data> obj) {
266 return obj.IsEmpty() ? ReportEmptyHandle(location) : false;
270 static inline bool EmptyCheck(const char* location, const v8::Data* obj) {
271 return (obj == 0) ? ReportEmptyHandle(location) : false;
274 // --- S t a t i c s ---
277 static bool InitializeHelper() {
278 if (i::Snapshot::Initialize()) return true;
279 return i::V8::Initialize(NULL);
283 static inline bool EnsureInitializedForIsolate(i::Isolate* isolate,
284 const char* location) {
285 if (IsDeadCheck(isolate, location)) return false;
286 if (isolate != NULL) {
287 if (isolate->IsInitialized()) return true;
289 ASSERT(isolate == i::Isolate::Current());
290 return ApiCheck(InitializeHelper(), location, "Error initializing V8");
293 // Some initializing API functions are called early and may be
294 // called on a thread different from static initializer thread.
295 // If Isolate API is used, Isolate::Enter() will initialize TLS so
296 // Isolate::Current() works. If it's a legacy case, then the thread
297 // may not have TLS initialized yet. However, in initializing APIs it
298 // may be too early to call EnsureInitialized() - some pre-init
299 // parameters still have to be configured.
300 static inline i::Isolate* EnterIsolateIfNeeded() {
301 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
305 i::Isolate::EnterDefaultIsolate();
306 isolate = i::Isolate::Current();
311 StartupDataDecompressor::StartupDataDecompressor()
312 : raw_data(i::NewArray<char*>(V8::GetCompressedStartupDataCount())) {
313 for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
319 StartupDataDecompressor::~StartupDataDecompressor() {
320 for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
321 i::DeleteArray(raw_data[i]);
323 i::DeleteArray(raw_data);
327 int StartupDataDecompressor::Decompress() {
328 int compressed_data_count = V8::GetCompressedStartupDataCount();
329 StartupData* compressed_data =
330 i::NewArray<StartupData>(compressed_data_count);
331 V8::GetCompressedStartupData(compressed_data);
332 for (int i = 0; i < compressed_data_count; ++i) {
333 char* decompressed = raw_data[i] =
334 i::NewArray<char>(compressed_data[i].raw_size);
335 if (compressed_data[i].compressed_size != 0) {
336 int result = DecompressData(decompressed,
337 &compressed_data[i].raw_size,
338 compressed_data[i].data,
339 compressed_data[i].compressed_size);
340 if (result != 0) return result;
342 ASSERT_EQ(0, compressed_data[i].raw_size);
344 compressed_data[i].data = decompressed;
346 V8::SetDecompressedStartupData(compressed_data);
351 StartupData::CompressionAlgorithm V8::GetCompressedStartupDataAlgorithm() {
352 #ifdef COMPRESS_STARTUP_DATA_BZ2
353 return StartupData::kBZip2;
355 return StartupData::kUncompressed;
360 enum CompressedStartupDataItems {
364 kExperimentalLibraries,
365 kCompressedStartupDataCount
368 int V8::GetCompressedStartupDataCount() {
369 #ifdef COMPRESS_STARTUP_DATA_BZ2
370 return kCompressedStartupDataCount;
377 void V8::GetCompressedStartupData(StartupData* compressed_data) {
378 #ifdef COMPRESS_STARTUP_DATA_BZ2
379 compressed_data[kSnapshot].data =
380 reinterpret_cast<const char*>(i::Snapshot::data());
381 compressed_data[kSnapshot].compressed_size = i::Snapshot::size();
382 compressed_data[kSnapshot].raw_size = i::Snapshot::raw_size();
384 compressed_data[kSnapshotContext].data =
385 reinterpret_cast<const char*>(i::Snapshot::context_data());
386 compressed_data[kSnapshotContext].compressed_size =
387 i::Snapshot::context_size();
388 compressed_data[kSnapshotContext].raw_size = i::Snapshot::context_raw_size();
390 i::Vector<const i::byte> libraries_source = i::Natives::GetScriptsSource();
391 compressed_data[kLibraries].data =
392 reinterpret_cast<const char*>(libraries_source.start());
393 compressed_data[kLibraries].compressed_size = libraries_source.length();
394 compressed_data[kLibraries].raw_size = i::Natives::GetRawScriptsSize();
396 i::Vector<const i::byte> exp_libraries_source =
397 i::ExperimentalNatives::GetScriptsSource();
398 compressed_data[kExperimentalLibraries].data =
399 reinterpret_cast<const char*>(exp_libraries_source.start());
400 compressed_data[kExperimentalLibraries].compressed_size =
401 exp_libraries_source.length();
402 compressed_data[kExperimentalLibraries].raw_size =
403 i::ExperimentalNatives::GetRawScriptsSize();
408 void V8::SetDecompressedStartupData(StartupData* decompressed_data) {
409 #ifdef COMPRESS_STARTUP_DATA_BZ2
410 ASSERT_EQ(i::Snapshot::raw_size(), decompressed_data[kSnapshot].raw_size);
411 i::Snapshot::set_raw_data(
412 reinterpret_cast<const i::byte*>(decompressed_data[kSnapshot].data));
414 ASSERT_EQ(i::Snapshot::context_raw_size(),
415 decompressed_data[kSnapshotContext].raw_size);
416 i::Snapshot::set_context_raw_data(
417 reinterpret_cast<const i::byte*>(
418 decompressed_data[kSnapshotContext].data));
420 ASSERT_EQ(i::Natives::GetRawScriptsSize(),
421 decompressed_data[kLibraries].raw_size);
422 i::Vector<const char> libraries_source(
423 decompressed_data[kLibraries].data,
424 decompressed_data[kLibraries].raw_size);
425 i::Natives::SetRawScriptsSource(libraries_source);
427 ASSERT_EQ(i::ExperimentalNatives::GetRawScriptsSize(),
428 decompressed_data[kExperimentalLibraries].raw_size);
429 i::Vector<const char> exp_libraries_source(
430 decompressed_data[kExperimentalLibraries].data,
431 decompressed_data[kExperimentalLibraries].raw_size);
432 i::ExperimentalNatives::SetRawScriptsSource(exp_libraries_source);
437 void V8::SetFatalErrorHandler(FatalErrorCallback that) {
438 i::Isolate* isolate = EnterIsolateIfNeeded();
439 isolate->set_exception_behavior(that);
443 void V8::SetAllowCodeGenerationFromStringsCallback(
444 AllowCodeGenerationFromStringsCallback callback) {
445 i::Isolate* isolate = EnterIsolateIfNeeded();
446 isolate->set_allow_code_gen_callback(callback);
451 void ImplementationUtilities::ZapHandleRange(i::Object** begin,
453 i::HandleScope::ZapRange(begin, end);
458 void V8::SetFlagsFromString(const char* str, int length) {
459 i::FlagList::SetFlagsFromString(str, length);
463 void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
464 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
468 v8::Handle<Value> ThrowException(v8::Handle<v8::Value> value) {
469 i::Isolate* isolate = i::Isolate::Current();
470 if (IsDeadCheck(isolate, "v8::ThrowException()")) {
471 return v8::Handle<Value>();
474 // If we're passed an empty handle, we throw an undefined exception
475 // to deal more gracefully with out of memory situations.
476 if (value.IsEmpty()) {
477 isolate->ScheduleThrow(isolate->heap()->undefined_value());
479 isolate->ScheduleThrow(*Utils::OpenHandle(*value));
481 return v8::Undefined();
485 RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
488 RegisteredExtension::RegisteredExtension(Extension* extension)
489 : extension_(extension), state_(UNVISITED) { }
492 void RegisteredExtension::Register(RegisteredExtension* that) {
493 that->next_ = first_extension_;
494 first_extension_ = that;
498 void RegisterExtension(Extension* that) {
499 RegisteredExtension* extension = new RegisteredExtension(that);
500 RegisteredExtension::Register(extension);
504 Extension::Extension(const char* name,
510 source_length_(source_length >= 0 ?
511 source_length : (source ? strlen(source) : 0)),
512 source_(source, source_length_),
513 dep_count_(dep_count),
515 auto_enable_(false) { }
518 v8::Handle<Primitive> Undefined() {
519 i::Isolate* isolate = i::Isolate::Current();
520 if (!EnsureInitializedForIsolate(isolate, "v8::Undefined()")) {
521 return v8::Handle<v8::Primitive>();
523 return v8::Handle<Primitive>(ToApi<Primitive>(
524 isolate->factory()->undefined_value()));
528 v8::Handle<Primitive> Null() {
529 i::Isolate* isolate = i::Isolate::Current();
530 if (!EnsureInitializedForIsolate(isolate, "v8::Null()")) {
531 return v8::Handle<v8::Primitive>();
533 return v8::Handle<Primitive>(
534 ToApi<Primitive>(isolate->factory()->null_value()));
538 v8::Handle<Boolean> True() {
539 i::Isolate* isolate = i::Isolate::Current();
540 if (!EnsureInitializedForIsolate(isolate, "v8::True()")) {
541 return v8::Handle<Boolean>();
543 return v8::Handle<Boolean>(
544 ToApi<Boolean>(isolate->factory()->true_value()));
548 v8::Handle<Boolean> False() {
549 i::Isolate* isolate = i::Isolate::Current();
550 if (!EnsureInitializedForIsolate(isolate, "v8::False()")) {
551 return v8::Handle<Boolean>();
553 return v8::Handle<Boolean>(
554 ToApi<Boolean>(isolate->factory()->false_value()));
558 ResourceConstraints::ResourceConstraints()
559 : max_young_space_size_(0),
560 max_old_space_size_(0),
561 max_executable_size_(0),
562 stack_limit_(NULL) { }
565 bool SetResourceConstraints(ResourceConstraints* constraints) {
566 i::Isolate* isolate = EnterIsolateIfNeeded();
568 int young_space_size = constraints->max_young_space_size();
569 int old_gen_size = constraints->max_old_space_size();
570 int max_executable_size = constraints->max_executable_size();
571 if (young_space_size != 0 || old_gen_size != 0 || max_executable_size != 0) {
572 // After initialization it's too late to change Heap constraints.
573 ASSERT(!isolate->IsInitialized());
574 bool result = isolate->heap()->ConfigureHeap(young_space_size / 2,
576 max_executable_size);
577 if (!result) return false;
579 if (constraints->stack_limit() != NULL) {
580 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints->stack_limit());
581 isolate->stack_guard()->SetStackLimit(limit);
587 i::Object** V8::GlobalizeReference(i::Object** obj) {
588 i::Isolate* isolate = i::Isolate::Current();
589 if (IsDeadCheck(isolate, "V8::Persistent::New")) return NULL;
590 LOG_API(isolate, "Persistent::New");
591 i::Handle<i::Object> result =
592 isolate->global_handles()->Create(*obj);
593 return result.location();
597 void V8::MakeWeak(i::Object** object, void* parameters,
598 WeakReferenceCallback callback) {
599 i::Isolate* isolate = i::Isolate::Current();
600 LOG_API(isolate, "MakeWeak");
601 isolate->global_handles()->MakeWeak(object, parameters,
606 void V8::ClearWeak(i::Object** obj) {
607 i::Isolate* isolate = i::Isolate::Current();
608 LOG_API(isolate, "ClearWeak");
609 isolate->global_handles()->ClearWeakness(obj);
613 void V8::MarkIndependent(i::Object** object) {
614 i::Isolate* isolate = i::Isolate::Current();
615 LOG_API(isolate, "MakeIndependent");
616 isolate->global_handles()->MarkIndependent(object);
620 bool V8::IsGlobalNearDeath(i::Object** obj) {
621 i::Isolate* isolate = i::Isolate::Current();
622 LOG_API(isolate, "IsGlobalNearDeath");
623 if (!isolate->IsInitialized()) return false;
624 return i::GlobalHandles::IsNearDeath(obj);
628 bool V8::IsGlobalWeak(i::Object** obj) {
629 i::Isolate* isolate = i::Isolate::Current();
630 LOG_API(isolate, "IsGlobalWeak");
631 if (!isolate->IsInitialized()) return false;
632 return i::GlobalHandles::IsWeak(obj);
636 void V8::DisposeGlobal(i::Object** obj) {
637 i::Isolate* isolate = i::Isolate::Current();
638 LOG_API(isolate, "DisposeGlobal");
639 if (!isolate->IsInitialized()) return;
640 isolate->global_handles()->Destroy(obj);
643 // --- H a n d l e s ---
646 HandleScope::HandleScope() {
647 i::Isolate* isolate = i::Isolate::Current();
648 API_ENTRY_CHECK(isolate, "HandleScope::HandleScope");
649 v8::ImplementationUtilities::HandleScopeData* current =
650 isolate->handle_scope_data();
652 prev_next_ = current->next;
653 prev_limit_ = current->limit;
659 HandleScope::~HandleScope() {
666 void HandleScope::Leave() {
667 ASSERT(isolate_ == i::Isolate::Current());
668 v8::ImplementationUtilities::HandleScopeData* current =
669 isolate_->handle_scope_data();
671 ASSERT(current->level >= 0);
672 current->next = prev_next_;
673 if (current->limit != prev_limit_) {
674 current->limit = prev_limit_;
675 i::HandleScope::DeleteExtensions(isolate_);
679 i::HandleScope::ZapRange(prev_next_, prev_limit_);
684 int HandleScope::NumberOfHandles() {
685 EnsureInitializedForIsolate(
686 i::Isolate::Current(), "HandleScope::NumberOfHandles");
687 return i::HandleScope::NumberOfHandles();
691 i::Object** HandleScope::CreateHandle(i::Object* value) {
692 return i::HandleScope::CreateHandle(value, i::Isolate::Current());
696 i::Object** HandleScope::CreateHandle(i::HeapObject* value) {
697 ASSERT(value->IsHeapObject());
698 return reinterpret_cast<i::Object**>(
699 i::HandleScope::CreateHandle(value, value->GetIsolate()));
703 void Context::Enter() {
704 i::Handle<i::Context> env = Utils::OpenHandle(this);
705 i::Isolate* isolate = env->GetIsolate();
706 if (IsDeadCheck(isolate, "v8::Context::Enter()")) return;
709 isolate->handle_scope_implementer()->EnterContext(env);
711 isolate->handle_scope_implementer()->SaveContext(isolate->context());
712 isolate->set_context(*env);
716 void Context::Exit() {
717 // Exit is essentially a static function and doesn't use the
718 // receiver, so we have to get the current isolate from the thread
720 i::Isolate* isolate = i::Isolate::Current();
721 if (!isolate->IsInitialized()) return;
723 if (!ApiCheck(isolate->handle_scope_implementer()->LeaveLastContext(),
724 "v8::Context::Exit()",
725 "Cannot exit non-entered context")) {
729 // Content of 'last_context' could be NULL.
730 i::Context* last_context =
731 isolate->handle_scope_implementer()->RestoreContext();
732 isolate->set_context(last_context);
736 void Context::SetData(v8::Handle<String> data) {
737 i::Handle<i::Context> env = Utils::OpenHandle(this);
738 i::Isolate* isolate = env->GetIsolate();
739 if (IsDeadCheck(isolate, "v8::Context::SetData()")) return;
740 i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
741 ASSERT(env->IsGlobalContext());
742 if (env->IsGlobalContext()) {
743 env->set_data(*raw_data);
748 v8::Local<v8::Value> Context::GetData() {
749 i::Handle<i::Context> env = Utils::OpenHandle(this);
750 i::Isolate* isolate = env->GetIsolate();
751 if (IsDeadCheck(isolate, "v8::Context::GetData()")) {
752 return v8::Local<Value>();
754 i::Object* raw_result = NULL;
755 ASSERT(env->IsGlobalContext());
756 if (env->IsGlobalContext()) {
757 raw_result = env->data();
759 return Local<Value>();
761 i::Handle<i::Object> result(raw_result, isolate);
762 return Utils::ToLocal(result);
766 i::Object** v8::HandleScope::RawClose(i::Object** value) {
767 if (!ApiCheck(!is_closed_,
768 "v8::HandleScope::Close()",
769 "Local scope has already been closed")) {
772 LOG_API(isolate_, "CloseHandleScope");
774 // Read the result before popping the handle block.
775 i::Object* result = NULL;
786 // Allocate a new handle on the previous handle block.
787 i::Handle<i::Object> handle(result);
788 return handle.location();
792 // --- N e a n d e r ---
795 // A constructor cannot easily return an error value, therefore it is necessary
796 // to check for a dead VM with ON_BAILOUT before constructing any Neander
797 // objects. To remind you about this there is no HandleScope in the
798 // NeanderObject constructor. When you add one to the site calling the
799 // constructor you should check that you ensured the VM was not dead first.
800 NeanderObject::NeanderObject(int size) {
801 i::Isolate* isolate = i::Isolate::Current();
802 EnsureInitializedForIsolate(isolate, "v8::Nowhere");
804 value_ = isolate->factory()->NewNeanderObject();
805 i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
806 value_->set_elements(*elements);
810 int NeanderObject::size() {
811 return i::FixedArray::cast(value_->elements())->length();
815 NeanderArray::NeanderArray() : obj_(2) {
816 obj_.set(0, i::Smi::FromInt(0));
820 int NeanderArray::length() {
821 return i::Smi::cast(obj_.get(0))->value();
825 i::Object* NeanderArray::get(int offset) {
827 ASSERT(offset < length());
828 return obj_.get(offset + 1);
832 // This method cannot easily return an error value, therefore it is necessary
833 // to check for a dead VM with ON_BAILOUT before calling it. To remind you
834 // about this there is no HandleScope in this method. When you add one to the
835 // site calling this method you should check that you ensured the VM was not
837 void NeanderArray::add(i::Handle<i::Object> value) {
838 int length = this->length();
839 int size = obj_.size();
840 if (length == size - 1) {
841 i::Handle<i::FixedArray> new_elms = FACTORY->NewFixedArray(2 * size);
842 for (int i = 0; i < length; i++)
843 new_elms->set(i + 1, get(i));
844 obj_.value()->set_elements(*new_elms);
846 obj_.set(length + 1, *value);
847 obj_.set(0, i::Smi::FromInt(length + 1));
851 void NeanderArray::set(int index, i::Object* value) {
852 if (index < 0 || index >= this->length()) return;
853 obj_.set(index + 1, value);
857 // --- T e m p l a t e ---
860 static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
861 that->set_tag(i::Smi::FromInt(type));
865 void Template::Set(v8::Handle<String> name, v8::Handle<Data> value,
866 v8::PropertyAttribute attribute) {
867 i::Isolate* isolate = i::Isolate::Current();
868 if (IsDeadCheck(isolate, "v8::Template::Set()")) return;
870 i::HandleScope scope(isolate);
871 i::Handle<i::Object> list(Utils::OpenHandle(this)->property_list());
872 if (list->IsUndefined()) {
873 list = NeanderArray().value();
874 Utils::OpenHandle(this)->set_property_list(*list);
876 NeanderArray array(list);
877 array.add(Utils::OpenHandle(*name));
878 array.add(Utils::OpenHandle(*value));
879 array.add(Utils::OpenHandle(*v8::Integer::New(attribute)));
883 // --- F u n c t i o n T e m p l a t e ---
884 static void InitializeFunctionTemplate(
885 i::Handle<i::FunctionTemplateInfo> info) {
886 info->set_tag(i::Smi::FromInt(Consts::FUNCTION_TEMPLATE));
891 Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
892 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
893 if (IsDeadCheck(isolate, "v8::FunctionTemplate::PrototypeTemplate()")) {
894 return Local<ObjectTemplate>();
897 i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template());
898 if (result->IsUndefined()) {
899 result = Utils::OpenHandle(*ObjectTemplate::New());
900 Utils::OpenHandle(this)->set_prototype_template(*result);
902 return Local<ObjectTemplate>(ToApi<ObjectTemplate>(result));
906 void FunctionTemplate::Inherit(v8::Handle<FunctionTemplate> value) {
907 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
908 if (IsDeadCheck(isolate, "v8::FunctionTemplate::Inherit()")) return;
910 Utils::OpenHandle(this)->set_parent_template(*Utils::OpenHandle(*value));
914 Local<FunctionTemplate> FunctionTemplate::New(InvocationCallback callback,
915 v8::Handle<Value> data, v8::Handle<Signature> signature) {
916 i::Isolate* isolate = i::Isolate::Current();
917 EnsureInitializedForIsolate(isolate, "v8::FunctionTemplate::New()");
918 LOG_API(isolate, "FunctionTemplate::New");
920 i::Handle<i::Struct> struct_obj =
921 isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
922 i::Handle<i::FunctionTemplateInfo> obj =
923 i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
924 InitializeFunctionTemplate(obj);
925 int next_serial_number = isolate->next_serial_number();
926 isolate->set_next_serial_number(next_serial_number + 1);
927 obj->set_serial_number(i::Smi::FromInt(next_serial_number));
929 if (data.IsEmpty()) data = v8::Undefined();
930 Utils::ToLocal(obj)->SetCallHandler(callback, data);
932 obj->set_undetectable(false);
933 obj->set_needs_access_check(false);
935 if (!signature.IsEmpty())
936 obj->set_signature(*Utils::OpenHandle(*signature));
937 return Utils::ToLocal(obj);
941 Local<Signature> Signature::New(Handle<FunctionTemplate> receiver,
942 int argc, Handle<FunctionTemplate> argv[]) {
943 i::Isolate* isolate = i::Isolate::Current();
944 EnsureInitializedForIsolate(isolate, "v8::Signature::New()");
945 LOG_API(isolate, "Signature::New");
947 i::Handle<i::Struct> struct_obj =
948 isolate->factory()->NewStruct(i::SIGNATURE_INFO_TYPE);
949 i::Handle<i::SignatureInfo> obj =
950 i::Handle<i::SignatureInfo>::cast(struct_obj);
951 if (!receiver.IsEmpty()) obj->set_receiver(*Utils::OpenHandle(*receiver));
953 i::Handle<i::FixedArray> args = isolate->factory()->NewFixedArray(argc);
954 for (int i = 0; i < argc; i++) {
955 if (!argv[i].IsEmpty())
956 args->set(i, *Utils::OpenHandle(*argv[i]));
958 obj->set_args(*args);
960 return Utils::ToLocal(obj);
964 Local<TypeSwitch> TypeSwitch::New(Handle<FunctionTemplate> type) {
965 Handle<FunctionTemplate> types[1] = { type };
966 return TypeSwitch::New(1, types);
970 Local<TypeSwitch> TypeSwitch::New(int argc, Handle<FunctionTemplate> types[]) {
971 i::Isolate* isolate = i::Isolate::Current();
972 EnsureInitializedForIsolate(isolate, "v8::TypeSwitch::New()");
973 LOG_API(isolate, "TypeSwitch::New");
975 i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
976 for (int i = 0; i < argc; i++)
977 vector->set(i, *Utils::OpenHandle(*types[i]));
978 i::Handle<i::Struct> struct_obj =
979 isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
980 i::Handle<i::TypeSwitchInfo> obj =
981 i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
982 obj->set_types(*vector);
983 return Utils::ToLocal(obj);
987 int TypeSwitch::match(v8::Handle<Value> value) {
988 i::Isolate* isolate = i::Isolate::Current();
989 LOG_API(isolate, "TypeSwitch::match");
991 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
992 i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
993 i::FixedArray* types = i::FixedArray::cast(info->types());
994 for (int i = 0; i < types->length(); i++) {
995 if (obj->IsInstanceOf(i::FunctionTemplateInfo::cast(types->get(i))))
1002 #define SET_FIELD_WRAPPED(obj, setter, cdata) do { \
1003 i::Handle<i::Object> foreign = FromCData(cdata); \
1004 (obj)->setter(*foreign); \
1008 void FunctionTemplate::SetCallHandler(InvocationCallback callback,
1009 v8::Handle<Value> data) {
1010 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1011 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetCallHandler()")) return;
1013 i::HandleScope scope(isolate);
1014 i::Handle<i::Struct> struct_obj =
1015 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1016 i::Handle<i::CallHandlerInfo> obj =
1017 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1018 SET_FIELD_WRAPPED(obj, set_callback, callback);
1019 if (data.IsEmpty()) data = v8::Undefined();
1020 obj->set_data(*Utils::OpenHandle(*data));
1021 Utils::OpenHandle(this)->set_call_code(*obj);
1025 static i::Handle<i::AccessorInfo> MakeAccessorInfo(
1026 v8::Handle<String> name,
1027 AccessorGetter getter,
1028 AccessorSetter setter,
1029 v8::Handle<Value> data,
1030 v8::AccessControl settings,
1031 v8::PropertyAttribute attributes) {
1032 i::Handle<i::AccessorInfo> obj = FACTORY->NewAccessorInfo();
1033 ASSERT(getter != NULL);
1034 SET_FIELD_WRAPPED(obj, set_getter, getter);
1035 SET_FIELD_WRAPPED(obj, set_setter, setter);
1036 if (data.IsEmpty()) data = v8::Undefined();
1037 obj->set_data(*Utils::OpenHandle(*data));
1038 obj->set_name(*Utils::OpenHandle(*name));
1039 if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
1040 if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
1041 if (settings & PROHIBITS_OVERWRITING) obj->set_prohibits_overwriting(true);
1042 obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
1047 void FunctionTemplate::AddInstancePropertyAccessor(
1048 v8::Handle<String> name,
1049 AccessorGetter getter,
1050 AccessorSetter setter,
1051 v8::Handle<Value> data,
1052 v8::AccessControl settings,
1053 v8::PropertyAttribute attributes) {
1054 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1055 if (IsDeadCheck(isolate,
1056 "v8::FunctionTemplate::AddInstancePropertyAccessor()")) {
1060 i::HandleScope scope(isolate);
1062 i::Handle<i::AccessorInfo> obj = MakeAccessorInfo(name,
1063 getter, setter, data,
1064 settings, attributes);
1065 i::Handle<i::Object> list(Utils::OpenHandle(this)->property_accessors());
1066 if (list->IsUndefined()) {
1067 list = NeanderArray().value();
1068 Utils::OpenHandle(this)->set_property_accessors(*list);
1070 NeanderArray array(list);
1075 Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
1076 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1077 if (IsDeadCheck(isolate, "v8::FunctionTemplate::InstanceTemplate()")
1078 || EmptyCheck("v8::FunctionTemplate::InstanceTemplate()", this))
1079 return Local<ObjectTemplate>();
1081 if (Utils::OpenHandle(this)->instance_template()->IsUndefined()) {
1082 Local<ObjectTemplate> templ =
1083 ObjectTemplate::New(v8::Handle<FunctionTemplate>(this));
1084 Utils::OpenHandle(this)->set_instance_template(*Utils::OpenHandle(*templ));
1086 i::Handle<i::ObjectTemplateInfo> result(i::ObjectTemplateInfo::cast(
1087 Utils::OpenHandle(this)->instance_template()));
1088 return Utils::ToLocal(result);
1092 void FunctionTemplate::SetClassName(Handle<String> name) {
1093 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1094 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetClassName()")) return;
1096 Utils::OpenHandle(this)->set_class_name(*Utils::OpenHandle(*name));
1100 void FunctionTemplate::SetHiddenPrototype(bool value) {
1101 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1102 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetHiddenPrototype()")) {
1106 Utils::OpenHandle(this)->set_hidden_prototype(value);
1110 void FunctionTemplate::ReadOnlyPrototype() {
1111 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1112 if (IsDeadCheck(isolate, "v8::FunctionTemplate::SetPrototypeAttributes()")) {
1116 Utils::OpenHandle(this)->set_read_only_prototype(true);
1120 void FunctionTemplate::SetNamedInstancePropertyHandler(
1121 NamedPropertyGetter getter,
1122 NamedPropertySetter setter,
1123 NamedPropertyQuery query,
1124 NamedPropertyDeleter remover,
1125 NamedPropertyEnumerator enumerator,
1127 Handle<Value> data) {
1128 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1129 if (IsDeadCheck(isolate,
1130 "v8::FunctionTemplate::SetNamedInstancePropertyHandler()")) {
1134 i::HandleScope scope(isolate);
1135 i::Handle<i::Struct> struct_obj =
1136 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE);
1137 i::Handle<i::InterceptorInfo> obj =
1138 i::Handle<i::InterceptorInfo>::cast(struct_obj);
1140 if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1141 if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1142 if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1143 if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1144 if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1145 obj->set_is_fallback(i::Smi::FromInt(is_fallback));
1147 if (data.IsEmpty()) data = v8::Undefined();
1148 obj->set_data(*Utils::OpenHandle(*data));
1149 Utils::OpenHandle(this)->set_named_property_handler(*obj);
1153 void FunctionTemplate::SetIndexedInstancePropertyHandler(
1154 IndexedPropertyGetter getter,
1155 IndexedPropertySetter setter,
1156 IndexedPropertyQuery query,
1157 IndexedPropertyDeleter remover,
1158 IndexedPropertyEnumerator enumerator,
1159 Handle<Value> data) {
1160 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1161 if (IsDeadCheck(isolate,
1162 "v8::FunctionTemplate::SetIndexedInstancePropertyHandler()")) {
1166 i::HandleScope scope(isolate);
1167 i::Handle<i::Struct> struct_obj =
1168 isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE);
1169 i::Handle<i::InterceptorInfo> obj =
1170 i::Handle<i::InterceptorInfo>::cast(struct_obj);
1172 if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
1173 if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
1174 if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
1175 if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
1176 if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
1178 if (data.IsEmpty()) data = v8::Undefined();
1179 obj->set_data(*Utils::OpenHandle(*data));
1180 Utils::OpenHandle(this)->set_indexed_property_handler(*obj);
1184 void FunctionTemplate::SetInstanceCallAsFunctionHandler(
1185 InvocationCallback callback,
1186 Handle<Value> data) {
1187 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1188 if (IsDeadCheck(isolate,
1189 "v8::FunctionTemplate::SetInstanceCallAsFunctionHandler()")) {
1193 i::HandleScope scope(isolate);
1194 i::Handle<i::Struct> struct_obj =
1195 isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
1196 i::Handle<i::CallHandlerInfo> obj =
1197 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
1198 SET_FIELD_WRAPPED(obj, set_callback, callback);
1199 if (data.IsEmpty()) data = v8::Undefined();
1200 obj->set_data(*Utils::OpenHandle(*data));
1201 Utils::OpenHandle(this)->set_instance_call_handler(*obj);
1205 // --- O b j e c t T e m p l a t e ---
1208 Local<ObjectTemplate> ObjectTemplate::New() {
1209 return New(Local<FunctionTemplate>());
1213 Local<ObjectTemplate> ObjectTemplate::New(
1214 v8::Handle<FunctionTemplate> constructor) {
1215 i::Isolate* isolate = i::Isolate::Current();
1216 if (IsDeadCheck(isolate, "v8::ObjectTemplate::New()")) {
1217 return Local<ObjectTemplate>();
1219 EnsureInitializedForIsolate(isolate, "v8::ObjectTemplate::New()");
1220 LOG_API(isolate, "ObjectTemplate::New");
1222 i::Handle<i::Struct> struct_obj =
1223 isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
1224 i::Handle<i::ObjectTemplateInfo> obj =
1225 i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
1226 InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
1227 if (!constructor.IsEmpty())
1228 obj->set_constructor(*Utils::OpenHandle(*constructor));
1229 obj->set_internal_field_count(i::Smi::FromInt(0));
1230 return Utils::ToLocal(obj);
1234 // Ensure that the object template has a constructor. If no
1235 // constructor is available we create one.
1236 static void EnsureConstructor(ObjectTemplate* object_template) {
1237 if (Utils::OpenHandle(object_template)->constructor()->IsUndefined()) {
1238 Local<FunctionTemplate> templ = FunctionTemplate::New();
1239 i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
1240 constructor->set_instance_template(*Utils::OpenHandle(object_template));
1241 Utils::OpenHandle(object_template)->set_constructor(*constructor);
1246 void ObjectTemplate::SetAccessor(v8::Handle<String> name,
1247 AccessorGetter getter,
1248 AccessorSetter setter,
1249 v8::Handle<Value> data,
1250 AccessControl settings,
1251 PropertyAttribute attribute) {
1252 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1253 if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetAccessor()")) return;
1255 i::HandleScope scope(isolate);
1256 EnsureConstructor(this);
1257 i::FunctionTemplateInfo* constructor =
1258 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1259 i::Handle<i::FunctionTemplateInfo> cons(constructor);
1260 Utils::ToLocal(cons)->AddInstancePropertyAccessor(name,
1269 void ObjectTemplate::SetNamedPropertyHandler(NamedPropertyGetter getter,
1270 NamedPropertySetter setter,
1271 NamedPropertyQuery query,
1272 NamedPropertyDeleter remover,
1273 NamedPropertyEnumerator enumerator,
1274 Handle<Value> data) {
1275 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1276 if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetNamedPropertyHandler()")) {
1280 i::HandleScope scope(isolate);
1281 EnsureConstructor(this);
1282 i::FunctionTemplateInfo* constructor =
1283 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1284 i::Handle<i::FunctionTemplateInfo> cons(constructor);
1285 Utils::ToLocal(cons)->SetNamedInstancePropertyHandler(getter,
1295 void ObjectTemplate::SetFallbackPropertyHandler(NamedPropertyGetter getter,
1296 NamedPropertySetter setter,
1297 NamedPropertyQuery query,
1298 NamedPropertyDeleter remover,
1299 NamedPropertyEnumerator enumerator,
1300 Handle<Value> data) {
1301 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1302 if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetNamedPropertyHandler()")) {
1306 i::HandleScope scope(isolate);
1307 EnsureConstructor(this);
1308 i::FunctionTemplateInfo* constructor =
1309 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1310 i::Handle<i::FunctionTemplateInfo> cons(constructor);
1311 Utils::ToLocal(cons)->SetNamedInstancePropertyHandler(getter,
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 bool ObjectTemplate::HasExternalResource()
1441 if (IsDeadCheck(Utils::OpenHandle(this)->GetIsolate(),
1442 "v8::ObjectTemplate::HasExternalResource()")) {
1445 return !Utils::OpenHandle(this)->has_external_resource()->IsUndefined();
1449 void ObjectTemplate::SetHasExternalResource(bool value)
1451 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1452 if (IsDeadCheck(isolate, "v8::ObjectTemplate::SetHasExternalResource()")) {
1457 EnsureConstructor(this);
1460 Utils::OpenHandle(this)->set_has_external_resource(i::Smi::FromInt(1));
1462 Utils::OpenHandle(this)->set_has_external_resource(Utils::OpenHandle(this)->GetHeap()->undefined_value());
1467 // --- S c r i p t D a t a ---
1470 ScriptData* ScriptData::PreCompile(const char* input, int length) {
1471 i::Utf8ToUC16CharacterStream stream(
1472 reinterpret_cast<const unsigned char*>(input), length);
1473 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1477 ScriptData* ScriptData::PreCompile(v8::Handle<String> source) {
1478 i::Handle<i::String> str = Utils::OpenHandle(*source);
1479 if (str->IsExternalTwoByteString()) {
1480 i::ExternalTwoByteStringUC16CharacterStream stream(
1481 i::Handle<i::ExternalTwoByteString>::cast(str), 0, str->length());
1482 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1484 i::GenericStringUC16CharacterStream stream(str, 0, str->length());
1485 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1490 ScriptData* ScriptData::New(const char* data, int length) {
1491 // Return an empty ScriptData if the length is obviously invalid.
1492 if (length % sizeof(unsigned) != 0) {
1493 return new i::ScriptDataImpl();
1496 // Copy the data to ensure it is properly aligned.
1497 int deserialized_data_length = length / sizeof(unsigned);
1498 // If aligned, don't create a copy of the data.
1499 if (reinterpret_cast<intptr_t>(data) % sizeof(unsigned) == 0) {
1500 return new i::ScriptDataImpl(data, length);
1502 // Copy the data to align it.
1503 unsigned* deserialized_data = i::NewArray<unsigned>(deserialized_data_length);
1504 i::OS::MemCopy(deserialized_data, data, length);
1506 return new i::ScriptDataImpl(
1507 i::Vector<unsigned>(deserialized_data, deserialized_data_length));
1511 // --- S c r i p t ---
1514 Local<Script> Script::New(v8::Handle<String> source,
1515 v8::ScriptOrigin* origin,
1516 v8::ScriptData* pre_data,
1517 v8::Handle<String> script_data) {
1518 i::Isolate* isolate = i::Isolate::Current();
1519 ON_BAILOUT(isolate, "v8::Script::New()", return Local<Script>());
1520 LOG_API(isolate, "Script::New");
1522 i::Handle<i::String> str = Utils::OpenHandle(*source);
1523 i::Handle<i::Object> name_obj;
1524 int line_offset = 0;
1525 int column_offset = 0;
1526 if (origin != NULL) {
1527 if (!origin->ResourceName().IsEmpty()) {
1528 name_obj = Utils::OpenHandle(*origin->ResourceName());
1530 if (!origin->ResourceLineOffset().IsEmpty()) {
1531 line_offset = static_cast<int>(origin->ResourceLineOffset()->Value());
1533 if (!origin->ResourceColumnOffset().IsEmpty()) {
1534 column_offset = static_cast<int>(origin->ResourceColumnOffset()->Value());
1537 EXCEPTION_PREAMBLE(isolate);
1538 i::ScriptDataImpl* pre_data_impl = static_cast<i::ScriptDataImpl*>(pre_data);
1539 // We assert that the pre-data is sane, even though we can actually
1540 // handle it if it turns out not to be in release mode.
1541 ASSERT(pre_data_impl == NULL || pre_data_impl->SanityCheck());
1542 // If the pre-data isn't sane we simply ignore it
1543 if (pre_data_impl != NULL && !pre_data_impl->SanityCheck()) {
1544 pre_data_impl = NULL;
1546 i::Handle<i::SharedFunctionInfo> result =
1547 i::Compiler::Compile(str,
1553 Utils::OpenHandle(*script_data),
1554 i::NOT_NATIVES_CODE);
1555 has_pending_exception = result.is_null();
1556 EXCEPTION_BAILOUT_CHECK(isolate, Local<Script>());
1557 return Local<Script>(ToApi<Script>(result));
1561 Local<Script> Script::New(v8::Handle<String> source,
1562 v8::Handle<Value> file_name) {
1563 ScriptOrigin origin(file_name);
1564 return New(source, &origin);
1568 Local<Script> Script::Compile(v8::Handle<String> source,
1569 v8::ScriptOrigin* origin,
1570 v8::ScriptData* pre_data,
1571 v8::Handle<String> script_data) {
1572 i::Isolate* isolate = i::Isolate::Current();
1573 ON_BAILOUT(isolate, "v8::Script::Compile()", return Local<Script>());
1574 LOG_API(isolate, "Script::Compile");
1576 Local<Script> generic = New(source, origin, pre_data, script_data);
1577 if (generic.IsEmpty())
1579 i::Handle<i::Object> obj = Utils::OpenHandle(*generic);
1580 i::Handle<i::SharedFunctionInfo> function =
1581 i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1582 i::Handle<i::JSFunction> result =
1583 isolate->factory()->NewFunctionFromSharedFunctionInfo(
1585 isolate->global_context());
1586 return Local<Script>(ToApi<Script>(result));
1590 Local<Script> Script::Compile(v8::Handle<String> source,
1591 v8::Handle<Value> file_name,
1592 v8::Handle<String> script_data) {
1593 ScriptOrigin origin(file_name);
1594 return Compile(source, &origin, 0, script_data);
1598 Local<Value> Script::Run() {
1599 i::Isolate* isolate = i::Isolate::Current();
1600 ON_BAILOUT(isolate, "v8::Script::Run()", return Local<Value>());
1601 LOG_API(isolate, "Script::Run");
1603 i::Object* raw_result = NULL;
1605 i::HandleScope scope(isolate);
1606 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1607 i::Handle<i::JSFunction> fun;
1608 if (obj->IsSharedFunctionInfo()) {
1609 i::Handle<i::SharedFunctionInfo>
1610 function_info(i::SharedFunctionInfo::cast(*obj), isolate);
1611 fun = isolate->factory()->NewFunctionFromSharedFunctionInfo(
1612 function_info, isolate->global_context());
1614 fun = i::Handle<i::JSFunction>(i::JSFunction::cast(*obj), isolate);
1616 EXCEPTION_PREAMBLE(isolate);
1617 i::Handle<i::Object> receiver(
1618 isolate->context()->global_proxy(), isolate);
1619 i::Handle<i::Object> result =
1620 i::Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1621 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
1622 raw_result = *result;
1624 i::Handle<i::Object> result(raw_result, isolate);
1625 return Utils::ToLocal(result);
1629 static i::Handle<i::SharedFunctionInfo> OpenScript(Script* script) {
1630 i::Handle<i::Object> obj = Utils::OpenHandle(script);
1631 i::Handle<i::SharedFunctionInfo> result;
1632 if (obj->IsSharedFunctionInfo()) {
1634 i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1637 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared());
1643 Local<Value> Script::Id() {
1644 i::Isolate* isolate = i::Isolate::Current();
1645 ON_BAILOUT(isolate, "v8::Script::Id()", return Local<Value>());
1646 LOG_API(isolate, "Script::Id");
1647 i::Object* raw_id = NULL;
1649 i::HandleScope scope(isolate);
1650 i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1651 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1652 i::Handle<i::Object> id(script->id());
1655 i::Handle<i::Object> id(raw_id);
1656 return Utils::ToLocal(id);
1660 void Script::SetData(v8::Handle<String> data) {
1661 i::Isolate* isolate = i::Isolate::Current();
1662 ON_BAILOUT(isolate, "v8::Script::SetData()", return);
1663 LOG_API(isolate, "Script::SetData");
1665 i::HandleScope scope(isolate);
1666 i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1667 i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
1668 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1669 script->set_data(*raw_data);
1674 // --- E x c e p t i o n s ---
1677 v8::TryCatch::TryCatch()
1678 : isolate_(i::Isolate::Current()),
1679 next_(isolate_->try_catch_handler_address()),
1680 exception_(isolate_->heap()->the_hole_value()),
1681 message_(i::Smi::FromInt(0)),
1683 can_continue_(true),
1684 capture_message_(true),
1686 isolate_->RegisterTryCatchHandler(this);
1690 v8::TryCatch::~TryCatch() {
1691 ASSERT(isolate_ == i::Isolate::Current());
1693 v8::HandleScope scope;
1694 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(Exception());
1695 isolate_->UnregisterTryCatchHandler(this);
1696 v8::ThrowException(exc);
1698 isolate_->UnregisterTryCatchHandler(this);
1703 bool v8::TryCatch::HasCaught() const {
1704 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
1708 bool v8::TryCatch::CanContinue() const {
1709 return can_continue_;
1713 v8::Handle<v8::Value> v8::TryCatch::ReThrow() {
1714 if (!HasCaught()) return v8::Local<v8::Value>();
1716 return v8::Undefined();
1720 v8::Local<Value> v8::TryCatch::Exception() const {
1721 ASSERT(isolate_ == i::Isolate::Current());
1723 // Check for out of memory exception.
1724 i::Object* exception = reinterpret_cast<i::Object*>(exception_);
1725 return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
1727 return v8::Local<Value>();
1732 v8::Local<Value> v8::TryCatch::StackTrace() const {
1733 ASSERT(isolate_ == i::Isolate::Current());
1735 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
1736 if (!raw_obj->IsJSObject()) return v8::Local<Value>();
1737 i::HandleScope scope(isolate_);
1738 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
1739 i::Handle<i::String> name = isolate_->factory()->LookupAsciiSymbol("stack");
1740 if (!obj->HasProperty(*name)) return v8::Local<Value>();
1741 i::Handle<i::Object> value = i::GetProperty(obj, name);
1742 if (value.is_null()) return v8::Local<Value>();
1743 return v8::Utils::ToLocal(scope.CloseAndEscape(value));
1745 return v8::Local<Value>();
1750 v8::Local<v8::Message> v8::TryCatch::Message() const {
1751 ASSERT(isolate_ == i::Isolate::Current());
1752 if (HasCaught() && message_ != i::Smi::FromInt(0)) {
1753 i::Object* message = reinterpret_cast<i::Object*>(message_);
1754 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
1756 return v8::Local<v8::Message>();
1761 void v8::TryCatch::Reset() {
1762 ASSERT(isolate_ == i::Isolate::Current());
1763 exception_ = isolate_->heap()->the_hole_value();
1764 message_ = i::Smi::FromInt(0);
1768 void v8::TryCatch::SetVerbose(bool value) {
1769 is_verbose_ = value;
1773 void v8::TryCatch::SetCaptureMessage(bool value) {
1774 capture_message_ = value;
1778 // --- M e s s a g e ---
1781 Local<String> Message::Get() const {
1782 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1783 ON_BAILOUT(isolate, "v8::Message::Get()", return Local<String>());
1786 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1787 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(obj);
1788 Local<String> result = Utils::ToLocal(raw_result);
1789 return scope.Close(result);
1793 v8::Handle<Value> Message::GetScriptResourceName() const {
1794 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1795 if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceName()")) {
1796 return Local<String>();
1800 i::Handle<i::JSMessageObject> message =
1801 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1802 // Return this.script.name.
1803 i::Handle<i::JSValue> script =
1804 i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1805 i::Handle<i::Object> resource_name(i::Script::cast(script->value())->name());
1806 return scope.Close(Utils::ToLocal(resource_name));
1810 v8::Handle<Value> Message::GetScriptData() const {
1811 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1812 if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceData()")) {
1813 return Local<Value>();
1817 i::Handle<i::JSMessageObject> message =
1818 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1819 // Return this.script.data.
1820 i::Handle<i::JSValue> script =
1821 i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1822 i::Handle<i::Object> data(i::Script::cast(script->value())->data());
1823 return scope.Close(Utils::ToLocal(data));
1827 v8::Handle<v8::StackTrace> Message::GetStackTrace() const {
1828 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1829 if (IsDeadCheck(isolate, "v8::Message::GetStackTrace()")) {
1830 return Local<v8::StackTrace>();
1834 i::Handle<i::JSMessageObject> message =
1835 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1836 i::Handle<i::Object> stackFramesObj(message->stack_frames());
1837 if (!stackFramesObj->IsJSArray()) return v8::Handle<v8::StackTrace>();
1838 i::Handle<i::JSArray> stackTrace =
1839 i::Handle<i::JSArray>::cast(stackFramesObj);
1840 return scope.Close(Utils::StackTraceToLocal(stackTrace));
1844 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1845 i::Handle<i::Object> recv,
1847 i::Handle<i::Object> argv[],
1848 bool* has_pending_exception) {
1849 i::Isolate* isolate = i::Isolate::Current();
1850 i::Handle<i::String> fmt_str = isolate->factory()->LookupAsciiSymbol(name);
1851 i::Object* object_fun =
1852 isolate->js_builtins_object()->GetPropertyNoExceptionThrown(*fmt_str);
1853 i::Handle<i::JSFunction> fun =
1854 i::Handle<i::JSFunction>(i::JSFunction::cast(object_fun));
1855 i::Handle<i::Object> value =
1856 i::Execution::Call(fun, recv, argc, argv, has_pending_exception);
1861 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1862 i::Handle<i::Object> data,
1863 bool* has_pending_exception) {
1864 i::Handle<i::Object> argv[] = { data };
1865 return CallV8HeapFunction(name,
1866 i::Isolate::Current()->js_builtins_object(),
1869 has_pending_exception);
1873 int Message::GetLineNumber() const {
1874 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1875 ON_BAILOUT(isolate, "v8::Message::GetLineNumber()", return kNoLineNumberInfo);
1877 i::HandleScope scope(isolate);
1879 EXCEPTION_PREAMBLE(isolate);
1880 i::Handle<i::Object> result = CallV8HeapFunction("GetLineNumber",
1881 Utils::OpenHandle(this),
1882 &has_pending_exception);
1883 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1884 return static_cast<int>(result->Number());
1888 int Message::GetStartPosition() const {
1889 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1890 if (IsDeadCheck(isolate, "v8::Message::GetStartPosition()")) return 0;
1892 i::HandleScope scope(isolate);
1893 i::Handle<i::JSMessageObject> message =
1894 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1895 return message->start_position();
1899 int Message::GetEndPosition() const {
1900 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1901 if (IsDeadCheck(isolate, "v8::Message::GetEndPosition()")) return 0;
1903 i::HandleScope scope(isolate);
1904 i::Handle<i::JSMessageObject> message =
1905 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1906 return message->end_position();
1910 int Message::GetStartColumn() const {
1911 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1912 if (IsDeadCheck(isolate, "v8::Message::GetStartColumn()")) {
1913 return kNoColumnInfo;
1916 i::HandleScope scope(isolate);
1917 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1918 EXCEPTION_PREAMBLE(isolate);
1919 i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1920 "GetPositionInLine",
1922 &has_pending_exception);
1923 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1924 return static_cast<int>(start_col_obj->Number());
1928 int Message::GetEndColumn() const {
1929 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1930 if (IsDeadCheck(isolate, "v8::Message::GetEndColumn()")) return kNoColumnInfo;
1932 i::HandleScope scope(isolate);
1933 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1934 EXCEPTION_PREAMBLE(isolate);
1935 i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1936 "GetPositionInLine",
1938 &has_pending_exception);
1939 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1940 i::Handle<i::JSMessageObject> message =
1941 i::Handle<i::JSMessageObject>::cast(data_obj);
1942 int start = message->start_position();
1943 int end = message->end_position();
1944 return static_cast<int>(start_col_obj->Number()) + (end - start);
1948 Local<String> Message::GetSourceLine() const {
1949 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1950 ON_BAILOUT(isolate, "v8::Message::GetSourceLine()", return Local<String>());
1953 EXCEPTION_PREAMBLE(isolate);
1954 i::Handle<i::Object> result = CallV8HeapFunction("GetSourceLine",
1955 Utils::OpenHandle(this),
1956 &has_pending_exception);
1957 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::String>());
1958 if (result->IsString()) {
1959 return scope.Close(Utils::ToLocal(i::Handle<i::String>::cast(result)));
1961 return Local<String>();
1966 void Message::PrintCurrentStackTrace(FILE* out) {
1967 i::Isolate* isolate = i::Isolate::Current();
1968 if (IsDeadCheck(isolate, "v8::Message::PrintCurrentStackTrace()")) return;
1970 isolate->PrintCurrentStackTrace(out);
1974 // --- S t a c k T r a c e ---
1976 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
1977 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1978 if (IsDeadCheck(isolate, "v8::StackTrace::GetFrame()")) {
1979 return Local<StackFrame>();
1983 i::Handle<i::JSArray> self = Utils::OpenHandle(this);
1984 i::Object* raw_object = self->GetElementNoExceptionThrown(index);
1985 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_object));
1986 return scope.Close(Utils::StackFrameToLocal(obj));
1990 int StackTrace::GetFrameCount() const {
1991 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1992 if (IsDeadCheck(isolate, "v8::StackTrace::GetFrameCount()")) return -1;
1994 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
1998 Local<Array> StackTrace::AsArray() {
1999 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2000 if (IsDeadCheck(isolate, "v8::StackTrace::AsArray()")) Local<Array>();
2002 return Utils::ToLocal(Utils::OpenHandle(this));
2006 Local<StackTrace> StackTrace::CurrentStackTrace(int frame_limit,
2007 StackTraceOptions options) {
2008 i::Isolate* isolate = i::Isolate::Current();
2009 if (IsDeadCheck(isolate, "v8::StackTrace::CurrentStackTrace()")) {
2010 Local<StackTrace>();
2013 i::Handle<i::JSArray> stackTrace =
2014 isolate->CaptureCurrentStackTrace(frame_limit, options);
2015 return Utils::StackTraceToLocal(stackTrace);
2019 // --- S t a c k F r a m e ---
2021 int StackFrame::GetLineNumber() const {
2022 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2023 if (IsDeadCheck(isolate, "v8::StackFrame::GetLineNumber()")) {
2024 return Message::kNoLineNumberInfo;
2027 i::HandleScope scope(isolate);
2028 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2029 i::Handle<i::Object> line = GetProperty(self, "lineNumber");
2030 if (!line->IsSmi()) {
2031 return Message::kNoLineNumberInfo;
2033 return i::Smi::cast(*line)->value();
2037 int StackFrame::GetColumn() const {
2038 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2039 if (IsDeadCheck(isolate, "v8::StackFrame::GetColumn()")) {
2040 return Message::kNoColumnInfo;
2043 i::HandleScope scope(isolate);
2044 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2045 i::Handle<i::Object> column = GetProperty(self, "column");
2046 if (!column->IsSmi()) {
2047 return Message::kNoColumnInfo;
2049 return i::Smi::cast(*column)->value();
2053 Local<String> StackFrame::GetScriptName() const {
2054 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2055 if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptName()")) {
2056 return Local<String>();
2060 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2061 i::Handle<i::Object> name = GetProperty(self, "scriptName");
2062 if (!name->IsString()) {
2063 return Local<String>();
2065 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2069 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2070 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2071 if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptNameOrSourceURL()")) {
2072 return Local<String>();
2076 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2077 i::Handle<i::Object> name = GetProperty(self, "scriptNameOrSourceURL");
2078 if (!name->IsString()) {
2079 return Local<String>();
2081 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2085 Local<String> StackFrame::GetFunctionName() const {
2086 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2087 if (IsDeadCheck(isolate, "v8::StackFrame::GetFunctionName()")) {
2088 return Local<String>();
2092 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2093 i::Handle<i::Object> name = GetProperty(self, "functionName");
2094 if (!name->IsString()) {
2095 return Local<String>();
2097 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2101 bool StackFrame::IsEval() const {
2102 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2103 if (IsDeadCheck(isolate, "v8::StackFrame::IsEval()")) return false;
2105 i::HandleScope scope(isolate);
2106 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2107 i::Handle<i::Object> is_eval = GetProperty(self, "isEval");
2108 return is_eval->IsTrue();
2112 bool StackFrame::IsConstructor() const {
2113 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2114 if (IsDeadCheck(isolate, "v8::StackFrame::IsConstructor()")) return false;
2116 i::HandleScope scope(isolate);
2117 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2118 i::Handle<i::Object> is_constructor = GetProperty(self, "isConstructor");
2119 return is_constructor->IsTrue();
2125 bool Value::IsUndefined() const {
2126 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUndefined()")) {
2129 return Utils::OpenHandle(this)->IsUndefined();
2133 bool Value::IsNull() const {
2134 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNull()")) return false;
2135 return Utils::OpenHandle(this)->IsNull();
2139 bool Value::IsTrue() const {
2140 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsTrue()")) return false;
2141 return Utils::OpenHandle(this)->IsTrue();
2145 bool Value::IsFalse() const {
2146 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFalse()")) return false;
2147 return Utils::OpenHandle(this)->IsFalse();
2151 bool Value::IsFunction() const {
2152 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFunction()")) {
2155 return Utils::OpenHandle(this)->IsJSFunction();
2159 bool Value::FullIsString() const {
2160 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsString()")) return false;
2161 bool result = Utils::OpenHandle(this)->IsString();
2162 ASSERT_EQ(result, QuickIsString());
2167 bool Value::IsArray() const {
2168 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsArray()")) return false;
2169 return Utils::OpenHandle(this)->IsJSArray();
2173 bool Value::IsObject() const {
2174 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsObject()")) return false;
2175 return Utils::OpenHandle(this)->IsJSObject();
2179 bool Value::IsNumber() const {
2180 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNumber()")) return false;
2181 return Utils::OpenHandle(this)->IsNumber();
2185 bool Value::IsBoolean() const {
2186 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsBoolean()")) {
2189 return Utils::OpenHandle(this)->IsBoolean();
2193 bool Value::IsExternal() const {
2194 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsExternal()")) {
2197 return Utils::OpenHandle(this)->IsForeign();
2201 bool Value::IsInt32() const {
2202 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsInt32()")) return false;
2203 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2204 if (obj->IsSmi()) return true;
2205 if (obj->IsNumber()) {
2206 double value = obj->Number();
2207 return i::FastI2D(i::FastD2I(value)) == value;
2213 bool Value::IsUint32() const {
2214 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUint32()")) return false;
2215 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2216 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2217 if (obj->IsNumber()) {
2218 double value = obj->Number();
2219 return i::FastUI2D(i::FastD2UI(value)) == value;
2225 bool Value::IsDate() const {
2226 i::Isolate* isolate = i::Isolate::Current();
2227 if (IsDeadCheck(isolate, "v8::Value::IsDate()")) return false;
2228 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2229 return obj->HasSpecificClassOf(isolate->heap()->Date_symbol());
2233 bool Value::IsStringObject() const {
2234 i::Isolate* isolate = i::Isolate::Current();
2235 if (IsDeadCheck(isolate, "v8::Value::IsStringObject()")) return false;
2236 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2237 return obj->HasSpecificClassOf(isolate->heap()->String_symbol());
2241 bool Value::IsNumberObject() const {
2242 i::Isolate* isolate = i::Isolate::Current();
2243 if (IsDeadCheck(isolate, "v8::Value::IsNumberObject()")) return false;
2244 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2245 return obj->HasSpecificClassOf(isolate->heap()->Number_symbol());
2249 static i::Object* LookupBuiltin(i::Isolate* isolate,
2250 const char* builtin_name) {
2251 i::Handle<i::String> symbol =
2252 isolate->factory()->LookupAsciiSymbol(builtin_name);
2253 i::Handle<i::JSBuiltinsObject> builtins = isolate->js_builtins_object();
2254 return builtins->GetPropertyNoExceptionThrown(*symbol);
2258 static bool CheckConstructor(i::Isolate* isolate,
2259 i::Handle<i::JSObject> obj,
2260 const char* class_name) {
2261 return obj->map()->constructor() == LookupBuiltin(isolate, class_name);
2265 bool Value::IsNativeError() const {
2266 i::Isolate* isolate = i::Isolate::Current();
2267 if (IsDeadCheck(isolate, "v8::Value::IsNativeError()")) return false;
2268 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2269 if (obj->IsJSObject()) {
2270 i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
2271 return CheckConstructor(isolate, js_obj, "$Error") ||
2272 CheckConstructor(isolate, js_obj, "$EvalError") ||
2273 CheckConstructor(isolate, js_obj, "$RangeError") ||
2274 CheckConstructor(isolate, js_obj, "$ReferenceError") ||
2275 CheckConstructor(isolate, js_obj, "$SyntaxError") ||
2276 CheckConstructor(isolate, js_obj, "$TypeError") ||
2277 CheckConstructor(isolate, js_obj, "$URIError");
2284 bool Value::IsBooleanObject() const {
2285 i::Isolate* isolate = i::Isolate::Current();
2286 if (IsDeadCheck(isolate, "v8::Value::IsBooleanObject()")) return false;
2287 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2288 return obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol());
2292 bool Value::IsRegExp() const {
2293 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsRegExp()")) return false;
2294 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2295 return obj->IsJSRegExp();
2299 Local<String> Value::ToString() const {
2300 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2301 i::Handle<i::Object> str;
2302 if (obj->IsString()) {
2305 i::Isolate* isolate = i::Isolate::Current();
2306 if (IsDeadCheck(isolate, "v8::Value::ToString()")) {
2307 return Local<String>();
2309 LOG_API(isolate, "ToString");
2311 EXCEPTION_PREAMBLE(isolate);
2312 str = i::Execution::ToString(obj, &has_pending_exception);
2313 EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2315 return Local<String>(ToApi<String>(str));
2319 Local<String> Value::ToDetailString() const {
2320 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2321 i::Handle<i::Object> str;
2322 if (obj->IsString()) {
2325 i::Isolate* isolate = i::Isolate::Current();
2326 if (IsDeadCheck(isolate, "v8::Value::ToDetailString()")) {
2327 return Local<String>();
2329 LOG_API(isolate, "ToDetailString");
2331 EXCEPTION_PREAMBLE(isolate);
2332 str = i::Execution::ToDetailString(obj, &has_pending_exception);
2333 EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2335 return Local<String>(ToApi<String>(str));
2339 Local<v8::Object> Value::ToObject() const {
2340 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2341 i::Handle<i::Object> val;
2342 if (obj->IsJSObject()) {
2345 i::Isolate* isolate = i::Isolate::Current();
2346 if (IsDeadCheck(isolate, "v8::Value::ToObject()")) {
2347 return Local<v8::Object>();
2349 LOG_API(isolate, "ToObject");
2351 EXCEPTION_PREAMBLE(isolate);
2352 val = i::Execution::ToObject(obj, &has_pending_exception);
2353 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
2355 return Local<v8::Object>(ToApi<Object>(val));
2359 Local<Boolean> Value::ToBoolean() const {
2360 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2361 if (obj->IsBoolean()) {
2362 return Local<Boolean>(ToApi<Boolean>(obj));
2364 i::Isolate* isolate = i::Isolate::Current();
2365 if (IsDeadCheck(isolate, "v8::Value::ToBoolean()")) {
2366 return Local<Boolean>();
2368 LOG_API(isolate, "ToBoolean");
2370 i::Handle<i::Object> val = i::Execution::ToBoolean(obj);
2371 return Local<Boolean>(ToApi<Boolean>(val));
2376 Local<Number> Value::ToNumber() const {
2377 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2378 i::Handle<i::Object> num;
2379 if (obj->IsNumber()) {
2382 i::Isolate* isolate = i::Isolate::Current();
2383 if (IsDeadCheck(isolate, "v8::Value::ToNumber()")) {
2384 return Local<Number>();
2386 LOG_API(isolate, "ToNumber");
2388 EXCEPTION_PREAMBLE(isolate);
2389 num = i::Execution::ToNumber(obj, &has_pending_exception);
2390 EXCEPTION_BAILOUT_CHECK(isolate, Local<Number>());
2392 return Local<Number>(ToApi<Number>(num));
2396 Local<Integer> Value::ToInteger() const {
2397 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2398 i::Handle<i::Object> num;
2402 i::Isolate* isolate = i::Isolate::Current();
2403 if (IsDeadCheck(isolate, "v8::Value::ToInteger()")) return Local<Integer>();
2404 LOG_API(isolate, "ToInteger");
2406 EXCEPTION_PREAMBLE(isolate);
2407 num = i::Execution::ToInteger(obj, &has_pending_exception);
2408 EXCEPTION_BAILOUT_CHECK(isolate, Local<Integer>());
2410 return Local<Integer>(ToApi<Integer>(num));
2414 void External::CheckCast(v8::Value* that) {
2415 if (IsDeadCheck(i::Isolate::Current(), "v8::External::Cast()")) return;
2416 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2417 ApiCheck(obj->IsForeign(),
2418 "v8::External::Cast()",
2419 "Could not convert to external");
2423 void v8::Object::CheckCast(Value* that) {
2424 if (IsDeadCheck(i::Isolate::Current(), "v8::Object::Cast()")) return;
2425 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2426 ApiCheck(obj->IsJSObject(),
2427 "v8::Object::Cast()",
2428 "Could not convert to object");
2432 void v8::Function::CheckCast(Value* that) {
2433 if (IsDeadCheck(i::Isolate::Current(), "v8::Function::Cast()")) return;
2434 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2435 ApiCheck(obj->IsJSFunction(),
2436 "v8::Function::Cast()",
2437 "Could not convert to function");
2441 void v8::String::CheckCast(v8::Value* that) {
2442 if (IsDeadCheck(i::Isolate::Current(), "v8::String::Cast()")) return;
2443 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2444 ApiCheck(obj->IsString(),
2445 "v8::String::Cast()",
2446 "Could not convert to string");
2450 void v8::Number::CheckCast(v8::Value* that) {
2451 if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Cast()")) return;
2452 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2453 ApiCheck(obj->IsNumber(),
2454 "v8::Number::Cast()",
2455 "Could not convert to number");
2459 void v8::Integer::CheckCast(v8::Value* that) {
2460 if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Cast()")) return;
2461 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2462 ApiCheck(obj->IsNumber(),
2463 "v8::Integer::Cast()",
2464 "Could not convert to number");
2468 void v8::Array::CheckCast(Value* that) {
2469 if (IsDeadCheck(i::Isolate::Current(), "v8::Array::Cast()")) return;
2470 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2471 ApiCheck(obj->IsJSArray(),
2472 "v8::Array::Cast()",
2473 "Could not convert to array");
2477 void v8::Date::CheckCast(v8::Value* that) {
2478 i::Isolate* isolate = i::Isolate::Current();
2479 if (IsDeadCheck(isolate, "v8::Date::Cast()")) return;
2480 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2481 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Date_symbol()),
2483 "Could not convert to date");
2487 void v8::StringObject::CheckCast(v8::Value* that) {
2488 i::Isolate* isolate = i::Isolate::Current();
2489 if (IsDeadCheck(isolate, "v8::StringObject::Cast()")) return;
2490 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2491 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->String_symbol()),
2492 "v8::StringObject::Cast()",
2493 "Could not convert to StringObject");
2497 void v8::NumberObject::CheckCast(v8::Value* that) {
2498 i::Isolate* isolate = i::Isolate::Current();
2499 if (IsDeadCheck(isolate, "v8::NumberObject::Cast()")) return;
2500 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2501 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Number_symbol()),
2502 "v8::NumberObject::Cast()",
2503 "Could not convert to NumberObject");
2507 void v8::BooleanObject::CheckCast(v8::Value* that) {
2508 i::Isolate* isolate = i::Isolate::Current();
2509 if (IsDeadCheck(isolate, "v8::BooleanObject::Cast()")) return;
2510 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2511 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol()),
2512 "v8::BooleanObject::Cast()",
2513 "Could not convert to BooleanObject");
2517 void v8::RegExp::CheckCast(v8::Value* that) {
2518 if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::Cast()")) return;
2519 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2520 ApiCheck(obj->IsJSRegExp(),
2521 "v8::RegExp::Cast()",
2522 "Could not convert to regular expression");
2526 bool Value::BooleanValue() const {
2527 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2528 if (obj->IsBoolean()) {
2529 return obj->IsTrue();
2531 i::Isolate* isolate = i::Isolate::Current();
2532 if (IsDeadCheck(isolate, "v8::Value::BooleanValue()")) return false;
2533 LOG_API(isolate, "BooleanValue");
2535 i::Handle<i::Object> value = i::Execution::ToBoolean(obj);
2536 return value->IsTrue();
2541 double Value::NumberValue() const {
2542 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2543 i::Handle<i::Object> num;
2544 if (obj->IsNumber()) {
2547 i::Isolate* isolate = i::Isolate::Current();
2548 if (IsDeadCheck(isolate, "v8::Value::NumberValue()")) {
2549 return i::OS::nan_value();
2551 LOG_API(isolate, "NumberValue");
2553 EXCEPTION_PREAMBLE(isolate);
2554 num = i::Execution::ToNumber(obj, &has_pending_exception);
2555 EXCEPTION_BAILOUT_CHECK(isolate, i::OS::nan_value());
2557 return num->Number();
2561 int64_t Value::IntegerValue() const {
2562 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2563 i::Handle<i::Object> num;
2564 if (obj->IsNumber()) {
2567 i::Isolate* isolate = i::Isolate::Current();
2568 if (IsDeadCheck(isolate, "v8::Value::IntegerValue()")) return 0;
2569 LOG_API(isolate, "IntegerValue");
2571 EXCEPTION_PREAMBLE(isolate);
2572 num = i::Execution::ToInteger(obj, &has_pending_exception);
2573 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2576 return i::Smi::cast(*num)->value();
2578 return static_cast<int64_t>(num->Number());
2583 Local<Int32> Value::ToInt32() const {
2584 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2585 i::Handle<i::Object> num;
2589 i::Isolate* isolate = i::Isolate::Current();
2590 if (IsDeadCheck(isolate, "v8::Value::ToInt32()")) return Local<Int32>();
2591 LOG_API(isolate, "ToInt32");
2593 EXCEPTION_PREAMBLE(isolate);
2594 num = i::Execution::ToInt32(obj, &has_pending_exception);
2595 EXCEPTION_BAILOUT_CHECK(isolate, Local<Int32>());
2597 return Local<Int32>(ToApi<Int32>(num));
2601 Local<Uint32> Value::ToUint32() const {
2602 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2603 i::Handle<i::Object> num;
2607 i::Isolate* isolate = i::Isolate::Current();
2608 if (IsDeadCheck(isolate, "v8::Value::ToUint32()")) return Local<Uint32>();
2609 LOG_API(isolate, "ToUInt32");
2611 EXCEPTION_PREAMBLE(isolate);
2612 num = i::Execution::ToUint32(obj, &has_pending_exception);
2613 EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2615 return Local<Uint32>(ToApi<Uint32>(num));
2619 Local<Uint32> Value::ToArrayIndex() const {
2620 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2622 if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
2623 return Local<Uint32>();
2625 i::Isolate* isolate = i::Isolate::Current();
2626 if (IsDeadCheck(isolate, "v8::Value::ToArrayIndex()")) return Local<Uint32>();
2627 LOG_API(isolate, "ToArrayIndex");
2629 EXCEPTION_PREAMBLE(isolate);
2630 i::Handle<i::Object> string_obj =
2631 i::Execution::ToString(obj, &has_pending_exception);
2632 EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2633 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
2635 if (str->AsArrayIndex(&index)) {
2636 i::Handle<i::Object> value;
2637 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
2638 value = i::Handle<i::Object>(i::Smi::FromInt(index));
2640 value = isolate->factory()->NewNumber(index);
2642 return Utils::Uint32ToLocal(value);
2644 return Local<Uint32>();
2648 int32_t Value::Int32Value() const {
2649 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2651 return i::Smi::cast(*obj)->value();
2653 i::Isolate* isolate = i::Isolate::Current();
2654 if (IsDeadCheck(isolate, "v8::Value::Int32Value()")) return 0;
2655 LOG_API(isolate, "Int32Value (slow)");
2657 EXCEPTION_PREAMBLE(isolate);
2658 i::Handle<i::Object> num =
2659 i::Execution::ToInt32(obj, &has_pending_exception);
2660 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2662 return i::Smi::cast(*num)->value();
2664 return static_cast<int32_t>(num->Number());
2670 bool Value::Equals(Handle<Value> that) const {
2671 i::Isolate* isolate = i::Isolate::Current();
2672 if (IsDeadCheck(isolate, "v8::Value::Equals()")
2673 || EmptyCheck("v8::Value::Equals()", this)
2674 || EmptyCheck("v8::Value::Equals()", that)) {
2677 LOG_API(isolate, "Equals");
2679 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2680 i::Handle<i::Object> other = Utils::OpenHandle(*that);
2681 // If both obj and other are JSObjects, we'd better compare by identity
2682 // immediately when going into JS builtin. The reason is Invoke
2683 // would overwrite global object receiver with global proxy.
2684 if (obj->IsJSObject() && other->IsJSObject()) {
2685 return *obj == *other;
2687 i::Handle<i::Object> args[] = { other };
2688 EXCEPTION_PREAMBLE(isolate);
2689 i::Handle<i::Object> result =
2690 CallV8HeapFunction("EQUALS", obj, ARRAY_SIZE(args), args,
2691 &has_pending_exception);
2692 EXCEPTION_BAILOUT_CHECK(isolate, false);
2693 return *result == i::Smi::FromInt(i::EQUAL);
2697 bool Value::StrictEquals(Handle<Value> that) const {
2698 i::Isolate* isolate = i::Isolate::Current();
2699 if (IsDeadCheck(isolate, "v8::Value::StrictEquals()")
2700 || EmptyCheck("v8::Value::StrictEquals()", this)
2701 || EmptyCheck("v8::Value::StrictEquals()", that)) {
2704 LOG_API(isolate, "StrictEquals");
2705 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2706 i::Handle<i::Object> other = Utils::OpenHandle(*that);
2707 // Must check HeapNumber first, since NaN !== NaN.
2708 if (obj->IsHeapNumber()) {
2709 if (!other->IsNumber()) return false;
2710 double x = obj->Number();
2711 double y = other->Number();
2712 // Must check explicitly for NaN:s on Windows, but -0 works fine.
2713 return x == y && !isnan(x) && !isnan(y);
2714 } else if (*obj == *other) { // Also covers Booleans.
2716 } else if (obj->IsSmi()) {
2717 return other->IsNumber() && obj->Number() == other->Number();
2718 } else if (obj->IsString()) {
2719 return other->IsString() &&
2720 i::String::cast(*obj)->Equals(i::String::cast(*other));
2721 } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
2722 return other->IsUndefined() || other->IsUndetectableObject();
2729 uint32_t Value::Uint32Value() const {
2730 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2732 return i::Smi::cast(*obj)->value();
2734 i::Isolate* isolate = i::Isolate::Current();
2735 if (IsDeadCheck(isolate, "v8::Value::Uint32Value()")) return 0;
2736 LOG_API(isolate, "Uint32Value");
2738 EXCEPTION_PREAMBLE(isolate);
2739 i::Handle<i::Object> num =
2740 i::Execution::ToUint32(obj, &has_pending_exception);
2741 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2743 return i::Smi::cast(*num)->value();
2745 return static_cast<uint32_t>(num->Number());
2751 bool v8::Object::Set(v8::Handle<Value> key, v8::Handle<Value> value,
2752 v8::PropertyAttribute attribs) {
2753 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2754 ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2756 i::HandleScope scope(isolate);
2757 i::Handle<i::Object> self = Utils::OpenHandle(this);
2758 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2759 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2760 EXCEPTION_PREAMBLE(isolate);
2761 i::Handle<i::Object> obj = i::SetProperty(
2765 static_cast<PropertyAttributes>(attribs),
2767 has_pending_exception = obj.is_null();
2768 EXCEPTION_BAILOUT_CHECK(isolate, false);
2773 bool v8::Object::Set(uint32_t index, v8::Handle<Value> value) {
2774 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2775 ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2777 i::HandleScope scope(isolate);
2778 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2779 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2780 EXCEPTION_PREAMBLE(isolate);
2781 i::Handle<i::Object> obj = i::SetElement(
2786 has_pending_exception = obj.is_null();
2787 EXCEPTION_BAILOUT_CHECK(isolate, false);
2792 bool v8::Object::ForceSet(v8::Handle<Value> key,
2793 v8::Handle<Value> value,
2794 v8::PropertyAttribute attribs) {
2795 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2796 ON_BAILOUT(isolate, "v8::Object::ForceSet()", return false);
2798 i::HandleScope scope(isolate);
2799 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2800 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2801 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2802 EXCEPTION_PREAMBLE(isolate);
2803 i::Handle<i::Object> obj = i::ForceSetProperty(
2807 static_cast<PropertyAttributes>(attribs));
2808 has_pending_exception = obj.is_null();
2809 EXCEPTION_BAILOUT_CHECK(isolate, false);
2814 bool v8::Object::ForceDelete(v8::Handle<Value> key) {
2815 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2816 ON_BAILOUT(isolate, "v8::Object::ForceDelete()", return false);
2818 i::HandleScope scope(isolate);
2819 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2820 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2822 // When turning on access checks for a global object deoptimize all functions
2823 // as optimized code does not always handle access checks.
2824 i::Deoptimizer::DeoptimizeGlobalObject(*self);
2826 EXCEPTION_PREAMBLE(isolate);
2827 i::Handle<i::Object> obj = i::ForceDeleteProperty(self, key_obj);
2828 has_pending_exception = obj.is_null();
2829 EXCEPTION_BAILOUT_CHECK(isolate, false);
2830 return obj->IsTrue();
2834 Local<Value> v8::Object::Get(v8::Handle<Value> key) {
2835 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2836 ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2838 i::Handle<i::Object> self = Utils::OpenHandle(this);
2839 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2840 EXCEPTION_PREAMBLE(isolate);
2841 i::Handle<i::Object> result = i::GetProperty(self, key_obj);
2842 has_pending_exception = result.is_null();
2843 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2844 return Utils::ToLocal(result);
2848 Local<Value> v8::Object::Get(uint32_t index) {
2849 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2850 ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2852 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2853 EXCEPTION_PREAMBLE(isolate);
2854 i::Handle<i::Object> result = i::Object::GetElement(self, index);
2855 has_pending_exception = result.is_null();
2856 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2857 return Utils::ToLocal(result);
2861 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Handle<Value> key) {
2862 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2863 ON_BAILOUT(isolate, "v8::Object::GetPropertyAttribute()",
2864 return static_cast<PropertyAttribute>(NONE));
2866 i::HandleScope scope(isolate);
2867 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2868 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2869 if (!key_obj->IsString()) {
2870 EXCEPTION_PREAMBLE(isolate);
2871 key_obj = i::Execution::ToString(key_obj, &has_pending_exception);
2872 EXCEPTION_BAILOUT_CHECK(isolate, static_cast<PropertyAttribute>(NONE));
2874 i::Handle<i::String> key_string = i::Handle<i::String>::cast(key_obj);
2875 PropertyAttributes result = self->GetPropertyAttribute(*key_string);
2876 if (result == ABSENT) return static_cast<PropertyAttribute>(NONE);
2877 return static_cast<PropertyAttribute>(result);
2881 Local<Value> v8::Object::GetPrototype() {
2882 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2883 ON_BAILOUT(isolate, "v8::Object::GetPrototype()",
2884 return Local<v8::Value>());
2886 i::Handle<i::Object> self = Utils::OpenHandle(this);
2887 i::Handle<i::Object> result = i::GetPrototype(self);
2888 return Utils::ToLocal(result);
2892 bool v8::Object::SetPrototype(Handle<Value> value) {
2893 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2894 ON_BAILOUT(isolate, "v8::Object::SetPrototype()", return false);
2896 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2897 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2898 // We do not allow exceptions thrown while setting the prototype
2899 // to propagate outside.
2901 EXCEPTION_PREAMBLE(isolate);
2902 i::Handle<i::Object> result = i::SetPrototype(self, value_obj);
2903 has_pending_exception = result.is_null();
2904 EXCEPTION_BAILOUT_CHECK(isolate, false);
2909 Local<Object> v8::Object::FindInstanceInPrototypeChain(
2910 v8::Handle<FunctionTemplate> tmpl) {
2911 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2913 "v8::Object::FindInstanceInPrototypeChain()",
2914 return Local<v8::Object>());
2916 i::JSObject* object = *Utils::OpenHandle(this);
2917 i::FunctionTemplateInfo* tmpl_info = *Utils::OpenHandle(*tmpl);
2918 while (!object->IsInstanceOf(tmpl_info)) {
2919 i::Object* prototype = object->GetPrototype();
2920 if (!prototype->IsJSObject()) return Local<Object>();
2921 object = i::JSObject::cast(prototype);
2923 return Utils::ToLocal(i::Handle<i::JSObject>(object));
2927 Local<Array> v8::Object::GetPropertyNames() {
2928 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2929 ON_BAILOUT(isolate, "v8::Object::GetPropertyNames()",
2930 return Local<v8::Array>());
2932 i::HandleScope scope(isolate);
2933 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2935 i::Handle<i::FixedArray> value =
2936 i::GetKeysInFixedArrayFor(self, i::INCLUDE_PROTOS, &threw);
2937 if (threw) return Local<v8::Array>();
2938 // Because we use caching to speed up enumeration it is important
2939 // to never change the result of the basic enumeration function so
2940 // we clone the result.
2941 i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2942 i::Handle<i::JSArray> result =
2943 isolate->factory()->NewJSArrayWithElements(elms);
2944 return Utils::ToLocal(scope.CloseAndEscape(result));
2948 Local<Array> v8::Object::GetOwnPropertyNames() {
2949 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2950 ON_BAILOUT(isolate, "v8::Object::GetOwnPropertyNames()",
2951 return Local<v8::Array>());
2953 i::HandleScope scope(isolate);
2954 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2956 i::Handle<i::FixedArray> value =
2957 i::GetKeysInFixedArrayFor(self, i::LOCAL_ONLY, &threw);
2958 if (threw) return Local<v8::Array>();
2959 // Because we use caching to speed up enumeration it is important
2960 // to never change the result of the basic enumeration function so
2961 // we clone the result.
2962 i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2963 i::Handle<i::JSArray> result =
2964 isolate->factory()->NewJSArrayWithElements(elms);
2965 return Utils::ToLocal(scope.CloseAndEscape(result));
2969 Local<String> v8::Object::ObjectProtoToString() {
2970 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2971 ON_BAILOUT(isolate, "v8::Object::ObjectProtoToString()",
2972 return Local<v8::String>());
2974 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2976 i::Handle<i::Object> name(self->class_name());
2978 // Native implementation of Object.prototype.toString (v8natives.js):
2979 // var c = %ClassOf(this);
2980 // if (c === 'Arguments') c = 'Object';
2981 // return "[object " + c + "]";
2983 if (!name->IsString()) {
2984 return v8::String::New("[object ]");
2987 i::Handle<i::String> class_name = i::Handle<i::String>::cast(name);
2988 if (class_name->IsEqualTo(i::CStrVector("Arguments"))) {
2989 return v8::String::New("[object Object]");
2992 const char* prefix = "[object ";
2993 Local<String> str = Utils::ToLocal(class_name);
2994 const char* postfix = "]";
2996 int prefix_len = i::StrLength(prefix);
2997 int str_len = str->Length();
2998 int postfix_len = i::StrLength(postfix);
3000 int buf_len = prefix_len + str_len + postfix_len;
3001 i::ScopedVector<char> buf(buf_len);
3004 char* ptr = buf.start();
3005 memcpy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3008 // Write real content.
3009 str->WriteAscii(ptr, 0, str_len);
3013 memcpy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3015 // Copy the buffer into a heap-allocated string and return it.
3016 Local<String> result = v8::String::New(buf.start(), buf_len);
3023 Local<String> v8::Object::GetConstructorName() {
3024 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3025 ON_BAILOUT(isolate, "v8::Object::GetConstructorName()",
3026 return Local<v8::String>());
3028 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3029 i::Handle<i::String> name(self->constructor_name());
3030 return Utils::ToLocal(name);
3034 bool v8::Object::Delete(v8::Handle<String> key) {
3035 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3036 ON_BAILOUT(isolate, "v8::Object::Delete()", return false);
3038 i::HandleScope scope(isolate);
3039 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3040 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3041 return i::DeleteProperty(self, key_obj)->IsTrue();
3045 bool v8::Object::Has(v8::Handle<String> key) {
3046 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3047 ON_BAILOUT(isolate, "v8::Object::Has()", return false);
3049 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3050 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3051 return self->HasProperty(*key_obj);
3055 bool v8::Object::Delete(uint32_t index) {
3056 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3057 ON_BAILOUT(isolate, "v8::Object::DeleteProperty()",
3061 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3062 return i::DeleteElement(self, index)->IsTrue();
3066 bool v8::Object::Has(uint32_t index) {
3067 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3068 ON_BAILOUT(isolate, "v8::Object::HasProperty()", return false);
3069 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3070 return self->HasElement(index);
3074 bool Object::SetAccessor(Handle<String> name,
3075 AccessorGetter getter,
3076 AccessorSetter setter,
3077 v8::Handle<Value> data,
3078 AccessControl settings,
3079 PropertyAttribute attributes) {
3080 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3081 ON_BAILOUT(isolate, "v8::Object::SetAccessor()", return false);
3083 i::HandleScope scope(isolate);
3084 i::Handle<i::AccessorInfo> info = MakeAccessorInfo(name,
3085 getter, setter, data,
3086 settings, attributes);
3087 i::Handle<i::Object> result = i::SetAccessor(Utils::OpenHandle(this), info);
3088 return !result.is_null() && !result->IsUndefined();
3092 bool v8::Object::HasOwnProperty(Handle<String> key) {
3093 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3094 ON_BAILOUT(isolate, "v8::Object::HasOwnProperty()",
3096 return Utils::OpenHandle(this)->HasLocalProperty(
3097 *Utils::OpenHandle(*key));
3101 bool v8::Object::HasRealNamedProperty(Handle<String> key) {
3102 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3103 ON_BAILOUT(isolate, "v8::Object::HasRealNamedProperty()",
3105 return Utils::OpenHandle(this)->HasRealNamedProperty(
3106 *Utils::OpenHandle(*key));
3110 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
3111 ON_BAILOUT(Utils::OpenHandle(this)->GetIsolate(),
3112 "v8::Object::HasRealIndexedProperty()",
3114 return Utils::OpenHandle(this)->HasRealElementProperty(index);
3118 bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
3119 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3121 "v8::Object::HasRealNamedCallbackProperty()",
3124 return Utils::OpenHandle(this)->HasRealNamedCallbackProperty(
3125 *Utils::OpenHandle(*key));
3129 bool v8::Object::HasNamedLookupInterceptor() {
3130 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3131 ON_BAILOUT(isolate, "v8::Object::HasNamedLookupInterceptor()",
3133 return Utils::OpenHandle(this)->HasNamedInterceptor();
3137 bool v8::Object::HasIndexedLookupInterceptor() {
3138 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3139 ON_BAILOUT(isolate, "v8::Object::HasIndexedLookupInterceptor()",
3141 return Utils::OpenHandle(this)->HasIndexedInterceptor();
3145 static Local<Value> GetPropertyByLookup(i::Isolate* isolate,
3146 i::Handle<i::JSObject> receiver,
3147 i::Handle<i::String> name,
3148 i::LookupResult* lookup) {
3149 if (!lookup->IsProperty()) {
3150 // No real property was found.
3151 return Local<Value>();
3154 // If the property being looked up is a callback, it can throw
3156 EXCEPTION_PREAMBLE(isolate);
3157 PropertyAttributes ignored;
3158 i::Handle<i::Object> result =
3159 i::Object::GetProperty(receiver, receiver, lookup, name,
3161 has_pending_exception = result.is_null();
3162 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3164 return Utils::ToLocal(result);
3168 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
3169 Handle<String> key) {
3170 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3172 "v8::Object::GetRealNamedPropertyInPrototypeChain()",
3173 return Local<Value>());
3175 i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3176 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3177 i::LookupResult lookup(isolate);
3178 self_obj->LookupRealNamedPropertyInPrototypes(*key_obj, &lookup);
3179 return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3183 Local<Value> v8::Object::GetRealNamedProperty(Handle<String> key) {
3184 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3185 ON_BAILOUT(isolate, "v8::Object::GetRealNamedProperty()",
3186 return Local<Value>());
3188 i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3189 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3190 i::LookupResult lookup(isolate);
3191 self_obj->LookupRealNamedProperty(*key_obj, &lookup);
3192 return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3196 // Turns on access checks by copying the map and setting the check flag.
3197 // Because the object gets a new map, existing inline cache caching
3198 // the old map of this object will fail.
3199 void v8::Object::TurnOnAccessCheck() {
3200 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3201 ON_BAILOUT(isolate, "v8::Object::TurnOnAccessCheck()", return);
3203 i::HandleScope scope(isolate);
3204 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3206 // When turning on access checks for a global object deoptimize all functions
3207 // as optimized code does not always handle access checks.
3208 i::Deoptimizer::DeoptimizeGlobalObject(*obj);
3210 i::Handle<i::Map> new_map =
3211 isolate->factory()->CopyMapDropTransitions(i::Handle<i::Map>(obj->map()));
3212 new_map->set_is_access_check_needed(true);
3213 obj->set_map(*new_map);
3217 bool v8::Object::IsDirty() {
3218 return Utils::OpenHandle(this)->IsDirty();
3222 Local<v8::Object> v8::Object::Clone() {
3223 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3224 ON_BAILOUT(isolate, "v8::Object::Clone()", return Local<Object>());
3226 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3227 EXCEPTION_PREAMBLE(isolate);
3228 i::Handle<i::JSObject> result = i::Copy(self);
3229 has_pending_exception = result.is_null();
3230 EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3231 return Utils::ToLocal(result);
3235 static i::Context* GetCreationContext(i::JSObject* object) {
3236 i::Object* constructor = object->map()->constructor();
3237 i::JSFunction* function;
3238 if (!constructor->IsJSFunction()) {
3239 // Functions have null as a constructor,
3240 // but any JSFunction knows its context immediately.
3241 ASSERT(object->IsJSFunction());
3242 function = i::JSFunction::cast(object);
3244 function = i::JSFunction::cast(constructor);
3246 return function->context()->global_context();
3250 Local<v8::Context> v8::Object::CreationContext() {
3251 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3253 "v8::Object::CreationContext()", return Local<v8::Context>());
3255 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3256 i::Context* context = GetCreationContext(*self);
3257 return Utils::ToLocal(i::Handle<i::Context>(context));
3261 int v8::Object::GetIdentityHash() {
3262 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3263 ON_BAILOUT(isolate, "v8::Object::GetIdentityHash()", return 0);
3265 i::HandleScope scope(isolate);
3266 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3267 return i::GetIdentityHash(self);
3271 bool v8::Object::SetHiddenValue(v8::Handle<v8::String> key,
3272 v8::Handle<v8::Value> value) {
3273 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3274 ON_BAILOUT(isolate, "v8::Object::SetHiddenValue()", return false);
3276 i::HandleScope scope(isolate);
3277 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3278 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3279 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3280 i::Handle<i::Object> result = i::SetHiddenProperty(self, key_obj, value_obj);
3281 return *result == *self;
3285 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Handle<v8::String> key) {
3286 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3287 ON_BAILOUT(isolate, "v8::Object::GetHiddenValue()",
3288 return Local<v8::Value>());
3290 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3291 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3292 i::Handle<i::Object> result(self->GetHiddenProperty(*key_obj));
3293 if (result->IsUndefined()) return v8::Local<v8::Value>();
3294 return Utils::ToLocal(result);
3298 bool v8::Object::DeleteHiddenValue(v8::Handle<v8::String> key) {
3299 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3300 ON_BAILOUT(isolate, "v8::DeleteHiddenValue()", return false);
3302 i::HandleScope scope(isolate);
3303 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3304 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3305 self->DeleteHiddenProperty(*key_obj);
3312 static i::ElementsKind GetElementsKindFromExternalArrayType(
3313 ExternalArrayType array_type) {
3314 switch (array_type) {
3315 case kExternalByteArray:
3316 return i::EXTERNAL_BYTE_ELEMENTS;
3318 case kExternalUnsignedByteArray:
3319 return i::EXTERNAL_UNSIGNED_BYTE_ELEMENTS;
3321 case kExternalShortArray:
3322 return i::EXTERNAL_SHORT_ELEMENTS;
3324 case kExternalUnsignedShortArray:
3325 return i::EXTERNAL_UNSIGNED_SHORT_ELEMENTS;
3327 case kExternalIntArray:
3328 return i::EXTERNAL_INT_ELEMENTS;
3330 case kExternalUnsignedIntArray:
3331 return i::EXTERNAL_UNSIGNED_INT_ELEMENTS;
3333 case kExternalFloatArray:
3334 return i::EXTERNAL_FLOAT_ELEMENTS;
3336 case kExternalDoubleArray:
3337 return i::EXTERNAL_DOUBLE_ELEMENTS;
3339 case kExternalPixelArray:
3340 return i::EXTERNAL_PIXEL_ELEMENTS;
3344 return i::DICTIONARY_ELEMENTS;
3348 void PrepareExternalArrayElements(i::Handle<i::JSObject> object,
3350 ExternalArrayType array_type,
3352 i::Isolate* isolate = object->GetIsolate();
3353 i::Handle<i::ExternalArray> array =
3354 isolate->factory()->NewExternalArray(length, array_type, data);
3356 i::Handle<i::Map> external_array_map =
3357 isolate->factory()->GetElementsTransitionMap(
3359 GetElementsKindFromExternalArrayType(array_type));
3361 object->set_map(*external_array_map);
3362 object->set_elements(*array);
3368 void v8::Object::SetIndexedPropertiesToPixelData(uint8_t* data, int length) {
3369 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3370 ON_BAILOUT(isolate, "v8::SetElementsToPixelData()", return);
3372 i::HandleScope scope(isolate);
3373 if (!ApiCheck(length <= i::ExternalPixelArray::kMaxLength,
3374 "v8::Object::SetIndexedPropertiesToPixelData()",
3375 "length exceeds max acceptable value")) {
3378 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3379 if (!ApiCheck(!self->IsJSArray(),
3380 "v8::Object::SetIndexedPropertiesToPixelData()",
3381 "JSArray is not supported")) {
3384 PrepareExternalArrayElements(self, data, kExternalPixelArray, length);
3388 bool v8::Object::HasIndexedPropertiesInPixelData() {
3389 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3390 ON_BAILOUT(self->GetIsolate(), "v8::HasIndexedPropertiesInPixelData()",
3392 return self->HasExternalPixelElements();
3396 uint8_t* v8::Object::GetIndexedPropertiesPixelData() {
3397 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3398 ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelData()",
3400 if (self->HasExternalPixelElements()) {
3401 return i::ExternalPixelArray::cast(self->elements())->
3402 external_pixel_pointer();
3409 int v8::Object::GetIndexedPropertiesPixelDataLength() {
3410 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3411 ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelDataLength()",
3413 if (self->HasExternalPixelElements()) {
3414 return i::ExternalPixelArray::cast(self->elements())->length();
3421 void v8::Object::SetIndexedPropertiesToExternalArrayData(
3423 ExternalArrayType array_type,
3425 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3426 ON_BAILOUT(isolate, "v8::SetIndexedPropertiesToExternalArrayData()", return);
3428 i::HandleScope scope(isolate);
3429 if (!ApiCheck(length <= i::ExternalArray::kMaxLength,
3430 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3431 "length exceeds max acceptable value")) {
3434 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3435 if (!ApiCheck(!self->IsJSArray(),
3436 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3437 "JSArray is not supported")) {
3440 PrepareExternalArrayElements(self, data, array_type, length);
3444 bool v8::Object::HasIndexedPropertiesInExternalArrayData() {
3445 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3446 ON_BAILOUT(self->GetIsolate(),
3447 "v8::HasIndexedPropertiesInExternalArrayData()",
3449 return self->HasExternalArrayElements();
3453 void* v8::Object::GetIndexedPropertiesExternalArrayData() {
3454 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3455 ON_BAILOUT(self->GetIsolate(),
3456 "v8::GetIndexedPropertiesExternalArrayData()",
3458 if (self->HasExternalArrayElements()) {
3459 return i::ExternalArray::cast(self->elements())->external_pointer();
3466 ExternalArrayType v8::Object::GetIndexedPropertiesExternalArrayDataType() {
3467 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3468 ON_BAILOUT(self->GetIsolate(),
3469 "v8::GetIndexedPropertiesExternalArrayDataType()",
3470 return static_cast<ExternalArrayType>(-1));
3471 switch (self->elements()->map()->instance_type()) {
3472 case i::EXTERNAL_BYTE_ARRAY_TYPE:
3473 return kExternalByteArray;
3474 case i::EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
3475 return kExternalUnsignedByteArray;
3476 case i::EXTERNAL_SHORT_ARRAY_TYPE:
3477 return kExternalShortArray;
3478 case i::EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
3479 return kExternalUnsignedShortArray;
3480 case i::EXTERNAL_INT_ARRAY_TYPE:
3481 return kExternalIntArray;
3482 case i::EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
3483 return kExternalUnsignedIntArray;
3484 case i::EXTERNAL_FLOAT_ARRAY_TYPE:
3485 return kExternalFloatArray;
3486 case i::EXTERNAL_DOUBLE_ARRAY_TYPE:
3487 return kExternalDoubleArray;
3488 case i::EXTERNAL_PIXEL_ARRAY_TYPE:
3489 return kExternalPixelArray;
3491 return static_cast<ExternalArrayType>(-1);
3496 int v8::Object::GetIndexedPropertiesExternalArrayDataLength() {
3497 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3498 ON_BAILOUT(self->GetIsolate(),
3499 "v8::GetIndexedPropertiesExternalArrayDataLength()",
3501 if (self->HasExternalArrayElements()) {
3502 return i::ExternalArray::cast(self->elements())->length();
3509 bool v8::Object::IsCallable() {
3510 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3511 ON_BAILOUT(isolate, "v8::Object::IsCallable()", return false);
3513 i::HandleScope scope(isolate);
3514 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3515 if (obj->IsJSFunction()) return true;
3516 return i::Execution::GetFunctionDelegate(obj)->IsJSFunction();
3520 Local<v8::Value> Object::CallAsFunction(v8::Handle<v8::Object> recv,
3522 v8::Handle<v8::Value> argv[]) {
3523 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3524 ON_BAILOUT(isolate, "v8::Object::CallAsFunction()",
3525 return Local<v8::Value>());
3526 LOG_API(isolate, "Object::CallAsFunction");
3528 i::HandleScope scope(isolate);
3529 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3530 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3531 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3532 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3533 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>();
3534 if (obj->IsJSFunction()) {
3535 fun = i::Handle<i::JSFunction>::cast(obj);
3537 EXCEPTION_PREAMBLE(isolate);
3538 i::Handle<i::Object> delegate =
3539 i::Execution::TryGetFunctionDelegate(obj, &has_pending_exception);
3540 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3541 fun = i::Handle<i::JSFunction>::cast(delegate);
3544 EXCEPTION_PREAMBLE(isolate);
3545 i::Handle<i::Object> returned =
3546 i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3547 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3548 return Utils::ToLocal(scope.CloseAndEscape(returned));
3552 Local<v8::Value> Object::CallAsConstructor(int argc,
3553 v8::Handle<v8::Value> argv[]) {
3554 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3555 ON_BAILOUT(isolate, "v8::Object::CallAsConstructor()",
3556 return Local<v8::Object>());
3557 LOG_API(isolate, "Object::CallAsConstructor");
3559 i::HandleScope scope(isolate);
3560 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3561 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3562 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3563 if (obj->IsJSFunction()) {
3564 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(obj);
3565 EXCEPTION_PREAMBLE(isolate);
3566 i::Handle<i::Object> returned =
3567 i::Execution::New(fun, argc, args, &has_pending_exception);
3568 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3569 return Utils::ToLocal(scope.CloseAndEscape(
3570 i::Handle<i::JSObject>::cast(returned)));
3572 EXCEPTION_PREAMBLE(isolate);
3573 i::Handle<i::Object> delegate =
3574 i::Execution::TryGetConstructorDelegate(obj, &has_pending_exception);
3575 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3576 if (!delegate->IsUndefined()) {
3577 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(delegate);
3578 EXCEPTION_PREAMBLE(isolate);
3579 i::Handle<i::Object> returned =
3580 i::Execution::Call(fun, obj, argc, args, &has_pending_exception);
3581 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3582 ASSERT(!delegate->IsUndefined());
3583 return Utils::ToLocal(scope.CloseAndEscape(returned));
3585 return Local<v8::Object>();
3589 Local<v8::Object> Function::NewInstance() const {
3590 return NewInstance(0, NULL);
3594 Local<v8::Object> Function::NewInstance(int argc,
3595 v8::Handle<v8::Value> argv[]) const {
3596 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3597 ON_BAILOUT(isolate, "v8::Function::NewInstance()",
3598 return Local<v8::Object>());
3599 LOG_API(isolate, "Function::NewInstance");
3602 i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
3603 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3604 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3605 EXCEPTION_PREAMBLE(isolate);
3606 i::Handle<i::Object> returned =
3607 i::Execution::New(function, argc, args, &has_pending_exception);
3608 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3609 return scope.Close(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
3613 Local<v8::Value> Function::Call(v8::Handle<v8::Object> recv, int argc,
3614 v8::Handle<v8::Value> argv[]) {
3615 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3616 ON_BAILOUT(isolate, "v8::Function::Call()", return Local<v8::Value>());
3617 LOG_API(isolate, "Function::Call");
3619 i::Object* raw_result = NULL;
3621 i::HandleScope scope(isolate);
3622 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
3623 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3624 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3625 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3626 EXCEPTION_PREAMBLE(isolate);
3627 i::Handle<i::Object> returned =
3628 i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3629 EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3630 raw_result = *returned;
3632 i::Handle<i::Object> result(raw_result);
3633 return Utils::ToLocal(result);
3637 void Function::SetName(v8::Handle<v8::String> name) {
3638 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3641 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3642 func->shared()->set_name(*Utils::OpenHandle(*name));
3646 Handle<Value> Function::GetName() const {
3647 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3648 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->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 String::Length() const {
3680 i::Handle<i::String> str = Utils::OpenHandle(this);
3681 if (IsDeadCheck(str->GetIsolate(), "v8::String::Length()")) return 0;
3682 return str->length();
3686 int String::Utf8Length() const {
3687 i::Handle<i::String> str = Utils::OpenHandle(this);
3688 if (IsDeadCheck(str->GetIsolate(), "v8::String::Utf8Length()")) return 0;
3689 return str->Utf8Length();
3693 uint32_t String::Hash() const {
3694 i::Handle<i::String> str = Utils::OpenHandle(this);
3695 if (IsDeadCheck(str->GetIsolate(), "v8::String::Hash()")) return 0;
3700 String::CompleteHashData String::CompleteHash() const {
3701 i::Handle<i::String> str = Utils::OpenHandle(this);
3702 if (IsDeadCheck(str->GetIsolate(), "v8::String::CompleteHash()")) return CompleteHashData();
3703 CompleteHashData result;
3704 result.length = str->length();
3705 result.hash = str->Hash();
3706 if (str->IsSeqString())
3707 result.symbol_id = i::SeqString::cast(*str)->symbol_id();
3712 uint32_t String::ComputeHash(uint16_t *string, int length) {
3713 return i::HashSequentialString<i::uc16>(string, length) >> i::String::kHashShift;
3717 uint32_t String::ComputeHash(char *string, int length) {
3718 return i::HashSequentialString<char>(string, length) >> i::String::kHashShift;
3722 uint16_t String::GetCharacter(int index)
3724 i::Handle<i::String> str = Utils::OpenHandle(this);
3725 return str->Get(index);
3729 bool String::Equals(uint16_t *string, int length) {
3730 i::Handle<i::String> str = Utils::OpenHandle(this);
3731 if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3732 return str->SlowEqualsExternal(string, length);
3736 bool String::Equals(char *string, int length)
3738 i::Handle<i::String> str = Utils::OpenHandle(this);
3739 if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3740 return str->SlowEqualsExternal(string, length);
3744 int String::WriteUtf8(char* buffer,
3747 int options) const {
3748 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3749 if (IsDeadCheck(isolate, "v8::String::WriteUtf8()")) return 0;
3750 LOG_API(isolate, "String::WriteUtf8");
3752 i::Handle<i::String> str = Utils::OpenHandle(this);
3753 if (str->IsAsciiRepresentation()) {
3755 if (capacity == -1) {
3756 capacity = str->length() + 1;
3757 len = str->length();
3759 len = i::Min(capacity, str->length());
3761 i::String::WriteToFlat(*str, buffer, 0, len);
3762 if (nchars_ref != NULL) *nchars_ref = len;
3763 if (!(options & NO_NULL_TERMINATION) && capacity > len) {
3770 i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3771 isolate->string_tracker()->RecordWrite(str);
3772 if (options & HINT_MANY_WRITES_EXPECTED) {
3773 // Flatten the string for efficiency. This applies whether we are
3774 // using StringInputBuffer or Get(i) to access the characters.
3777 write_input_buffer.Reset(0, *str);
3778 int len = str->length();
3779 // Encode the first K - 3 bytes directly into the buffer since we
3780 // know there's room for them. If no capacity is given we copy all
3782 int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
3786 for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
3787 i::uc32 c = write_input_buffer.GetNext();
3788 int written = unibrow::Utf8::Encode(buffer + pos, c);
3793 // For the last characters we need to check the length for each one
3794 // because they may be longer than the remaining space in the
3796 char intermediate[unibrow::Utf8::kMaxEncodedSize];
3797 for (; i < len && pos < capacity; i++) {
3798 i::uc32 c = write_input_buffer.GetNext();
3799 int written = unibrow::Utf8::Encode(intermediate, c);
3800 if (pos + written <= capacity) {
3801 for (int j = 0; j < written; j++)
3802 buffer[pos + j] = intermediate[j];
3806 // We've reached the end of the buffer
3811 if (nchars_ref != NULL) *nchars_ref = nchars;
3812 if (!(options & NO_NULL_TERMINATION) &&
3813 (i == len && (capacity == -1 || pos < capacity)))
3814 buffer[pos++] = '\0';
3819 int String::WriteAscii(char* buffer,
3822 int options) const {
3823 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3824 if (IsDeadCheck(isolate, "v8::String::WriteAscii()")) return 0;
3825 LOG_API(isolate, "String::WriteAscii");
3827 i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3828 ASSERT(start >= 0 && length >= -1);
3829 i::Handle<i::String> str = Utils::OpenHandle(this);
3830 isolate->string_tracker()->RecordWrite(str);
3831 if (options & HINT_MANY_WRITES_EXPECTED) {
3832 // Flatten the string for efficiency. This applies whether we are
3833 // using StringInputBuffer or Get(i) to access the characters.
3837 if ( (length == -1) || (length > str->length() - start) )
3838 end = str->length() - start;
3839 if (end < 0) return 0;
3840 write_input_buffer.Reset(start, *str);
3842 for (i = 0; i < end; i++) {
3843 char c = static_cast<char>(write_input_buffer.GetNext());
3844 if (c == '\0') c = ' ';
3847 if (!(options & NO_NULL_TERMINATION) && (length == -1 || i < length))
3853 int String::Write(uint16_t* buffer,
3856 int options) const {
3857 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3858 if (IsDeadCheck(isolate, "v8::String::Write()")) return 0;
3859 LOG_API(isolate, "String::Write");
3861 ASSERT(start >= 0 && length >= -1);
3862 i::Handle<i::String> str = Utils::OpenHandle(this);
3863 isolate->string_tracker()->RecordWrite(str);
3864 if (options & HINT_MANY_WRITES_EXPECTED) {
3865 // Flatten the string for efficiency. This applies whether we are
3866 // using StringInputBuffer or Get(i) to access the characters.
3869 int end = start + length;
3870 if ((length == -1) || (length > str->length() - start) )
3871 end = str->length();
3872 if (end < 0) return 0;
3873 i::String::WriteToFlat(*str, buffer, start, end);
3874 if (!(options & NO_NULL_TERMINATION) &&
3875 (length == -1 || end - start < length)) {
3876 buffer[end - start] = '\0';
3882 bool v8::String::IsExternal() const {
3883 i::Handle<i::String> str = Utils::OpenHandle(this);
3884 if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternal()")) {
3887 EnsureInitializedForIsolate(str->GetIsolate(), "v8::String::IsExternal()");
3888 return i::StringShape(*str).IsExternalTwoByte();
3892 bool v8::String::IsExternalAscii() const {
3893 i::Handle<i::String> str = Utils::OpenHandle(this);
3894 if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternalAscii()")) {
3897 return i::StringShape(*str).IsExternalAscii();
3901 void v8::String::VerifyExternalStringResource(
3902 v8::String::ExternalStringResource* value) const {
3903 i::Handle<i::String> str = Utils::OpenHandle(this);
3904 const v8::String::ExternalStringResource* expected;
3905 if (i::StringShape(*str).IsExternalTwoByte()) {
3906 const void* resource =
3907 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
3908 expected = reinterpret_cast<const ExternalStringResource*>(resource);
3912 CHECK_EQ(expected, value);
3916 const v8::String::ExternalAsciiStringResource*
3917 v8::String::GetExternalAsciiStringResource() const {
3918 i::Handle<i::String> str = Utils::OpenHandle(this);
3919 if (IsDeadCheck(str->GetIsolate(),
3920 "v8::String::GetExternalAsciiStringResource()")) {
3923 if (i::StringShape(*str).IsExternalAscii()) {
3924 const void* resource =
3925 i::Handle<i::ExternalAsciiString>::cast(str)->resource();
3926 return reinterpret_cast<const ExternalAsciiStringResource*>(resource);
3933 double Number::Value() const {
3934 if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Value()")) return 0;
3935 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3936 return obj->Number();
3940 bool Boolean::Value() const {
3941 if (IsDeadCheck(i::Isolate::Current(), "v8::Boolean::Value()")) return false;
3942 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3943 return obj->IsTrue();
3947 int64_t Integer::Value() const {
3948 if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Value()")) return 0;
3949 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3951 return i::Smi::cast(*obj)->value();
3953 return static_cast<int64_t>(obj->Number());
3958 int32_t Int32::Value() const {
3959 if (IsDeadCheck(i::Isolate::Current(), "v8::Int32::Value()")) return 0;
3960 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3962 return i::Smi::cast(*obj)->value();
3964 return static_cast<int32_t>(obj->Number());
3969 uint32_t Uint32::Value() const {
3970 if (IsDeadCheck(i::Isolate::Current(), "v8::Uint32::Value()")) return 0;
3971 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3973 return i::Smi::cast(*obj)->value();
3975 return static_cast<uint32_t>(obj->Number());
3980 int v8::Object::InternalFieldCount() {
3981 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3982 if (IsDeadCheck(obj->GetIsolate(), "v8::Object::InternalFieldCount()")) {
3985 return obj->GetInternalFieldCount();
3989 Local<Value> v8::Object::CheckedGetInternalField(int index) {
3990 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3991 if (IsDeadCheck(obj->GetIsolate(), "v8::Object::GetInternalField()")) {
3992 return Local<Value>();
3994 if (!ApiCheck(index < obj->GetInternalFieldCount(),
3995 "v8::Object::GetInternalField()",
3996 "Reading internal field out of bounds")) {
3997 return Local<Value>();
3999 i::Handle<i::Object> value(obj->GetInternalField(index));
4000 Local<Value> result = Utils::ToLocal(value);
4002 Local<Value> unchecked = UncheckedGetInternalField(index);
4003 ASSERT(unchecked.IsEmpty() || (unchecked == result));
4009 void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
4010 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4011 i::Isolate* isolate = obj->GetIsolate();
4012 if (IsDeadCheck(isolate, "v8::Object::SetInternalField()")) {
4015 if (!ApiCheck(index < obj->GetInternalFieldCount(),
4016 "v8::Object::SetInternalField()",
4017 "Writing internal field out of bounds")) {
4021 i::Handle<i::Object> val = Utils::OpenHandle(*value);
4022 obj->SetInternalField(index, *val);
4026 static bool CanBeEncodedAsSmi(void* ptr) {
4027 const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4028 return ((address & i::kEncodablePointerMask) == 0);
4032 static i::Smi* EncodeAsSmi(void* ptr) {
4033 ASSERT(CanBeEncodedAsSmi(ptr));
4034 const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4035 i::Smi* result = reinterpret_cast<i::Smi*>(address << i::kPointerToSmiShift);
4036 ASSERT(i::Internals::HasSmiTag(result));
4037 ASSERT_EQ(result, i::Smi::FromInt(result->value()));
4038 ASSERT_EQ(ptr, i::Internals::GetExternalPointerFromSmi(result));
4043 void v8::Object::SetPointerInInternalField(int index, void* value) {
4044 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4046 if (CanBeEncodedAsSmi(value)) {
4047 Utils::OpenHandle(this)->SetInternalField(index, EncodeAsSmi(value));
4050 i::Handle<i::Foreign> foreign =
4051 isolate->factory()->NewForeign(
4052 reinterpret_cast<i::Address>(value), i::TENURED);
4053 if (!foreign.is_null())
4054 Utils::OpenHandle(this)->SetInternalField(index, *foreign);
4056 ASSERT_EQ(value, GetPointerFromInternalField(index));
4060 void v8::Object::SetExternalResource(v8::Object::ExternalResource *resource) {
4061 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4063 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4064 if (CanBeEncodedAsSmi(resource)) {
4065 obj->SetExternalResourceObject(EncodeAsSmi(resource));
4067 obj->SetExternalResourceObject(*isolate->factory()->NewForeign(static_cast<i::Address>((void *)resource)));
4069 if (!obj->IsSymbol()) {
4070 isolate->heap()->external_string_table()->AddObject(*obj);
4075 v8::Object::ExternalResource *v8::Object::GetExternalResource() {
4076 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4077 i::Object* value = obj->GetExternalResourceObject();
4078 if (value->IsSmi()) {
4079 return reinterpret_cast<v8::Object::ExternalResource*>(i::Internals::GetExternalPointerFromSmi(value));
4080 } else if (value->IsForeign()) {
4081 return reinterpret_cast<v8::Object::ExternalResource*>(i::Foreign::cast(value)->address());
4088 // --- E n v i r o n m e n t ---
4091 bool v8::V8::Initialize() {
4092 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4093 if (isolate != NULL && isolate->IsInitialized()) {
4096 return InitializeHelper();
4100 void v8::V8::SetEntropySource(EntropySource source) {
4101 i::V8::SetEntropySource(source);
4105 bool v8::V8::Dispose() {
4106 i::Isolate* isolate = i::Isolate::Current();
4107 if (!ApiCheck(isolate != NULL && isolate->IsDefaultIsolate(),
4108 "v8::V8::Dispose()",
4109 "Use v8::Isolate::Dispose() for a non-default isolate.")) {
4117 HeapStatistics::HeapStatistics(): total_heap_size_(0),
4118 total_heap_size_executable_(0),
4120 heap_size_limit_(0) { }
4123 void v8::V8::GetHeapStatistics(HeapStatistics* heap_statistics) {
4124 if (!i::Isolate::Current()->IsInitialized()) {
4125 // Isolate is unitialized thus heap is not configured yet.
4126 heap_statistics->set_total_heap_size(0);
4127 heap_statistics->set_total_heap_size_executable(0);
4128 heap_statistics->set_used_heap_size(0);
4129 heap_statistics->set_heap_size_limit(0);
4133 i::Heap* heap = i::Isolate::Current()->heap();
4134 heap_statistics->set_total_heap_size(heap->CommittedMemory());
4135 heap_statistics->set_total_heap_size_executable(
4136 heap->CommittedMemoryExecutable());
4137 heap_statistics->set_used_heap_size(heap->SizeOfObjects());
4138 heap_statistics->set_heap_size_limit(heap->MaxReserved());
4142 bool v8::V8::IdleNotification() {
4143 // Returning true tells the caller that it need not
4144 // continue to call IdleNotification.
4145 i::Isolate* isolate = i::Isolate::Current();
4146 if (isolate == NULL || !isolate->IsInitialized()) return true;
4147 return i::V8::IdleNotification();
4151 void v8::V8::LowMemoryNotification() {
4152 i::Isolate* isolate = i::Isolate::Current();
4153 if (isolate == NULL || !isolate->IsInitialized()) return;
4154 isolate->heap()->CollectAllAvailableGarbage();
4158 int v8::V8::ContextDisposedNotification() {
4159 i::Isolate* isolate = i::Isolate::Current();
4160 if (!isolate->IsInitialized()) return 0;
4161 return isolate->heap()->NotifyContextDisposed();
4165 const char* v8::V8::GetVersion() {
4166 return i::Version::GetVersion();
4170 static i::Handle<i::FunctionTemplateInfo>
4171 EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
4172 if (templ->constructor()->IsUndefined()) {
4173 Local<FunctionTemplate> constructor = FunctionTemplate::New();
4174 Utils::OpenHandle(*constructor)->set_instance_template(*templ);
4175 templ->set_constructor(*Utils::OpenHandle(*constructor));
4177 return i::Handle<i::FunctionTemplateInfo>(
4178 i::FunctionTemplateInfo::cast(templ->constructor()));
4182 Persistent<Context> v8::Context::New(
4183 v8::ExtensionConfiguration* extensions,
4184 v8::Handle<ObjectTemplate> global_template,
4185 v8::Handle<Value> global_object) {
4186 i::Isolate* isolate = i::Isolate::Current();
4187 EnsureInitializedForIsolate(isolate, "v8::Context::New()");
4188 LOG_API(isolate, "Context::New");
4189 ON_BAILOUT(isolate, "v8::Context::New()", return Persistent<Context>());
4191 // Enter V8 via an ENTER_V8 scope.
4192 i::Handle<i::Context> env;
4195 v8::Handle<ObjectTemplate> proxy_template = global_template;
4196 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
4197 i::Handle<i::FunctionTemplateInfo> global_constructor;
4199 if (!global_template.IsEmpty()) {
4200 // Make sure that the global_template has a constructor.
4201 global_constructor =
4202 EnsureConstructor(Utils::OpenHandle(*global_template));
4204 // Create a fresh template for the global proxy object.
4205 proxy_template = ObjectTemplate::New();
4207 EnsureConstructor(Utils::OpenHandle(*proxy_template));
4209 // Set the global template to be the prototype template of
4210 // global proxy template.
4211 proxy_constructor->set_prototype_template(
4212 *Utils::OpenHandle(*global_template));
4214 // Migrate security handlers from global_template to
4215 // proxy_template. Temporarily removing access check
4216 // information from the global template.
4217 if (!global_constructor->access_check_info()->IsUndefined()) {
4218 proxy_constructor->set_access_check_info(
4219 global_constructor->access_check_info());
4220 proxy_constructor->set_needs_access_check(
4221 global_constructor->needs_access_check());
4222 global_constructor->set_needs_access_check(false);
4223 global_constructor->set_access_check_info(
4224 isolate->heap()->undefined_value());
4228 // Create the environment.
4229 env = isolate->bootstrapper()->CreateEnvironment(
4231 Utils::OpenHandle(*global_object),
4235 // Restore the access check info on the global template.
4236 if (!global_template.IsEmpty()) {
4237 ASSERT(!global_constructor.is_null());
4238 ASSERT(!proxy_constructor.is_null());
4239 global_constructor->set_access_check_info(
4240 proxy_constructor->access_check_info());
4241 global_constructor->set_needs_access_check(
4242 proxy_constructor->needs_access_check());
4244 isolate->runtime_profiler()->Reset();
4248 if (env.is_null()) {
4249 return Persistent<Context>();
4251 return Persistent<Context>(Utils::ToLocal(env));
4255 void v8::Context::SetSecurityToken(Handle<Value> token) {
4256 i::Isolate* isolate = i::Isolate::Current();
4257 if (IsDeadCheck(isolate, "v8::Context::SetSecurityToken()")) {
4261 i::Handle<i::Context> env = Utils::OpenHandle(this);
4262 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
4263 env->set_security_token(*token_handle);
4267 void v8::Context::UseDefaultSecurityToken() {
4268 i::Isolate* isolate = i::Isolate::Current();
4269 if (IsDeadCheck(isolate,
4270 "v8::Context::UseDefaultSecurityToken()")) {
4274 i::Handle<i::Context> env = Utils::OpenHandle(this);
4275 env->set_security_token(env->global());
4279 Handle<Value> v8::Context::GetSecurityToken() {
4280 i::Isolate* isolate = i::Isolate::Current();
4281 if (IsDeadCheck(isolate, "v8::Context::GetSecurityToken()")) {
4282 return Handle<Value>();
4284 i::Handle<i::Context> env = Utils::OpenHandle(this);
4285 i::Object* security_token = env->security_token();
4286 i::Handle<i::Object> token_handle(security_token);
4287 return Utils::ToLocal(token_handle);
4291 bool Context::HasOutOfMemoryException() {
4292 i::Handle<i::Context> env = Utils::OpenHandle(this);
4293 return env->has_out_of_memory();
4297 bool Context::InContext() {
4298 return i::Isolate::Current()->context() != NULL;
4302 v8::Local<v8::Context> Context::GetEntered() {
4303 i::Isolate* isolate = i::Isolate::Current();
4304 if (!EnsureInitializedForIsolate(isolate, "v8::Context::GetEntered()")) {
4305 return Local<Context>();
4307 i::Handle<i::Object> last =
4308 isolate->handle_scope_implementer()->LastEnteredContext();
4309 if (last.is_null()) return Local<Context>();
4310 i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
4311 return Utils::ToLocal(context);
4315 v8::Local<v8::Context> Context::GetCurrent() {
4316 i::Isolate* isolate = i::Isolate::Current();
4317 if (IsDeadCheck(isolate, "v8::Context::GetCurrent()")) {
4318 return Local<Context>();
4320 i::Handle<i::Object> current = isolate->global_context();
4321 if (current.is_null()) return Local<Context>();
4322 i::Handle<i::Context> context = i::Handle<i::Context>::cast(current);
4323 return Utils::ToLocal(context);
4327 v8::Local<v8::Context> Context::GetCalling() {
4328 i::Isolate* isolate = i::Isolate::Current();
4329 if (IsDeadCheck(isolate, "v8::Context::GetCalling()")) {
4330 return Local<Context>();
4332 i::Handle<i::Object> calling =
4333 isolate->GetCallingGlobalContext();
4334 if (calling.is_null()) return Local<Context>();
4335 i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
4336 return Utils::ToLocal(context);
4340 v8::Local<v8::Object> Context::Global() {
4341 if (IsDeadCheck(i::Isolate::Current(), "v8::Context::Global()")) {
4342 return Local<v8::Object>();
4344 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4345 i::Handle<i::Context> context =
4346 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4347 i::Handle<i::Object> global(context->global_proxy());
4348 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
4352 void Context::DetachGlobal() {
4353 i::Isolate* isolate = i::Isolate::Current();
4354 if (IsDeadCheck(isolate, "v8::Context::DetachGlobal()")) return;
4356 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4357 i::Handle<i::Context> context =
4358 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4359 isolate->bootstrapper()->DetachGlobal(context);
4363 void Context::ReattachGlobal(Handle<Object> global_object) {
4364 i::Isolate* isolate = i::Isolate::Current();
4365 if (IsDeadCheck(isolate, "v8::Context::ReattachGlobal()")) return;
4367 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4368 i::Handle<i::Context> context =
4369 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4370 isolate->bootstrapper()->ReattachGlobal(
4372 Utils::OpenHandle(*global_object));
4376 void Context::AllowCodeGenerationFromStrings(bool allow) {
4377 i::Isolate* isolate = i::Isolate::Current();
4378 if (IsDeadCheck(isolate, "v8::Context::AllowCodeGenerationFromStrings()")) {
4382 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4383 i::Handle<i::Context> context =
4384 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4385 context->set_allow_code_gen_from_strings(
4386 allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
4390 void V8::SetWrapperClassId(i::Object** global_handle, uint16_t class_id) {
4391 i::GlobalHandles::SetWrapperClassId(global_handle, class_id);
4395 Local<v8::Object> ObjectTemplate::NewInstance() {
4396 i::Isolate* isolate = i::Isolate::Current();
4397 ON_BAILOUT(isolate, "v8::ObjectTemplate::NewInstance()",
4398 return Local<v8::Object>());
4399 LOG_API(isolate, "ObjectTemplate::NewInstance");
4401 EXCEPTION_PREAMBLE(isolate);
4402 i::Handle<i::Object> obj =
4403 i::Execution::InstantiateObject(Utils::OpenHandle(this),
4404 &has_pending_exception);
4405 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
4406 return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
4410 Local<v8::Function> FunctionTemplate::GetFunction() {
4411 i::Isolate* isolate = i::Isolate::Current();
4412 ON_BAILOUT(isolate, "v8::FunctionTemplate::GetFunction()",
4413 return Local<v8::Function>());
4414 LOG_API(isolate, "FunctionTemplate::GetFunction");
4416 EXCEPTION_PREAMBLE(isolate);
4417 i::Handle<i::Object> obj =
4418 i::Execution::InstantiateFunction(Utils::OpenHandle(this),
4419 &has_pending_exception);
4420 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Function>());
4421 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
4425 bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
4426 ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
4428 i::Object* obj = *Utils::OpenHandle(*value);
4429 return obj->IsInstanceOf(*Utils::OpenHandle(this));
4433 static Local<External> ExternalNewImpl(void* data) {
4434 return Utils::ToLocal(FACTORY->NewForeign(static_cast<i::Address>(data)));
4437 static void* ExternalValueImpl(i::Handle<i::Object> obj) {
4438 return reinterpret_cast<void*>(i::Foreign::cast(*obj)->address());
4442 Local<Value> v8::External::Wrap(void* data) {
4443 i::Isolate* isolate = i::Isolate::Current();
4444 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4445 EnsureInitializedForIsolate(isolate, "v8::External::Wrap()");
4446 LOG_API(isolate, "External::Wrap");
4449 v8::Local<v8::Value> result = CanBeEncodedAsSmi(data)
4450 ? Utils::ToLocal(i::Handle<i::Object>(EncodeAsSmi(data)))
4451 : v8::Local<v8::Value>(ExternalNewImpl(data));
4453 ASSERT_EQ(data, Unwrap(result));
4458 void* v8::Object::SlowGetPointerFromInternalField(int index) {
4459 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4460 i::Object* value = obj->GetInternalField(index);
4461 if (value->IsSmi()) {
4462 return i::Internals::GetExternalPointerFromSmi(value);
4463 } else if (value->IsForeign()) {
4464 return reinterpret_cast<void*>(i::Foreign::cast(value)->address());
4471 void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
4472 if (IsDeadCheck(i::Isolate::Current(), "v8::External::Unwrap()")) return 0;
4473 i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
4476 result = i::Internals::GetExternalPointerFromSmi(*obj);
4477 } else if (obj->IsForeign()) {
4478 result = ExternalValueImpl(obj);
4482 ASSERT_EQ(result, QuickUnwrap(wrapper));
4487 Local<External> v8::External::New(void* data) {
4488 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4489 i::Isolate* isolate = i::Isolate::Current();
4490 EnsureInitializedForIsolate(isolate, "v8::External::New()");
4491 LOG_API(isolate, "External::New");
4493 return ExternalNewImpl(data);
4497 void* External::Value() const {
4498 if (IsDeadCheck(i::Isolate::Current(), "v8::External::Value()")) return 0;
4499 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4500 return ExternalValueImpl(obj);
4504 Local<String> v8::String::Empty() {
4505 i::Isolate* isolate = i::Isolate::Current();
4506 EnsureInitializedForIsolate(isolate, "v8::String::Empty()");
4507 LOG_API(isolate, "String::Empty()");
4508 return Utils::ToLocal(isolate->factory()->empty_symbol());
4512 Local<String> v8::String::New(const char* data, int length) {
4513 i::Isolate* isolate = i::Isolate::Current();
4514 EnsureInitializedForIsolate(isolate, "v8::String::New()");
4515 LOG_API(isolate, "String::New(char)");
4516 if (length == 0) return Empty();
4518 if (length == -1) length = i::StrLength(data);
4519 i::Handle<i::String> result =
4520 isolate->factory()->NewStringFromUtf8(
4521 i::Vector<const char>(data, length));
4522 return Utils::ToLocal(result);
4526 Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
4527 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
4528 i::Isolate* isolate = left_string->GetIsolate();
4529 EnsureInitializedForIsolate(isolate, "v8::String::New()");
4530 LOG_API(isolate, "String::New(char)");
4532 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
4533 i::Handle<i::String> result = isolate->factory()->NewConsString(left_string,
4535 return Utils::ToLocal(result);
4539 Local<String> v8::String::NewUndetectable(const char* data, int length) {
4540 i::Isolate* isolate = i::Isolate::Current();
4541 EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4542 LOG_API(isolate, "String::NewUndetectable(char)");
4544 if (length == -1) length = i::StrLength(data);
4545 i::Handle<i::String> result =
4546 isolate->factory()->NewStringFromUtf8(
4547 i::Vector<const char>(data, length));
4548 result->MarkAsUndetectable();
4549 return Utils::ToLocal(result);
4553 static int TwoByteStringLength(const uint16_t* data) {
4555 while (data[length] != '\0') length++;
4560 Local<String> v8::String::New(const uint16_t* data, int length) {
4561 i::Isolate* isolate = i::Isolate::Current();
4562 EnsureInitializedForIsolate(isolate, "v8::String::New()");
4563 LOG_API(isolate, "String::New(uint16_)");
4564 if (length == 0) return Empty();
4566 if (length == -1) length = TwoByteStringLength(data);
4567 i::Handle<i::String> result =
4568 isolate->factory()->NewStringFromTwoByte(
4569 i::Vector<const uint16_t>(data, length));
4570 return Utils::ToLocal(result);
4574 Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
4575 i::Isolate* isolate = i::Isolate::Current();
4576 EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4577 LOG_API(isolate, "String::NewUndetectable(uint16_)");
4579 if (length == -1) length = TwoByteStringLength(data);
4580 i::Handle<i::String> result =
4581 isolate->factory()->NewStringFromTwoByte(
4582 i::Vector<const uint16_t>(data, length));
4583 result->MarkAsUndetectable();
4584 return Utils::ToLocal(result);
4588 i::Handle<i::String> NewExternalStringHandle(i::Isolate* isolate,
4589 v8::String::ExternalStringResource* resource) {
4590 i::Handle<i::String> result =
4591 isolate->factory()->NewExternalStringFromTwoByte(resource);
4596 i::Handle<i::String> NewExternalAsciiStringHandle(i::Isolate* isolate,
4597 v8::String::ExternalAsciiStringResource* resource) {
4598 i::Handle<i::String> result =
4599 isolate->factory()->NewExternalStringFromAscii(resource);
4604 Local<String> v8::String::NewExternal(
4605 v8::String::ExternalStringResource* resource) {
4606 i::Isolate* isolate = i::Isolate::Current();
4607 EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4608 LOG_API(isolate, "String::NewExternal");
4610 i::Handle<i::String> result = NewExternalStringHandle(isolate, resource);
4611 isolate->heap()->external_string_table()->AddString(*result);
4612 return Utils::ToLocal(result);
4616 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
4617 i::Handle<i::String> obj = Utils::OpenHandle(this);
4618 i::Isolate* isolate = obj->GetIsolate();
4619 if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4620 if (i::StringShape(*obj).IsExternalTwoByte()) {
4621 return false; // Already an external string.
4624 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4627 if (isolate->heap()->IsInGCPostProcessing()) {
4630 bool result = obj->MakeExternal(resource);
4631 if (result && !obj->IsSymbol()) {
4632 isolate->heap()->external_string_table()->AddString(*obj);
4638 Local<String> v8::String::NewExternal(
4639 v8::String::ExternalAsciiStringResource* resource) {
4640 i::Isolate* isolate = i::Isolate::Current();
4641 EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4642 LOG_API(isolate, "String::NewExternal");
4644 i::Handle<i::String> result = NewExternalAsciiStringHandle(isolate, resource);
4645 isolate->heap()->external_string_table()->AddString(*result);
4646 return Utils::ToLocal(result);
4650 bool v8::String::MakeExternal(
4651 v8::String::ExternalAsciiStringResource* resource) {
4652 i::Handle<i::String> obj = Utils::OpenHandle(this);
4653 i::Isolate* isolate = obj->GetIsolate();
4654 if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4655 if (i::StringShape(*obj).IsExternalTwoByte()) {
4656 return false; // Already an external string.
4659 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4662 if (isolate->heap()->IsInGCPostProcessing()) {
4665 bool result = obj->MakeExternal(resource);
4666 if (result && !obj->IsSymbol()) {
4667 isolate->heap()->external_string_table()->AddString(*obj);
4673 bool v8::String::CanMakeExternal() {
4674 if (!internal::FLAG_clever_optimizations) return false;
4675 i::Handle<i::String> obj = Utils::OpenHandle(this);
4676 i::Isolate* isolate = obj->GetIsolate();
4677 if (IsDeadCheck(isolate, "v8::String::CanMakeExternal()")) return false;
4678 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4681 int size = obj->Size(); // Byte size of the original string.
4682 if (size < i::ExternalString::kSize)
4684 i::StringShape shape(*obj);
4685 return !shape.IsExternal();
4689 Local<v8::Object> v8::Object::New() {
4690 i::Isolate* isolate = i::Isolate::Current();
4691 EnsureInitializedForIsolate(isolate, "v8::Object::New()");
4692 LOG_API(isolate, "Object::New");
4694 i::Handle<i::JSObject> obj =
4695 isolate->factory()->NewJSObject(isolate->object_function());
4696 return Utils::ToLocal(obj);
4700 Local<v8::Value> v8::NumberObject::New(double value) {
4701 i::Isolate* isolate = i::Isolate::Current();
4702 EnsureInitializedForIsolate(isolate, "v8::NumberObject::New()");
4703 LOG_API(isolate, "NumberObject::New");
4705 i::Handle<i::Object> number = isolate->factory()->NewNumber(value);
4706 i::Handle<i::Object> obj = isolate->factory()->ToObject(number);
4707 return Utils::ToLocal(obj);
4711 double v8::NumberObject::NumberValue() const {
4712 i::Isolate* isolate = i::Isolate::Current();
4713 if (IsDeadCheck(isolate, "v8::NumberObject::NumberValue()")) return 0;
4714 LOG_API(isolate, "NumberObject::NumberValue");
4715 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4716 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4717 return jsvalue->value()->Number();
4721 Local<v8::Value> v8::BooleanObject::New(bool value) {
4722 i::Isolate* isolate = i::Isolate::Current();
4723 EnsureInitializedForIsolate(isolate, "v8::BooleanObject::New()");
4724 LOG_API(isolate, "BooleanObject::New");
4726 i::Handle<i::Object> boolean(value ? isolate->heap()->true_value()
4727 : isolate->heap()->false_value());
4728 i::Handle<i::Object> obj = isolate->factory()->ToObject(boolean);
4729 return Utils::ToLocal(obj);
4733 bool v8::BooleanObject::BooleanValue() const {
4734 i::Isolate* isolate = i::Isolate::Current();
4735 if (IsDeadCheck(isolate, "v8::BooleanObject::BooleanValue()")) return 0;
4736 LOG_API(isolate, "BooleanObject::BooleanValue");
4737 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4738 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4739 return jsvalue->value()->IsTrue();
4743 Local<v8::Value> v8::StringObject::New(Handle<String> value) {
4744 i::Isolate* isolate = i::Isolate::Current();
4745 EnsureInitializedForIsolate(isolate, "v8::StringObject::New()");
4746 LOG_API(isolate, "StringObject::New");
4748 i::Handle<i::Object> obj =
4749 isolate->factory()->ToObject(Utils::OpenHandle(*value));
4750 return Utils::ToLocal(obj);
4754 Local<v8::String> v8::StringObject::StringValue() const {
4755 i::Isolate* isolate = i::Isolate::Current();
4756 if (IsDeadCheck(isolate, "v8::StringObject::StringValue()")) {
4757 return Local<v8::String>();
4759 LOG_API(isolate, "StringObject::StringValue");
4760 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4761 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4762 return Utils::ToLocal(
4763 i::Handle<i::String>(i::String::cast(jsvalue->value())));
4767 Local<v8::Value> v8::Date::New(double time) {
4768 i::Isolate* isolate = i::Isolate::Current();
4769 EnsureInitializedForIsolate(isolate, "v8::Date::New()");
4770 LOG_API(isolate, "Date::New");
4772 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4773 time = i::OS::nan_value();
4776 EXCEPTION_PREAMBLE(isolate);
4777 i::Handle<i::Object> obj =
4778 i::Execution::NewDate(time, &has_pending_exception);
4779 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Value>());
4780 return Utils::ToLocal(obj);
4784 double v8::Date::NumberValue() const {
4785 i::Isolate* isolate = i::Isolate::Current();
4786 if (IsDeadCheck(isolate, "v8::Date::NumberValue()")) return 0;
4787 LOG_API(isolate, "Date::NumberValue");
4788 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4789 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4790 return jsvalue->value()->Number();
4794 void v8::Date::DateTimeConfigurationChangeNotification() {
4795 i::Isolate* isolate = i::Isolate::Current();
4796 ON_BAILOUT(isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
4798 LOG_API(isolate, "Date::DateTimeConfigurationChangeNotification");
4801 i::HandleScope scope(isolate);
4802 // Get the function ResetDateCache (defined in date-delay.js).
4803 i::Handle<i::String> func_name_str =
4804 isolate->factory()->LookupAsciiSymbol("ResetDateCache");
4805 i::MaybeObject* result =
4806 isolate->js_builtins_object()->GetProperty(*func_name_str);
4807 i::Object* object_func;
4808 if (!result->ToObject(&object_func)) {
4812 if (object_func->IsJSFunction()) {
4813 i::Handle<i::JSFunction> func =
4814 i::Handle<i::JSFunction>(i::JSFunction::cast(object_func));
4816 // Call ResetDateCache(0 but expect no exceptions:
4817 bool caught_exception = false;
4818 i::Execution::TryCall(func,
4819 isolate->js_builtins_object(),
4827 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
4830 if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
4831 if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
4832 if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
4833 ASSERT(num_flags <= static_cast<int>(ARRAY_SIZE(flags_buf)));
4834 return FACTORY->LookupSymbol(
4835 i::Vector<const char>(flags_buf, num_flags));
4839 Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
4841 i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
4842 EnsureInitializedForIsolate(isolate, "v8::RegExp::New()");
4843 LOG_API(isolate, "RegExp::New");
4845 EXCEPTION_PREAMBLE(isolate);
4846 i::Handle<i::JSRegExp> obj = i::Execution::NewJSRegExp(
4847 Utils::OpenHandle(*pattern),
4848 RegExpFlagsToString(flags),
4849 &has_pending_exception);
4850 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::RegExp>());
4851 return Utils::ToLocal(i::Handle<i::JSRegExp>::cast(obj));
4855 Local<v8::String> v8::RegExp::GetSource() const {
4856 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4857 if (IsDeadCheck(isolate, "v8::RegExp::GetSource()")) {
4858 return Local<v8::String>();
4860 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4861 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
4865 // Assert that the static flags cast in GetFlags is valid.
4866 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
4867 STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
4868 static_cast<int>(i::JSRegExp::internal_flag))
4869 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
4870 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
4871 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
4872 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
4873 #undef REGEXP_FLAG_ASSERT_EQ
4875 v8::RegExp::Flags v8::RegExp::GetFlags() const {
4876 if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::GetFlags()")) {
4877 return v8::RegExp::kNone;
4879 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4880 return static_cast<RegExp::Flags>(obj->GetFlags().value());
4884 Local<v8::Array> v8::Array::New(int length) {
4885 i::Isolate* isolate = i::Isolate::Current();
4886 EnsureInitializedForIsolate(isolate, "v8::Array::New()");
4887 LOG_API(isolate, "Array::New");
4889 int real_length = length > 0 ? length : 0;
4890 i::Handle<i::JSArray> obj = isolate->factory()->NewJSArray(real_length);
4891 i::Handle<i::Object> length_obj =
4892 isolate->factory()->NewNumberFromInt(real_length);
4893 obj->set_length(*length_obj);
4894 return Utils::ToLocal(obj);
4898 uint32_t v8::Array::Length() const {
4899 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4900 if (IsDeadCheck(isolate, "v8::Array::Length()")) return 0;
4901 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
4902 i::Object* length = obj->length();
4903 if (length->IsSmi()) {
4904 return i::Smi::cast(length)->value();
4906 return static_cast<uint32_t>(length->Number());
4911 Local<Object> Array::CloneElementAt(uint32_t index) {
4912 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4913 ON_BAILOUT(isolate, "v8::Array::CloneElementAt()", return Local<Object>());
4914 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4915 if (!self->HasFastElements()) {
4916 return Local<Object>();
4918 i::FixedArray* elms = i::FixedArray::cast(self->elements());
4919 i::Object* paragon = elms->get(index);
4920 if (!paragon->IsJSObject()) {
4921 return Local<Object>();
4923 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
4924 EXCEPTION_PREAMBLE(isolate);
4926 i::Handle<i::JSObject> result = i::Copy(paragon_handle);
4927 has_pending_exception = result.is_null();
4928 EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
4929 return Utils::ToLocal(result);
4933 Local<String> v8::String::NewSymbol(const char* data, int length) {
4934 i::Isolate* isolate = i::Isolate::Current();
4935 EnsureInitializedForIsolate(isolate, "v8::String::NewSymbol()");
4936 LOG_API(isolate, "String::NewSymbol(char)");
4938 if (length == -1) length = i::StrLength(data);
4939 i::Handle<i::String> result =
4940 isolate->factory()->LookupSymbol(i::Vector<const char>(data, length));
4941 return Utils::ToLocal(result);
4945 Local<Number> v8::Number::New(double value) {
4946 i::Isolate* isolate = i::Isolate::Current();
4947 EnsureInitializedForIsolate(isolate, "v8::Number::New()");
4949 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4950 value = i::OS::nan_value();
4953 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4954 return Utils::NumberToLocal(result);
4958 Local<Integer> v8::Integer::New(int32_t value) {
4959 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4960 EnsureInitializedForIsolate(isolate, "v8::Integer::New()");
4961 if (i::Smi::IsValid(value)) {
4962 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
4966 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4967 return Utils::IntegerToLocal(result);
4971 Local<Integer> Integer::NewFromUnsigned(uint32_t value) {
4972 bool fits_into_int32_t = (value & (1 << 31)) == 0;
4973 if (fits_into_int32_t) {
4974 return Integer::New(static_cast<int32_t>(value));
4976 i::Isolate* isolate = i::Isolate::Current();
4978 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
4979 return Utils::IntegerToLocal(result);
4983 void V8::IgnoreOutOfMemoryException() {
4984 EnterIsolateIfNeeded()->set_ignore_out_of_memory(true);
4988 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
4989 i::Isolate* isolate = i::Isolate::Current();
4990 EnsureInitializedForIsolate(isolate, "v8::V8::AddMessageListener()");
4991 ON_BAILOUT(isolate, "v8::V8::AddMessageListener()", return false);
4993 i::HandleScope scope(isolate);
4994 NeanderArray listeners(isolate->factory()->message_listeners());
4995 NeanderObject obj(2);
4996 obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
4997 obj.set(1, data.IsEmpty() ?
4998 isolate->heap()->undefined_value() :
4999 *Utils::OpenHandle(*data));
5000 listeners.add(obj.value());
5005 void V8::RemoveMessageListeners(MessageCallback that) {
5006 i::Isolate* isolate = i::Isolate::Current();
5007 EnsureInitializedForIsolate(isolate, "v8::V8::RemoveMessageListener()");
5008 ON_BAILOUT(isolate, "v8::V8::RemoveMessageListeners()", return);
5010 i::HandleScope scope(isolate);
5011 NeanderArray listeners(isolate->factory()->message_listeners());
5012 for (int i = 0; i < listeners.length(); i++) {
5013 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
5015 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
5016 i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
5017 if (callback_obj->address() == FUNCTION_ADDR(that)) {
5018 listeners.set(i, isolate->heap()->undefined_value());
5024 void V8::SetCaptureStackTraceForUncaughtExceptions(
5027 StackTrace::StackTraceOptions options) {
5028 i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
5035 void V8::SetCounterFunction(CounterLookupCallback callback) {
5036 i::Isolate* isolate = EnterIsolateIfNeeded();
5037 if (IsDeadCheck(isolate, "v8::V8::SetCounterFunction()")) return;
5038 isolate->stats_table()->SetCounterFunction(callback);
5041 void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
5042 i::Isolate* isolate = EnterIsolateIfNeeded();
5043 if (IsDeadCheck(isolate, "v8::V8::SetCreateHistogramFunction()")) return;
5044 isolate->stats_table()->SetCreateHistogramFunction(callback);
5047 void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
5048 i::Isolate* isolate = EnterIsolateIfNeeded();
5049 if (IsDeadCheck(isolate, "v8::V8::SetAddHistogramSampleFunction()")) return;
5050 isolate->stats_table()->
5051 SetAddHistogramSampleFunction(callback);
5054 void V8::EnableSlidingStateWindow() {
5055 i::Isolate* isolate = i::Isolate::Current();
5056 if (IsDeadCheck(isolate, "v8::V8::EnableSlidingStateWindow()")) return;
5057 isolate->logger()->EnableSlidingStateWindow();
5061 void V8::SetFailedAccessCheckCallbackFunction(
5062 FailedAccessCheckCallback callback) {
5063 i::Isolate* isolate = i::Isolate::Current();
5064 if (IsDeadCheck(isolate, "v8::V8::SetFailedAccessCheckCallbackFunction()")) {
5067 isolate->SetFailedAccessCheckCallback(callback);
5070 void V8::AddObjectGroup(Persistent<Value>* objects,
5072 RetainedObjectInfo* info) {
5073 i::Isolate* isolate = i::Isolate::Current();
5074 if (IsDeadCheck(isolate, "v8::V8::AddObjectGroup()")) return;
5075 STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5076 isolate->global_handles()->AddObjectGroup(
5077 reinterpret_cast<i::Object***>(objects), length, info);
5081 void V8::AddImplicitReferences(Persistent<Object> parent,
5082 Persistent<Value>* children,
5084 i::Isolate* isolate = i::Isolate::Current();
5085 if (IsDeadCheck(isolate, "v8::V8::AddImplicitReferences()")) return;
5086 STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5087 isolate->global_handles()->AddImplicitReferences(
5088 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(*parent)).location(),
5089 reinterpret_cast<i::Object***>(children), length);
5093 int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
5094 i::Isolate* isolate = i::Isolate::Current();
5095 if (IsDeadCheck(isolate, "v8::V8::AdjustAmountOfExternalAllocatedMemory()")) {
5098 return isolate->heap()->AdjustAmountOfExternalAllocatedMemory(
5103 void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
5104 i::Isolate* isolate = i::Isolate::Current();
5105 if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCPrologueCallback()")) return;
5106 isolate->heap()->SetGlobalGCPrologueCallback(callback);
5110 void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
5111 i::Isolate* isolate = i::Isolate::Current();
5112 if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCEpilogueCallback()")) return;
5113 isolate->heap()->SetGlobalGCEpilogueCallback(callback);
5117 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5118 i::Isolate* isolate = i::Isolate::Current();
5119 if (IsDeadCheck(isolate, "v8::V8::AddGCPrologueCallback()")) return;
5120 isolate->heap()->AddGCPrologueCallback(callback, gc_type);
5124 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5125 i::Isolate* isolate = i::Isolate::Current();
5126 if (IsDeadCheck(isolate, "v8::V8::RemoveGCPrologueCallback()")) return;
5127 isolate->heap()->RemoveGCPrologueCallback(callback);
5131 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5132 i::Isolate* isolate = i::Isolate::Current();
5133 if (IsDeadCheck(isolate, "v8::V8::AddGCEpilogueCallback()")) return;
5134 isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
5138 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5139 i::Isolate* isolate = i::Isolate::Current();
5140 if (IsDeadCheck(isolate, "v8::V8::RemoveGCEpilogueCallback()")) return;
5141 isolate->heap()->RemoveGCEpilogueCallback(callback);
5145 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5147 AllocationAction action) {
5148 i::Isolate* isolate = i::Isolate::Current();
5149 if (IsDeadCheck(isolate, "v8::V8::AddMemoryAllocationCallback()")) return;
5150 isolate->memory_allocator()->AddMemoryAllocationCallback(
5151 callback, space, action);
5155 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
5156 i::Isolate* isolate = i::Isolate::Current();
5157 if (IsDeadCheck(isolate, "v8::V8::RemoveMemoryAllocationCallback()")) return;
5158 isolate->memory_allocator()->RemoveMemoryAllocationCallback(
5163 void V8::PauseProfiler() {
5164 i::Isolate* isolate = i::Isolate::Current();
5165 isolate->logger()->PauseProfiler();
5169 void V8::ResumeProfiler() {
5170 i::Isolate* isolate = i::Isolate::Current();
5171 isolate->logger()->ResumeProfiler();
5175 bool V8::IsProfilerPaused() {
5176 i::Isolate* isolate = i::Isolate::Current();
5177 return isolate->logger()->IsProfilerPaused();
5181 int V8::GetCurrentThreadId() {
5182 i::Isolate* isolate = i::Isolate::Current();
5183 EnsureInitializedForIsolate(isolate, "V8::GetCurrentThreadId()");
5184 return isolate->thread_id().ToInteger();
5188 void V8::TerminateExecution(int thread_id) {
5189 i::Isolate* isolate = i::Isolate::Current();
5190 if (!isolate->IsInitialized()) return;
5191 API_ENTRY_CHECK(isolate, "V8::TerminateExecution()");
5192 // If the thread_id identifies the current thread just terminate
5193 // execution right away. Otherwise, ask the thread manager to
5194 // terminate the thread with the given id if any.
5195 i::ThreadId internal_tid = i::ThreadId::FromInteger(thread_id);
5196 if (isolate->thread_id().Equals(internal_tid)) {
5197 isolate->stack_guard()->TerminateExecution();
5199 isolate->thread_manager()->TerminateExecution(internal_tid);
5204 void V8::TerminateExecution(Isolate* isolate) {
5205 // If no isolate is supplied, use the default isolate.
5206 if (isolate != NULL) {
5207 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->TerminateExecution();
5209 i::Isolate::GetDefaultIsolateStackGuard()->TerminateExecution();
5214 bool V8::IsExecutionTerminating(Isolate* isolate) {
5215 i::Isolate* i_isolate = isolate != NULL ?
5216 reinterpret_cast<i::Isolate*>(isolate) : i::Isolate::Current();
5217 return IsExecutionTerminatingCheck(i_isolate);
5221 Isolate* Isolate::GetCurrent() {
5222 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5223 return reinterpret_cast<Isolate*>(isolate);
5227 Isolate* Isolate::New() {
5228 i::Isolate* isolate = new i::Isolate();
5229 return reinterpret_cast<Isolate*>(isolate);
5233 void Isolate::Dispose() {
5234 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5235 if (!ApiCheck(!isolate->IsInUse(),
5236 "v8::Isolate::Dispose()",
5237 "Disposing the isolate that is entered by a thread.")) {
5240 isolate->TearDown();
5244 void Isolate::Enter() {
5245 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5250 void Isolate::Exit() {
5251 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5256 void Isolate::SetData(void* data) {
5257 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5258 isolate->SetData(data);
5261 void* Isolate::GetData() {
5262 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5263 return isolate->GetData();
5267 String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj)
5268 : str_(NULL), length_(0) {
5269 i::Isolate* isolate = i::Isolate::Current();
5270 if (IsDeadCheck(isolate, "v8::String::Utf8Value::Utf8Value()")) return;
5271 if (obj.IsEmpty()) return;
5273 i::HandleScope scope(isolate);
5275 Handle<String> str = obj->ToString();
5276 if (str.IsEmpty()) return;
5277 length_ = str->Utf8Length();
5278 str_ = i::NewArray<char>(length_ + 1);
5279 str->WriteUtf8(str_);
5283 String::Utf8Value::~Utf8Value() {
5284 i::DeleteArray(str_);
5288 String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj)
5289 : str_(NULL), length_(0) {
5290 i::Isolate* isolate = i::Isolate::Current();
5291 if (IsDeadCheck(isolate, "v8::String::AsciiValue::AsciiValue()")) return;
5292 if (obj.IsEmpty()) return;
5294 i::HandleScope scope(isolate);
5296 Handle<String> str = obj->ToString();
5297 if (str.IsEmpty()) return;
5298 length_ = str->Length();
5299 str_ = i::NewArray<char>(length_ + 1);
5300 str->WriteAscii(str_);
5304 String::AsciiValue::~AsciiValue() {
5305 i::DeleteArray(str_);
5309 String::Value::Value(v8::Handle<v8::Value> obj)
5310 : str_(NULL), length_(0) {
5311 i::Isolate* isolate = i::Isolate::Current();
5312 if (IsDeadCheck(isolate, "v8::String::Value::Value()")) return;
5313 if (obj.IsEmpty()) return;
5315 i::HandleScope scope(isolate);
5317 Handle<String> str = obj->ToString();
5318 if (str.IsEmpty()) return;
5319 length_ = str->Length();
5320 str_ = i::NewArray<uint16_t>(length_ + 1);
5325 String::Value::~Value() {
5326 i::DeleteArray(str_);
5329 Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
5330 i::Isolate* isolate = i::Isolate::Current();
5331 LOG_API(isolate, "RangeError");
5332 ON_BAILOUT(isolate, "v8::Exception::RangeError()", return Local<Value>());
5336 i::HandleScope scope(isolate);
5337 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5338 i::Handle<i::Object> result = isolate->factory()->NewRangeError(message);
5341 i::Handle<i::Object> result(error);
5342 return Utils::ToLocal(result);
5345 Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
5346 i::Isolate* isolate = i::Isolate::Current();
5347 LOG_API(isolate, "ReferenceError");
5348 ON_BAILOUT(isolate, "v8::Exception::ReferenceError()", return Local<Value>());
5352 i::HandleScope scope(isolate);
5353 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5354 i::Handle<i::Object> result =
5355 isolate->factory()->NewReferenceError(message);
5358 i::Handle<i::Object> result(error);
5359 return Utils::ToLocal(result);
5362 Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
5363 i::Isolate* isolate = i::Isolate::Current();
5364 LOG_API(isolate, "SyntaxError");
5365 ON_BAILOUT(isolate, "v8::Exception::SyntaxError()", return Local<Value>());
5369 i::HandleScope scope(isolate);
5370 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5371 i::Handle<i::Object> result = isolate->factory()->NewSyntaxError(message);
5374 i::Handle<i::Object> result(error);
5375 return Utils::ToLocal(result);
5378 Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
5379 i::Isolate* isolate = i::Isolate::Current();
5380 LOG_API(isolate, "TypeError");
5381 ON_BAILOUT(isolate, "v8::Exception::TypeError()", return Local<Value>());
5385 i::HandleScope scope(isolate);
5386 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5387 i::Handle<i::Object> result = isolate->factory()->NewTypeError(message);
5390 i::Handle<i::Object> result(error);
5391 return Utils::ToLocal(result);
5394 Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
5395 i::Isolate* isolate = i::Isolate::Current();
5396 LOG_API(isolate, "Error");
5397 ON_BAILOUT(isolate, "v8::Exception::Error()", return Local<Value>());
5401 i::HandleScope scope(isolate);
5402 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5403 i::Handle<i::Object> result = isolate->factory()->NewError(message);
5406 i::Handle<i::Object> result(error);
5407 return Utils::ToLocal(result);
5411 // --- D e b u g S u p p o r t ---
5413 #ifdef ENABLE_DEBUGGER_SUPPORT
5415 static void EventCallbackWrapper(const v8::Debug::EventDetails& event_details) {
5416 i::Isolate* isolate = i::Isolate::Current();
5417 if (isolate->debug_event_callback() != NULL) {
5418 isolate->debug_event_callback()(event_details.GetEvent(),
5419 event_details.GetExecutionState(),
5420 event_details.GetEventData(),
5421 event_details.GetCallbackData());
5426 bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
5427 i::Isolate* isolate = i::Isolate::Current();
5428 EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener()");
5429 ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5432 isolate->set_debug_event_callback(that);
5434 i::HandleScope scope(isolate);
5435 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5438 isolate->factory()->NewForeign(FUNCTION_ADDR(EventCallbackWrapper));
5440 isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5445 bool Debug::SetDebugEventListener2(EventCallback2 that, Handle<Value> data) {
5446 i::Isolate* isolate = i::Isolate::Current();
5447 EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener2()");
5448 ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener2()", return false);
5450 i::HandleScope scope(isolate);
5451 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5453 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
5455 isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5460 bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
5461 Handle<Value> data) {
5462 i::Isolate* isolate = i::Isolate::Current();
5463 ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5465 isolate->debugger()->SetEventListener(Utils::OpenHandle(*that),
5466 Utils::OpenHandle(*data));
5471 void Debug::DebugBreak(Isolate* isolate) {
5472 // If no isolate is supplied, use the default isolate.
5473 if (isolate != NULL) {
5474 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->DebugBreak();
5476 i::Isolate::GetDefaultIsolateStackGuard()->DebugBreak();
5481 void Debug::CancelDebugBreak(Isolate* isolate) {
5482 // If no isolate is supplied, use the default isolate.
5483 if (isolate != NULL) {
5484 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5485 internal_isolate->stack_guard()->Continue(i::DEBUGBREAK);
5487 i::Isolate::GetDefaultIsolateStackGuard()->Continue(i::DEBUGBREAK);
5492 void Debug::DebugBreakForCommand(ClientData* data, Isolate* isolate) {
5493 // If no isolate is supplied, use the default isolate.
5494 if (isolate != NULL) {
5495 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5496 internal_isolate->debugger()->EnqueueDebugCommand(data);
5498 i::Isolate::GetDefaultIsolateDebugger()->EnqueueDebugCommand(data);
5503 static void MessageHandlerWrapper(const v8::Debug::Message& message) {
5504 i::Isolate* isolate = i::Isolate::Current();
5505 if (isolate->message_handler()) {
5506 v8::String::Value json(message.GetJSON());
5507 (isolate->message_handler())(*json, json.length(), message.GetClientData());
5512 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
5513 bool message_handler_thread) {
5514 i::Isolate* isolate = i::Isolate::Current();
5515 EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5518 // Message handler thread not supported any more. Parameter temporally left in
5519 // the API for client compatibility reasons.
5520 CHECK(!message_handler_thread);
5522 // TODO(sgjesse) support the old message handler API through a simple wrapper.
5523 isolate->set_message_handler(handler);
5524 if (handler != NULL) {
5525 isolate->debugger()->SetMessageHandler(MessageHandlerWrapper);
5527 isolate->debugger()->SetMessageHandler(NULL);
5532 void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
5533 i::Isolate* isolate = i::Isolate::Current();
5534 EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5536 isolate->debugger()->SetMessageHandler(handler);
5540 void Debug::SendCommand(const uint16_t* command, int length,
5541 ClientData* client_data,
5543 // If no isolate is supplied, use the default isolate.
5544 if (isolate != NULL) {
5545 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5546 internal_isolate->debugger()->ProcessCommand(
5547 i::Vector<const uint16_t>(command, length), client_data);
5549 i::Isolate::GetDefaultIsolateDebugger()->ProcessCommand(
5550 i::Vector<const uint16_t>(command, length), client_data);
5555 void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
5557 i::Isolate* isolate = i::Isolate::Current();
5558 EnsureInitializedForIsolate(isolate, "v8::Debug::SetHostDispatchHandler");
5560 isolate->debugger()->SetHostDispatchHandler(handler, period);
5564 void Debug::SetDebugMessageDispatchHandler(
5565 DebugMessageDispatchHandler handler, bool provide_locker) {
5566 i::Isolate* isolate = i::Isolate::Current();
5567 EnsureInitializedForIsolate(isolate,
5568 "v8::Debug::SetDebugMessageDispatchHandler");
5570 isolate->debugger()->SetDebugMessageDispatchHandler(
5571 handler, provide_locker);
5575 Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
5576 v8::Handle<v8::Value> data) {
5577 i::Isolate* isolate = i::Isolate::Current();
5578 if (!isolate->IsInitialized()) return Local<Value>();
5579 ON_BAILOUT(isolate, "v8::Debug::Call()", return Local<Value>());
5581 i::Handle<i::Object> result;
5582 EXCEPTION_PREAMBLE(isolate);
5583 if (data.IsEmpty()) {
5584 result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5585 isolate->factory()->undefined_value(),
5586 &has_pending_exception);
5588 result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5589 Utils::OpenHandle(*data),
5590 &has_pending_exception);
5592 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5593 return Utils::ToLocal(result);
5597 Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
5598 i::Isolate* isolate = i::Isolate::Current();
5599 if (!isolate->IsInitialized()) return Local<Value>();
5600 ON_BAILOUT(isolate, "v8::Debug::GetMirror()", return Local<Value>());
5602 v8::HandleScope scope;
5603 i::Debug* isolate_debug = isolate->debug();
5604 isolate_debug->Load();
5605 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global());
5606 i::Handle<i::String> name =
5607 isolate->factory()->LookupAsciiSymbol("MakeMirror");
5608 i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
5609 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
5610 v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
5611 const int kArgc = 1;
5612 v8::Handle<v8::Value> argv[kArgc] = { obj };
5613 EXCEPTION_PREAMBLE(isolate);
5614 v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
5617 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5618 return scope.Close(result);
5622 bool Debug::EnableAgent(const char* name, int port, bool wait_for_connection) {
5623 return i::Isolate::Current()->debugger()->StartAgent(name, port,
5624 wait_for_connection);
5628 void Debug::DisableAgent() {
5629 return i::Isolate::Current()->debugger()->StopAgent();
5633 void Debug::ProcessDebugMessages() {
5634 i::Execution::ProcessDebugMesssages(true);
5637 Local<Context> Debug::GetDebugContext() {
5638 i::Isolate* isolate = i::Isolate::Current();
5639 EnsureInitializedForIsolate(isolate, "v8::Debug::GetDebugContext()");
5641 return Utils::ToLocal(i::Isolate::Current()->debugger()->GetDebugContext());
5644 #endif // ENABLE_DEBUGGER_SUPPORT
5647 Handle<String> CpuProfileNode::GetFunctionName() const {
5648 i::Isolate* isolate = i::Isolate::Current();
5649 IsDeadCheck(isolate, "v8::CpuProfileNode::GetFunctionName");
5650 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5651 const i::CodeEntry* entry = node->entry();
5652 if (!entry->has_name_prefix()) {
5653 return Handle<String>(ToApi<String>(
5654 isolate->factory()->LookupAsciiSymbol(entry->name())));
5656 return Handle<String>(ToApi<String>(isolate->factory()->NewConsString(
5657 isolate->factory()->LookupAsciiSymbol(entry->name_prefix()),
5658 isolate->factory()->LookupAsciiSymbol(entry->name()))));
5663 Handle<String> CpuProfileNode::GetScriptResourceName() const {
5664 i::Isolate* isolate = i::Isolate::Current();
5665 IsDeadCheck(isolate, "v8::CpuProfileNode::GetScriptResourceName");
5666 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5667 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5668 node->entry()->resource_name())));
5672 int CpuProfileNode::GetLineNumber() const {
5673 i::Isolate* isolate = i::Isolate::Current();
5674 IsDeadCheck(isolate, "v8::CpuProfileNode::GetLineNumber");
5675 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
5679 double CpuProfileNode::GetTotalTime() const {
5680 i::Isolate* isolate = i::Isolate::Current();
5681 IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalTime");
5682 return reinterpret_cast<const i::ProfileNode*>(this)->GetTotalMillis();
5686 double CpuProfileNode::GetSelfTime() const {
5687 i::Isolate* isolate = i::Isolate::Current();
5688 IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfTime");
5689 return reinterpret_cast<const i::ProfileNode*>(this)->GetSelfMillis();
5693 double CpuProfileNode::GetTotalSamplesCount() const {
5694 i::Isolate* isolate = i::Isolate::Current();
5695 IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalSamplesCount");
5696 return reinterpret_cast<const i::ProfileNode*>(this)->total_ticks();
5700 double CpuProfileNode::GetSelfSamplesCount() const {
5701 i::Isolate* isolate = i::Isolate::Current();
5702 IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfSamplesCount");
5703 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
5707 unsigned CpuProfileNode::GetCallUid() const {
5708 i::Isolate* isolate = i::Isolate::Current();
5709 IsDeadCheck(isolate, "v8::CpuProfileNode::GetCallUid");
5710 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->GetCallUid();
5714 int CpuProfileNode::GetChildrenCount() const {
5715 i::Isolate* isolate = i::Isolate::Current();
5716 IsDeadCheck(isolate, "v8::CpuProfileNode::GetChildrenCount");
5717 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
5721 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
5722 i::Isolate* isolate = i::Isolate::Current();
5723 IsDeadCheck(isolate, "v8::CpuProfileNode::GetChild");
5724 const i::ProfileNode* child =
5725 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
5726 return reinterpret_cast<const CpuProfileNode*>(child);
5730 void CpuProfile::Delete() {
5731 i::Isolate* isolate = i::Isolate::Current();
5732 IsDeadCheck(isolate, "v8::CpuProfile::Delete");
5733 i::CpuProfiler::DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
5734 if (i::CpuProfiler::GetProfilesCount() == 0 &&
5735 !i::CpuProfiler::HasDetachedProfiles()) {
5736 // If this was the last profile, clean up all accessory data as well.
5737 i::CpuProfiler::DeleteAllProfiles();
5742 unsigned CpuProfile::GetUid() const {
5743 i::Isolate* isolate = i::Isolate::Current();
5744 IsDeadCheck(isolate, "v8::CpuProfile::GetUid");
5745 return reinterpret_cast<const i::CpuProfile*>(this)->uid();
5749 Handle<String> CpuProfile::GetTitle() const {
5750 i::Isolate* isolate = i::Isolate::Current();
5751 IsDeadCheck(isolate, "v8::CpuProfile::GetTitle");
5752 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5753 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5754 profile->title())));
5758 const CpuProfileNode* CpuProfile::GetBottomUpRoot() const {
5759 i::Isolate* isolate = i::Isolate::Current();
5760 IsDeadCheck(isolate, "v8::CpuProfile::GetBottomUpRoot");
5761 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5762 return reinterpret_cast<const CpuProfileNode*>(profile->bottom_up()->root());
5766 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
5767 i::Isolate* isolate = i::Isolate::Current();
5768 IsDeadCheck(isolate, "v8::CpuProfile::GetTopDownRoot");
5769 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5770 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
5774 int CpuProfiler::GetProfilesCount() {
5775 i::Isolate* isolate = i::Isolate::Current();
5776 IsDeadCheck(isolate, "v8::CpuProfiler::GetProfilesCount");
5777 return i::CpuProfiler::GetProfilesCount();
5781 const CpuProfile* CpuProfiler::GetProfile(int index,
5782 Handle<Value> security_token) {
5783 i::Isolate* isolate = i::Isolate::Current();
5784 IsDeadCheck(isolate, "v8::CpuProfiler::GetProfile");
5785 return reinterpret_cast<const CpuProfile*>(
5786 i::CpuProfiler::GetProfile(
5787 security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5792 const CpuProfile* CpuProfiler::FindProfile(unsigned uid,
5793 Handle<Value> security_token) {
5794 i::Isolate* isolate = i::Isolate::Current();
5795 IsDeadCheck(isolate, "v8::CpuProfiler::FindProfile");
5796 return reinterpret_cast<const CpuProfile*>(
5797 i::CpuProfiler::FindProfile(
5798 security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5803 void CpuProfiler::StartProfiling(Handle<String> title) {
5804 i::Isolate* isolate = i::Isolate::Current();
5805 IsDeadCheck(isolate, "v8::CpuProfiler::StartProfiling");
5806 i::CpuProfiler::StartProfiling(*Utils::OpenHandle(*title));
5810 const CpuProfile* CpuProfiler::StopProfiling(Handle<String> title,
5811 Handle<Value> security_token) {
5812 i::Isolate* isolate = i::Isolate::Current();
5813 IsDeadCheck(isolate, "v8::CpuProfiler::StopProfiling");
5814 return reinterpret_cast<const CpuProfile*>(
5815 i::CpuProfiler::StopProfiling(
5816 security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5817 *Utils::OpenHandle(*title)));
5821 void CpuProfiler::DeleteAllProfiles() {
5822 i::Isolate* isolate = i::Isolate::Current();
5823 IsDeadCheck(isolate, "v8::CpuProfiler::DeleteAllProfiles");
5824 i::CpuProfiler::DeleteAllProfiles();
5828 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
5829 return const_cast<i::HeapGraphEdge*>(
5830 reinterpret_cast<const i::HeapGraphEdge*>(edge));
5834 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
5835 i::Isolate* isolate = i::Isolate::Current();
5836 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetType");
5837 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
5841 Handle<Value> HeapGraphEdge::GetName() const {
5842 i::Isolate* isolate = i::Isolate::Current();
5843 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetName");
5844 i::HeapGraphEdge* edge = ToInternal(this);
5845 switch (edge->type()) {
5846 case i::HeapGraphEdge::kContextVariable:
5847 case i::HeapGraphEdge::kInternal:
5848 case i::HeapGraphEdge::kProperty:
5849 case i::HeapGraphEdge::kShortcut:
5850 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5852 case i::HeapGraphEdge::kElement:
5853 case i::HeapGraphEdge::kHidden:
5854 return Handle<Number>(ToApi<Number>(isolate->factory()->NewNumberFromInt(
5856 default: UNREACHABLE();
5858 return v8::Undefined();
5862 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
5863 i::Isolate* isolate = i::Isolate::Current();
5864 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetFromNode");
5865 const i::HeapEntry* from = ToInternal(this)->From();
5866 return reinterpret_cast<const HeapGraphNode*>(from);
5870 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
5871 i::Isolate* isolate = i::Isolate::Current();
5872 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetToNode");
5873 const i::HeapEntry* to = ToInternal(this)->to();
5874 return reinterpret_cast<const HeapGraphNode*>(to);
5878 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
5879 return const_cast<i::HeapEntry*>(
5880 reinterpret_cast<const i::HeapEntry*>(entry));
5884 HeapGraphNode::Type HeapGraphNode::GetType() const {
5885 i::Isolate* isolate = i::Isolate::Current();
5886 IsDeadCheck(isolate, "v8::HeapGraphNode::GetType");
5887 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
5891 Handle<String> HeapGraphNode::GetName() const {
5892 i::Isolate* isolate = i::Isolate::Current();
5893 IsDeadCheck(isolate, "v8::HeapGraphNode::GetName");
5894 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5895 ToInternal(this)->name())));
5899 uint64_t HeapGraphNode::GetId() const {
5900 i::Isolate* isolate = i::Isolate::Current();
5901 IsDeadCheck(isolate, "v8::HeapGraphNode::GetId");
5902 return ToInternal(this)->id();
5906 int HeapGraphNode::GetSelfSize() const {
5907 i::Isolate* isolate = i::Isolate::Current();
5908 IsDeadCheck(isolate, "v8::HeapGraphNode::GetSelfSize");
5909 return ToInternal(this)->self_size();
5913 int HeapGraphNode::GetRetainedSize(bool exact) const {
5914 i::Isolate* isolate = i::Isolate::Current();
5915 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainedSize");
5916 return ToInternal(this)->RetainedSize(exact);
5920 int HeapGraphNode::GetChildrenCount() const {
5921 i::Isolate* isolate = i::Isolate::Current();
5922 IsDeadCheck(isolate, "v8::HeapSnapshot::GetChildrenCount");
5923 return ToInternal(this)->children().length();
5927 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
5928 i::Isolate* isolate = i::Isolate::Current();
5929 IsDeadCheck(isolate, "v8::HeapSnapshot::GetChild");
5930 return reinterpret_cast<const HeapGraphEdge*>(
5931 &ToInternal(this)->children()[index]);
5935 int HeapGraphNode::GetRetainersCount() const {
5936 i::Isolate* isolate = i::Isolate::Current();
5937 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainersCount");
5938 return ToInternal(this)->retainers().length();
5942 const HeapGraphEdge* HeapGraphNode::GetRetainer(int index) const {
5943 i::Isolate* isolate = i::Isolate::Current();
5944 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainer");
5945 return reinterpret_cast<const HeapGraphEdge*>(
5946 ToInternal(this)->retainers()[index]);
5950 const HeapGraphNode* HeapGraphNode::GetDominatorNode() const {
5951 i::Isolate* isolate = i::Isolate::Current();
5952 IsDeadCheck(isolate, "v8::HeapSnapshot::GetDominatorNode");
5953 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->dominator());
5957 v8::Handle<v8::Value> HeapGraphNode::GetHeapValue() const {
5958 i::Isolate* isolate = i::Isolate::Current();
5959 IsDeadCheck(isolate, "v8::HeapGraphNode::GetHeapValue");
5960 i::Handle<i::HeapObject> object = ToInternal(this)->GetHeapObject();
5961 return v8::Handle<Value>(!object.is_null() ?
5962 ToApi<Value>(object) : ToApi<Value>(
5963 isolate->factory()->undefined_value()));
5967 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
5968 return const_cast<i::HeapSnapshot*>(
5969 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
5973 void HeapSnapshot::Delete() {
5974 i::Isolate* isolate = i::Isolate::Current();
5975 IsDeadCheck(isolate, "v8::HeapSnapshot::Delete");
5976 if (i::HeapProfiler::GetSnapshotsCount() > 1) {
5977 ToInternal(this)->Delete();
5979 // If this is the last snapshot, clean up all accessory data as well.
5980 i::HeapProfiler::DeleteAllSnapshots();
5985 HeapSnapshot::Type HeapSnapshot::GetType() const {
5986 i::Isolate* isolate = i::Isolate::Current();
5987 IsDeadCheck(isolate, "v8::HeapSnapshot::GetType");
5988 return static_cast<HeapSnapshot::Type>(ToInternal(this)->type());
5992 unsigned HeapSnapshot::GetUid() const {
5993 i::Isolate* isolate = i::Isolate::Current();
5994 IsDeadCheck(isolate, "v8::HeapSnapshot::GetUid");
5995 return ToInternal(this)->uid();
5999 Handle<String> HeapSnapshot::GetTitle() const {
6000 i::Isolate* isolate = i::Isolate::Current();
6001 IsDeadCheck(isolate, "v8::HeapSnapshot::GetTitle");
6002 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
6003 ToInternal(this)->title())));
6007 const HeapGraphNode* HeapSnapshot::GetRoot() const {
6008 i::Isolate* isolate = i::Isolate::Current();
6009 IsDeadCheck(isolate, "v8::HeapSnapshot::GetHead");
6010 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
6014 const HeapGraphNode* HeapSnapshot::GetNodeById(uint64_t id) const {
6015 i::Isolate* isolate = i::Isolate::Current();
6016 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodeById");
6017 return reinterpret_cast<const HeapGraphNode*>(
6018 ToInternal(this)->GetEntryById(id));
6022 int HeapSnapshot::GetNodesCount() const {
6023 i::Isolate* isolate = i::Isolate::Current();
6024 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodesCount");
6025 return ToInternal(this)->entries()->length();
6029 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
6030 i::Isolate* isolate = i::Isolate::Current();
6031 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNode");
6032 return reinterpret_cast<const HeapGraphNode*>(
6033 ToInternal(this)->entries()->at(index));
6037 void HeapSnapshot::Serialize(OutputStream* stream,
6038 HeapSnapshot::SerializationFormat format) const {
6039 i::Isolate* isolate = i::Isolate::Current();
6040 IsDeadCheck(isolate, "v8::HeapSnapshot::Serialize");
6041 ApiCheck(format == kJSON,
6042 "v8::HeapSnapshot::Serialize",
6043 "Unknown serialization format");
6044 ApiCheck(stream->GetOutputEncoding() == OutputStream::kAscii,
6045 "v8::HeapSnapshot::Serialize",
6046 "Unsupported output encoding");
6047 ApiCheck(stream->GetChunkSize() > 0,
6048 "v8::HeapSnapshot::Serialize",
6049 "Invalid stream chunk size");
6050 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
6051 serializer.Serialize(stream);
6055 int HeapProfiler::GetSnapshotsCount() {
6056 i::Isolate* isolate = i::Isolate::Current();
6057 IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshotsCount");
6058 return i::HeapProfiler::GetSnapshotsCount();
6062 const HeapSnapshot* HeapProfiler::GetSnapshot(int index) {
6063 i::Isolate* isolate = i::Isolate::Current();
6064 IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshot");
6065 return reinterpret_cast<const HeapSnapshot*>(
6066 i::HeapProfiler::GetSnapshot(index));
6070 const HeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {
6071 i::Isolate* isolate = i::Isolate::Current();
6072 IsDeadCheck(isolate, "v8::HeapProfiler::FindSnapshot");
6073 return reinterpret_cast<const HeapSnapshot*>(
6074 i::HeapProfiler::FindSnapshot(uid));
6078 const HeapSnapshot* HeapProfiler::TakeSnapshot(Handle<String> title,
6079 HeapSnapshot::Type type,
6080 ActivityControl* control) {
6081 i::Isolate* isolate = i::Isolate::Current();
6082 IsDeadCheck(isolate, "v8::HeapProfiler::TakeSnapshot");
6083 i::HeapSnapshot::Type internal_type = i::HeapSnapshot::kFull;
6085 case HeapSnapshot::kFull:
6086 internal_type = i::HeapSnapshot::kFull;
6091 return reinterpret_cast<const HeapSnapshot*>(
6092 i::HeapProfiler::TakeSnapshot(
6093 *Utils::OpenHandle(*title), internal_type, control));
6097 void HeapProfiler::DeleteAllSnapshots() {
6098 i::Isolate* isolate = i::Isolate::Current();
6099 IsDeadCheck(isolate, "v8::HeapProfiler::DeleteAllSnapshots");
6100 i::HeapProfiler::DeleteAllSnapshots();
6104 void HeapProfiler::DefineWrapperClass(uint16_t class_id,
6105 WrapperInfoCallback callback) {
6106 i::Isolate::Current()->heap_profiler()->DefineWrapperClass(class_id,
6112 v8::Testing::StressType internal::Testing::stress_type_ =
6113 v8::Testing::kStressTypeOpt;
6116 void Testing::SetStressRunType(Testing::StressType type) {
6117 internal::Testing::set_stress_type(type);
6120 int Testing::GetStressRuns() {
6121 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
6123 // In debug mode the code runs much slower so stressing will only make two
6132 static void SetFlagsFromString(const char* flags) {
6133 V8::SetFlagsFromString(flags, i::StrLength(flags));
6137 void Testing::PrepareStressRun(int run) {
6138 static const char* kLazyOptimizations =
6139 "--prepare-always-opt --nolimit-inlining "
6140 "--noalways-opt --noopt-eagerly";
6141 static const char* kEagerOptimizations = "--opt-eagerly";
6142 static const char* kForcedOptimizations = "--always-opt";
6144 // If deoptimization stressed turn on frequent deoptimization. If no value
6145 // is spefified through --deopt-every-n-times use a default default value.
6146 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
6147 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
6148 internal::FLAG_deopt_every_n_times == 0) {
6149 SetFlagsFromString(kDeoptEvery13Times);
6153 // As stressing in debug mode only make two runs skip the deopt stressing
6155 if (run == GetStressRuns() - 1) {
6156 SetFlagsFromString(kForcedOptimizations);
6158 SetFlagsFromString(kEagerOptimizations);
6159 SetFlagsFromString(kLazyOptimizations);
6162 if (run == GetStressRuns() - 1) {
6163 SetFlagsFromString(kForcedOptimizations);
6164 } else if (run == GetStressRuns() - 2) {
6165 SetFlagsFromString(kEagerOptimizations);
6167 SetFlagsFromString(kLazyOptimizations);
6173 void Testing::DeoptimizeAll() {
6174 internal::Deoptimizer::DeoptimizeAll();
6178 namespace internal {
6181 void HandleScopeImplementer::FreeThreadResources() {
6186 char* HandleScopeImplementer::ArchiveThread(char* storage) {
6187 v8::ImplementationUtilities::HandleScopeData* current =
6188 isolate_->handle_scope_data();
6189 handle_scope_data_ = *current;
6190 memcpy(storage, this, sizeof(*this));
6192 ResetAfterArchive();
6193 current->Initialize();
6195 return storage + ArchiveSpacePerThread();
6199 int HandleScopeImplementer::ArchiveSpacePerThread() {
6200 return sizeof(HandleScopeImplementer);
6204 char* HandleScopeImplementer::RestoreThread(char* storage) {
6205 memcpy(this, storage, sizeof(*this));
6206 *isolate_->handle_scope_data() = handle_scope_data_;
6207 return storage + ArchiveSpacePerThread();
6211 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
6212 // Iterate over all handles in the blocks except for the last.
6213 for (int i = blocks()->length() - 2; i >= 0; --i) {
6214 Object** block = blocks()->at(i);
6215 v->VisitPointers(block, &block[kHandleBlockSize]);
6218 // Iterate over live handles in the last block (if any).
6219 if (!blocks()->is_empty()) {
6220 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
6223 if (!saved_contexts_.is_empty()) {
6224 Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
6225 v->VisitPointers(start, start + saved_contexts_.length());
6230 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
6231 v8::ImplementationUtilities::HandleScopeData* current =
6232 isolate_->handle_scope_data();
6233 handle_scope_data_ = *current;
6238 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
6239 HandleScopeImplementer* scope_implementer =
6240 reinterpret_cast<HandleScopeImplementer*>(storage);
6241 scope_implementer->IterateThis(v);
6242 return storage + ArchiveSpacePerThread();
6245 } } // namespace v8::internal