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 void ObjectTemplate::MarkAsUseUserObjectComparison()
1469 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1470 if (IsDeadCheck(isolate, "v8::ObjectTemplate::MarkAsUseUserObjectComparison()")) {
1474 EnsureConstructor(this);
1475 Utils::OpenHandle(this)->set_use_user_object_comparison(i::Smi::FromInt(1));
1478 // --- S c r i p t D a t a ---
1481 ScriptData* ScriptData::PreCompile(const char* input, int length) {
1482 i::Utf8ToUC16CharacterStream stream(
1483 reinterpret_cast<const unsigned char*>(input), length);
1484 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1488 ScriptData* ScriptData::PreCompile(v8::Handle<String> source) {
1489 i::Handle<i::String> str = Utils::OpenHandle(*source);
1490 if (str->IsExternalTwoByteString()) {
1491 i::ExternalTwoByteStringUC16CharacterStream stream(
1492 i::Handle<i::ExternalTwoByteString>::cast(str), 0, str->length());
1493 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1495 i::GenericStringUC16CharacterStream stream(str, 0, str->length());
1496 return i::ParserApi::PreParse(&stream, NULL, i::FLAG_harmony_scoping);
1501 ScriptData* ScriptData::New(const char* data, int length) {
1502 // Return an empty ScriptData if the length is obviously invalid.
1503 if (length % sizeof(unsigned) != 0) {
1504 return new i::ScriptDataImpl();
1507 // Copy the data to ensure it is properly aligned.
1508 int deserialized_data_length = length / sizeof(unsigned);
1509 // If aligned, don't create a copy of the data.
1510 if (reinterpret_cast<intptr_t>(data) % sizeof(unsigned) == 0) {
1511 return new i::ScriptDataImpl(data, length);
1513 // Copy the data to align it.
1514 unsigned* deserialized_data = i::NewArray<unsigned>(deserialized_data_length);
1515 i::OS::MemCopy(deserialized_data, data, length);
1517 return new i::ScriptDataImpl(
1518 i::Vector<unsigned>(deserialized_data, deserialized_data_length));
1522 // --- S c r i p t ---
1525 Local<Script> Script::New(v8::Handle<String> source,
1526 v8::ScriptOrigin* origin,
1527 v8::ScriptData* pre_data,
1528 v8::Handle<String> script_data,
1529 v8::Script::CompileFlags compile_flags) {
1530 i::Isolate* isolate = i::Isolate::Current();
1531 ON_BAILOUT(isolate, "v8::Script::New()", return Local<Script>());
1532 LOG_API(isolate, "Script::New");
1534 i::Handle<i::String> str = Utils::OpenHandle(*source);
1535 i::Handle<i::Object> name_obj;
1536 int line_offset = 0;
1537 int column_offset = 0;
1538 if (origin != NULL) {
1539 if (!origin->ResourceName().IsEmpty()) {
1540 name_obj = Utils::OpenHandle(*origin->ResourceName());
1542 if (!origin->ResourceLineOffset().IsEmpty()) {
1543 line_offset = static_cast<int>(origin->ResourceLineOffset()->Value());
1545 if (!origin->ResourceColumnOffset().IsEmpty()) {
1546 column_offset = static_cast<int>(origin->ResourceColumnOffset()->Value());
1549 EXCEPTION_PREAMBLE(isolate);
1550 i::ScriptDataImpl* pre_data_impl = static_cast<i::ScriptDataImpl*>(pre_data);
1551 // We assert that the pre-data is sane, even though we can actually
1552 // handle it if it turns out not to be in release mode.
1553 ASSERT(pre_data_impl == NULL || pre_data_impl->SanityCheck());
1554 // If the pre-data isn't sane we simply ignore it
1555 if (pre_data_impl != NULL && !pre_data_impl->SanityCheck()) {
1556 pre_data_impl = NULL;
1558 i::Handle<i::SharedFunctionInfo> result =
1559 i::Compiler::Compile(str,
1565 Utils::OpenHandle(*script_data),
1566 i::NOT_NATIVES_CODE,
1568 has_pending_exception = result.is_null();
1569 EXCEPTION_BAILOUT_CHECK(isolate, Local<Script>());
1570 return Local<Script>(ToApi<Script>(result));
1574 Local<Script> Script::New(v8::Handle<String> source,
1575 v8::Handle<Value> file_name,
1576 v8::Script::CompileFlags compile_flags) {
1577 ScriptOrigin origin(file_name);
1578 return New(source, &origin, 0, Handle<String>(), compile_flags);
1582 Local<Script> Script::Compile(v8::Handle<String> source,
1583 v8::ScriptOrigin* origin,
1584 v8::ScriptData* pre_data,
1585 v8::Handle<String> script_data,
1586 v8::Script::CompileFlags compile_flags) {
1587 i::Isolate* isolate = i::Isolate::Current();
1588 ON_BAILOUT(isolate, "v8::Script::Compile()", return Local<Script>());
1589 LOG_API(isolate, "Script::Compile");
1591 Local<Script> generic = New(source, origin, pre_data, script_data, compile_flags);
1592 if (generic.IsEmpty())
1594 i::Handle<i::Object> obj = Utils::OpenHandle(*generic);
1595 i::Handle<i::SharedFunctionInfo> function =
1596 i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1597 i::Handle<i::JSFunction> result =
1598 isolate->factory()->NewFunctionFromSharedFunctionInfo(
1600 isolate->global_context());
1601 return Local<Script>(ToApi<Script>(result));
1605 Local<Script> Script::Compile(v8::Handle<String> source,
1606 v8::Handle<Value> file_name,
1607 v8::Handle<String> script_data,
1608 v8::Script::CompileFlags compile_flags) {
1609 ScriptOrigin origin(file_name);
1610 return Compile(source, &origin, 0, script_data, compile_flags);
1614 Local<Value> Script::Run() {
1615 return Run(Handle<Object>());
1618 Local<Value> Script::Run(Handle<Object> qml) {
1619 i::Isolate* isolate = i::Isolate::Current();
1620 ON_BAILOUT(isolate, "v8::Script::Run()", return Local<Value>());
1621 LOG_API(isolate, "Script::Run");
1623 i::Object* raw_result = NULL;
1625 i::HandleScope scope(isolate);
1626 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1627 i::Handle<i::JSFunction> fun;
1628 if (obj->IsSharedFunctionInfo()) {
1629 i::Handle<i::SharedFunctionInfo>
1630 function_info(i::SharedFunctionInfo::cast(*obj), isolate);
1631 fun = isolate->factory()->NewFunctionFromSharedFunctionInfo(
1632 function_info, isolate->global_context());
1634 fun = i::Handle<i::JSFunction>(i::JSFunction::cast(*obj), isolate);
1636 EXCEPTION_PREAMBLE(isolate);
1637 i::Handle<i::Object> qmlglobal = Utils::OpenHandle(*qml);
1638 i::Handle<i::Object> receiver(
1639 isolate->context()->global_proxy(), isolate);
1640 i::Handle<i::Object> result =
1641 i::Execution::Call(fun, receiver, 0, NULL, &has_pending_exception, false, qmlglobal);
1642 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
1643 raw_result = *result;
1645 i::Handle<i::Object> result(raw_result, isolate);
1646 return Utils::ToLocal(result);
1650 static i::Handle<i::SharedFunctionInfo> OpenScript(Script* script) {
1651 i::Handle<i::Object> obj = Utils::OpenHandle(script);
1652 i::Handle<i::SharedFunctionInfo> result;
1653 if (obj->IsSharedFunctionInfo()) {
1655 i::Handle<i::SharedFunctionInfo>(i::SharedFunctionInfo::cast(*obj));
1658 i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared());
1664 Local<Value> Script::Id() {
1665 i::Isolate* isolate = i::Isolate::Current();
1666 ON_BAILOUT(isolate, "v8::Script::Id()", return Local<Value>());
1667 LOG_API(isolate, "Script::Id");
1668 i::Object* raw_id = NULL;
1670 i::HandleScope scope(isolate);
1671 i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1672 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1673 i::Handle<i::Object> id(script->id());
1676 i::Handle<i::Object> id(raw_id);
1677 return Utils::ToLocal(id);
1681 void Script::SetData(v8::Handle<String> data) {
1682 i::Isolate* isolate = i::Isolate::Current();
1683 ON_BAILOUT(isolate, "v8::Script::SetData()", return);
1684 LOG_API(isolate, "Script::SetData");
1686 i::HandleScope scope(isolate);
1687 i::Handle<i::SharedFunctionInfo> function_info = OpenScript(this);
1688 i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
1689 i::Handle<i::Script> script(i::Script::cast(function_info->script()));
1690 script->set_data(*raw_data);
1695 // --- E x c e p t i o n s ---
1698 v8::TryCatch::TryCatch()
1699 : isolate_(i::Isolate::Current()),
1700 next_(isolate_->try_catch_handler_address()),
1701 exception_(isolate_->heap()->the_hole_value()),
1702 message_(i::Smi::FromInt(0)),
1704 can_continue_(true),
1705 capture_message_(true),
1707 isolate_->RegisterTryCatchHandler(this);
1711 v8::TryCatch::~TryCatch() {
1712 ASSERT(isolate_ == i::Isolate::Current());
1714 v8::HandleScope scope;
1715 v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(Exception());
1716 isolate_->UnregisterTryCatchHandler(this);
1717 v8::ThrowException(exc);
1719 isolate_->UnregisterTryCatchHandler(this);
1724 bool v8::TryCatch::HasCaught() const {
1725 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
1729 bool v8::TryCatch::CanContinue() const {
1730 return can_continue_;
1734 v8::Handle<v8::Value> v8::TryCatch::ReThrow() {
1735 if (!HasCaught()) return v8::Local<v8::Value>();
1737 return v8::Undefined();
1741 v8::Local<Value> v8::TryCatch::Exception() const {
1742 ASSERT(isolate_ == i::Isolate::Current());
1744 // Check for out of memory exception.
1745 i::Object* exception = reinterpret_cast<i::Object*>(exception_);
1746 return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
1748 return v8::Local<Value>();
1753 v8::Local<Value> v8::TryCatch::StackTrace() const {
1754 ASSERT(isolate_ == i::Isolate::Current());
1756 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
1757 if (!raw_obj->IsJSObject()) return v8::Local<Value>();
1758 i::HandleScope scope(isolate_);
1759 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
1760 i::Handle<i::String> name = isolate_->factory()->LookupAsciiSymbol("stack");
1761 if (!obj->HasProperty(*name)) return v8::Local<Value>();
1762 i::Handle<i::Object> value = i::GetProperty(obj, name);
1763 if (value.is_null()) return v8::Local<Value>();
1764 return v8::Utils::ToLocal(scope.CloseAndEscape(value));
1766 return v8::Local<Value>();
1771 v8::Local<v8::Message> v8::TryCatch::Message() const {
1772 ASSERT(isolate_ == i::Isolate::Current());
1773 if (HasCaught() && message_ != i::Smi::FromInt(0)) {
1774 i::Object* message = reinterpret_cast<i::Object*>(message_);
1775 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
1777 return v8::Local<v8::Message>();
1782 void v8::TryCatch::Reset() {
1783 ASSERT(isolate_ == i::Isolate::Current());
1784 exception_ = isolate_->heap()->the_hole_value();
1785 message_ = i::Smi::FromInt(0);
1789 void v8::TryCatch::SetVerbose(bool value) {
1790 is_verbose_ = value;
1794 void v8::TryCatch::SetCaptureMessage(bool value) {
1795 capture_message_ = value;
1799 // --- M e s s a g e ---
1802 Local<String> Message::Get() const {
1803 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1804 ON_BAILOUT(isolate, "v8::Message::Get()", return Local<String>());
1807 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1808 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(obj);
1809 Local<String> result = Utils::ToLocal(raw_result);
1810 return scope.Close(result);
1814 v8::Handle<Value> Message::GetScriptResourceName() const {
1815 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1816 if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceName()")) {
1817 return Local<String>();
1821 i::Handle<i::JSMessageObject> message =
1822 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1823 // Return this.script.name.
1824 i::Handle<i::JSValue> script =
1825 i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1826 i::Handle<i::Object> resource_name(i::Script::cast(script->value())->name());
1827 return scope.Close(Utils::ToLocal(resource_name));
1831 v8::Handle<Value> Message::GetScriptData() const {
1832 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1833 if (IsDeadCheck(isolate, "v8::Message::GetScriptResourceData()")) {
1834 return Local<Value>();
1838 i::Handle<i::JSMessageObject> message =
1839 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1840 // Return this.script.data.
1841 i::Handle<i::JSValue> script =
1842 i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script()));
1843 i::Handle<i::Object> data(i::Script::cast(script->value())->data());
1844 return scope.Close(Utils::ToLocal(data));
1848 v8::Handle<v8::StackTrace> Message::GetStackTrace() const {
1849 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1850 if (IsDeadCheck(isolate, "v8::Message::GetStackTrace()")) {
1851 return Local<v8::StackTrace>();
1855 i::Handle<i::JSMessageObject> message =
1856 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1857 i::Handle<i::Object> stackFramesObj(message->stack_frames());
1858 if (!stackFramesObj->IsJSArray()) return v8::Handle<v8::StackTrace>();
1859 i::Handle<i::JSArray> stackTrace =
1860 i::Handle<i::JSArray>::cast(stackFramesObj);
1861 return scope.Close(Utils::StackTraceToLocal(stackTrace));
1865 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1866 i::Handle<i::Object> recv,
1868 i::Handle<i::Object> argv[],
1869 bool* has_pending_exception) {
1870 i::Isolate* isolate = i::Isolate::Current();
1871 i::Handle<i::String> fmt_str = isolate->factory()->LookupAsciiSymbol(name);
1872 i::Object* object_fun =
1873 isolate->js_builtins_object()->GetPropertyNoExceptionThrown(*fmt_str);
1874 i::Handle<i::JSFunction> fun =
1875 i::Handle<i::JSFunction>(i::JSFunction::cast(object_fun));
1876 i::Handle<i::Object> value =
1877 i::Execution::Call(fun, recv, argc, argv, has_pending_exception);
1882 static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1883 i::Handle<i::Object> data,
1884 bool* has_pending_exception) {
1885 i::Handle<i::Object> argv[] = { data };
1886 return CallV8HeapFunction(name,
1887 i::Isolate::Current()->js_builtins_object(),
1890 has_pending_exception);
1894 int Message::GetLineNumber() const {
1895 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1896 ON_BAILOUT(isolate, "v8::Message::GetLineNumber()", return kNoLineNumberInfo);
1898 i::HandleScope scope(isolate);
1900 EXCEPTION_PREAMBLE(isolate);
1901 i::Handle<i::Object> result = CallV8HeapFunction("GetLineNumber",
1902 Utils::OpenHandle(this),
1903 &has_pending_exception);
1904 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1905 return static_cast<int>(result->Number());
1909 int Message::GetStartPosition() const {
1910 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1911 if (IsDeadCheck(isolate, "v8::Message::GetStartPosition()")) return 0;
1913 i::HandleScope scope(isolate);
1914 i::Handle<i::JSMessageObject> message =
1915 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1916 return message->start_position();
1920 int Message::GetEndPosition() const {
1921 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1922 if (IsDeadCheck(isolate, "v8::Message::GetEndPosition()")) return 0;
1924 i::HandleScope scope(isolate);
1925 i::Handle<i::JSMessageObject> message =
1926 i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
1927 return message->end_position();
1931 int Message::GetStartColumn() const {
1932 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1933 if (IsDeadCheck(isolate, "v8::Message::GetStartColumn()")) {
1934 return kNoColumnInfo;
1937 i::HandleScope scope(isolate);
1938 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1939 EXCEPTION_PREAMBLE(isolate);
1940 i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1941 "GetPositionInLine",
1943 &has_pending_exception);
1944 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1945 return static_cast<int>(start_col_obj->Number());
1949 int Message::GetEndColumn() const {
1950 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1951 if (IsDeadCheck(isolate, "v8::Message::GetEndColumn()")) return kNoColumnInfo;
1953 i::HandleScope scope(isolate);
1954 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1955 EXCEPTION_PREAMBLE(isolate);
1956 i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1957 "GetPositionInLine",
1959 &has_pending_exception);
1960 EXCEPTION_BAILOUT_CHECK(isolate, 0);
1961 i::Handle<i::JSMessageObject> message =
1962 i::Handle<i::JSMessageObject>::cast(data_obj);
1963 int start = message->start_position();
1964 int end = message->end_position();
1965 return static_cast<int>(start_col_obj->Number()) + (end - start);
1969 Local<String> Message::GetSourceLine() const {
1970 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1971 ON_BAILOUT(isolate, "v8::Message::GetSourceLine()", return Local<String>());
1974 EXCEPTION_PREAMBLE(isolate);
1975 i::Handle<i::Object> result = CallV8HeapFunction("GetSourceLine",
1976 Utils::OpenHandle(this),
1977 &has_pending_exception);
1978 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::String>());
1979 if (result->IsString()) {
1980 return scope.Close(Utils::ToLocal(i::Handle<i::String>::cast(result)));
1982 return Local<String>();
1987 void Message::PrintCurrentStackTrace(FILE* out) {
1988 i::Isolate* isolate = i::Isolate::Current();
1989 if (IsDeadCheck(isolate, "v8::Message::PrintCurrentStackTrace()")) return;
1991 isolate->PrintCurrentStackTrace(out);
1995 // --- S t a c k T r a c e ---
1997 Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
1998 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
1999 if (IsDeadCheck(isolate, "v8::StackTrace::GetFrame()")) {
2000 return Local<StackFrame>();
2004 i::Handle<i::JSArray> self = Utils::OpenHandle(this);
2005 i::Object* raw_object = self->GetElementNoExceptionThrown(index);
2006 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_object));
2007 return scope.Close(Utils::StackFrameToLocal(obj));
2011 int StackTrace::GetFrameCount() const {
2012 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2013 if (IsDeadCheck(isolate, "v8::StackTrace::GetFrameCount()")) return -1;
2015 return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
2019 Local<Array> StackTrace::AsArray() {
2020 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2021 if (IsDeadCheck(isolate, "v8::StackTrace::AsArray()")) Local<Array>();
2023 return Utils::ToLocal(Utils::OpenHandle(this));
2027 Local<StackTrace> StackTrace::CurrentStackTrace(int frame_limit,
2028 StackTraceOptions options) {
2029 i::Isolate* isolate = i::Isolate::Current();
2030 if (IsDeadCheck(isolate, "v8::StackTrace::CurrentStackTrace()")) {
2031 Local<StackTrace>();
2034 i::Handle<i::JSArray> stackTrace =
2035 isolate->CaptureCurrentStackTrace(frame_limit, options);
2036 return Utils::StackTraceToLocal(stackTrace);
2040 // --- S t a c k F r a m e ---
2042 int StackFrame::GetLineNumber() const {
2043 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2044 if (IsDeadCheck(isolate, "v8::StackFrame::GetLineNumber()")) {
2045 return Message::kNoLineNumberInfo;
2048 i::HandleScope scope(isolate);
2049 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2050 i::Handle<i::Object> line = GetProperty(self, "lineNumber");
2051 if (!line->IsSmi()) {
2052 return Message::kNoLineNumberInfo;
2054 return i::Smi::cast(*line)->value();
2058 int StackFrame::GetColumn() const {
2059 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2060 if (IsDeadCheck(isolate, "v8::StackFrame::GetColumn()")) {
2061 return Message::kNoColumnInfo;
2064 i::HandleScope scope(isolate);
2065 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2066 i::Handle<i::Object> column = GetProperty(self, "column");
2067 if (!column->IsSmi()) {
2068 return Message::kNoColumnInfo;
2070 return i::Smi::cast(*column)->value();
2074 Local<String> StackFrame::GetScriptName() const {
2075 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2076 if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptName()")) {
2077 return Local<String>();
2081 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2082 i::Handle<i::Object> name = GetProperty(self, "scriptName");
2083 if (!name->IsString()) {
2084 return Local<String>();
2086 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2090 Local<String> StackFrame::GetScriptNameOrSourceURL() const {
2091 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2092 if (IsDeadCheck(isolate, "v8::StackFrame::GetScriptNameOrSourceURL()")) {
2093 return Local<String>();
2097 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2098 i::Handle<i::Object> name = GetProperty(self, "scriptNameOrSourceURL");
2099 if (!name->IsString()) {
2100 return Local<String>();
2102 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2106 Local<String> StackFrame::GetFunctionName() const {
2107 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2108 if (IsDeadCheck(isolate, "v8::StackFrame::GetFunctionName()")) {
2109 return Local<String>();
2113 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2114 i::Handle<i::Object> name = GetProperty(self, "functionName");
2115 if (!name->IsString()) {
2116 return Local<String>();
2118 return scope.Close(Local<String>::Cast(Utils::ToLocal(name)));
2122 bool StackFrame::IsEval() const {
2123 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2124 if (IsDeadCheck(isolate, "v8::StackFrame::IsEval()")) return false;
2126 i::HandleScope scope(isolate);
2127 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2128 i::Handle<i::Object> is_eval = GetProperty(self, "isEval");
2129 return is_eval->IsTrue();
2133 bool StackFrame::IsConstructor() const {
2134 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2135 if (IsDeadCheck(isolate, "v8::StackFrame::IsConstructor()")) return false;
2137 i::HandleScope scope(isolate);
2138 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2139 i::Handle<i::Object> is_constructor = GetProperty(self, "isConstructor");
2140 return is_constructor->IsTrue();
2146 bool Value::IsUndefined() const {
2147 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUndefined()")) {
2150 return Utils::OpenHandle(this)->IsUndefined();
2154 bool Value::IsNull() const {
2155 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNull()")) return false;
2156 return Utils::OpenHandle(this)->IsNull();
2160 bool Value::IsTrue() const {
2161 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsTrue()")) return false;
2162 return Utils::OpenHandle(this)->IsTrue();
2166 bool Value::IsFalse() const {
2167 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFalse()")) return false;
2168 return Utils::OpenHandle(this)->IsFalse();
2172 bool Value::IsFunction() const {
2173 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsFunction()")) {
2176 return Utils::OpenHandle(this)->IsJSFunction();
2180 bool Value::FullIsString() const {
2181 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsString()")) return false;
2182 bool result = Utils::OpenHandle(this)->IsString();
2183 ASSERT_EQ(result, QuickIsString());
2188 bool Value::IsArray() const {
2189 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsArray()")) return false;
2190 return Utils::OpenHandle(this)->IsJSArray();
2194 bool Value::IsObject() const {
2195 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsObject()")) return false;
2196 return Utils::OpenHandle(this)->IsJSObject();
2200 bool Value::IsNumber() const {
2201 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsNumber()")) return false;
2202 return Utils::OpenHandle(this)->IsNumber();
2206 bool Value::IsBoolean() const {
2207 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsBoolean()")) {
2210 return Utils::OpenHandle(this)->IsBoolean();
2214 bool Value::IsExternal() const {
2215 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsExternal()")) {
2218 return Utils::OpenHandle(this)->IsForeign();
2222 bool Value::IsInt32() const {
2223 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsInt32()")) return false;
2224 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2225 if (obj->IsSmi()) return true;
2226 if (obj->IsNumber()) {
2227 double value = obj->Number();
2228 return i::FastI2D(i::FastD2I(value)) == value;
2234 bool Value::IsUint32() const {
2235 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsUint32()")) return false;
2236 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2237 if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
2238 if (obj->IsNumber()) {
2239 double value = obj->Number();
2240 return i::FastUI2D(i::FastD2UI(value)) == value;
2246 bool Value::IsDate() const {
2247 i::Isolate* isolate = i::Isolate::Current();
2248 if (IsDeadCheck(isolate, "v8::Value::IsDate()")) return false;
2249 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2250 return obj->HasSpecificClassOf(isolate->heap()->Date_symbol());
2254 bool Value::IsStringObject() const {
2255 i::Isolate* isolate = i::Isolate::Current();
2256 if (IsDeadCheck(isolate, "v8::Value::IsStringObject()")) return false;
2257 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2258 return obj->HasSpecificClassOf(isolate->heap()->String_symbol());
2262 bool Value::IsNumberObject() const {
2263 i::Isolate* isolate = i::Isolate::Current();
2264 if (IsDeadCheck(isolate, "v8::Value::IsNumberObject()")) return false;
2265 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2266 return obj->HasSpecificClassOf(isolate->heap()->Number_symbol());
2270 static i::Object* LookupBuiltin(i::Isolate* isolate,
2271 const char* builtin_name) {
2272 i::Handle<i::String> symbol =
2273 isolate->factory()->LookupAsciiSymbol(builtin_name);
2274 i::Handle<i::JSBuiltinsObject> builtins = isolate->js_builtins_object();
2275 return builtins->GetPropertyNoExceptionThrown(*symbol);
2279 static bool CheckConstructor(i::Isolate* isolate,
2280 i::Handle<i::JSObject> obj,
2281 const char* class_name) {
2282 return obj->map()->constructor() == LookupBuiltin(isolate, class_name);
2286 bool Value::IsNativeError() const {
2287 i::Isolate* isolate = i::Isolate::Current();
2288 if (IsDeadCheck(isolate, "v8::Value::IsNativeError()")) return false;
2289 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2290 if (obj->IsJSObject()) {
2291 i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
2292 return CheckConstructor(isolate, js_obj, "$Error") ||
2293 CheckConstructor(isolate, js_obj, "$EvalError") ||
2294 CheckConstructor(isolate, js_obj, "$RangeError") ||
2295 CheckConstructor(isolate, js_obj, "$ReferenceError") ||
2296 CheckConstructor(isolate, js_obj, "$SyntaxError") ||
2297 CheckConstructor(isolate, js_obj, "$TypeError") ||
2298 CheckConstructor(isolate, js_obj, "$URIError");
2305 bool Value::IsBooleanObject() const {
2306 i::Isolate* isolate = i::Isolate::Current();
2307 if (IsDeadCheck(isolate, "v8::Value::IsBooleanObject()")) return false;
2308 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2309 return obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol());
2313 bool Value::IsRegExp() const {
2314 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsRegExp()")) return false;
2315 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2316 return obj->IsJSRegExp();
2319 bool Value::IsError() const {
2320 if (IsDeadCheck(i::Isolate::Current(), "v8::Value::IsError()")) return false;
2321 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2322 return obj->HasSpecificClassOf(HEAP->Error_symbol());
2326 Local<String> Value::ToString() const {
2327 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2328 i::Handle<i::Object> str;
2329 if (obj->IsString()) {
2332 i::Isolate* isolate = i::Isolate::Current();
2333 if (IsDeadCheck(isolate, "v8::Value::ToString()")) {
2334 return Local<String>();
2336 LOG_API(isolate, "ToString");
2338 EXCEPTION_PREAMBLE(isolate);
2339 str = i::Execution::ToString(obj, &has_pending_exception);
2340 EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2342 return Local<String>(ToApi<String>(str));
2346 Local<String> Value::ToDetailString() const {
2347 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2348 i::Handle<i::Object> str;
2349 if (obj->IsString()) {
2352 i::Isolate* isolate = i::Isolate::Current();
2353 if (IsDeadCheck(isolate, "v8::Value::ToDetailString()")) {
2354 return Local<String>();
2356 LOG_API(isolate, "ToDetailString");
2358 EXCEPTION_PREAMBLE(isolate);
2359 str = i::Execution::ToDetailString(obj, &has_pending_exception);
2360 EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
2362 return Local<String>(ToApi<String>(str));
2366 Local<v8::Object> Value::ToObject() const {
2367 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2368 i::Handle<i::Object> val;
2369 if (obj->IsJSObject()) {
2372 i::Isolate* isolate = i::Isolate::Current();
2373 if (IsDeadCheck(isolate, "v8::Value::ToObject()")) {
2374 return Local<v8::Object>();
2376 LOG_API(isolate, "ToObject");
2378 EXCEPTION_PREAMBLE(isolate);
2379 val = i::Execution::ToObject(obj, &has_pending_exception);
2380 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
2382 return Local<v8::Object>(ToApi<Object>(val));
2386 Local<Boolean> Value::ToBoolean() const {
2387 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2388 if (obj->IsBoolean()) {
2389 return Local<Boolean>(ToApi<Boolean>(obj));
2391 i::Isolate* isolate = i::Isolate::Current();
2392 if (IsDeadCheck(isolate, "v8::Value::ToBoolean()")) {
2393 return Local<Boolean>();
2395 LOG_API(isolate, "ToBoolean");
2397 i::Handle<i::Object> val = i::Execution::ToBoolean(obj);
2398 return Local<Boolean>(ToApi<Boolean>(val));
2403 Local<Number> Value::ToNumber() const {
2404 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2405 i::Handle<i::Object> num;
2406 if (obj->IsNumber()) {
2409 i::Isolate* isolate = i::Isolate::Current();
2410 if (IsDeadCheck(isolate, "v8::Value::ToNumber()")) {
2411 return Local<Number>();
2413 LOG_API(isolate, "ToNumber");
2415 EXCEPTION_PREAMBLE(isolate);
2416 num = i::Execution::ToNumber(obj, &has_pending_exception);
2417 EXCEPTION_BAILOUT_CHECK(isolate, Local<Number>());
2419 return Local<Number>(ToApi<Number>(num));
2423 Local<Integer> Value::ToInteger() const {
2424 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2425 i::Handle<i::Object> num;
2429 i::Isolate* isolate = i::Isolate::Current();
2430 if (IsDeadCheck(isolate, "v8::Value::ToInteger()")) return Local<Integer>();
2431 LOG_API(isolate, "ToInteger");
2433 EXCEPTION_PREAMBLE(isolate);
2434 num = i::Execution::ToInteger(obj, &has_pending_exception);
2435 EXCEPTION_BAILOUT_CHECK(isolate, Local<Integer>());
2437 return Local<Integer>(ToApi<Integer>(num));
2441 void External::CheckCast(v8::Value* that) {
2442 if (IsDeadCheck(i::Isolate::Current(), "v8::External::Cast()")) return;
2443 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2444 ApiCheck(obj->IsForeign(),
2445 "v8::External::Cast()",
2446 "Could not convert to external");
2450 void v8::Object::CheckCast(Value* that) {
2451 if (IsDeadCheck(i::Isolate::Current(), "v8::Object::Cast()")) return;
2452 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2453 ApiCheck(obj->IsJSObject(),
2454 "v8::Object::Cast()",
2455 "Could not convert to object");
2459 void v8::Function::CheckCast(Value* that) {
2460 if (IsDeadCheck(i::Isolate::Current(), "v8::Function::Cast()")) return;
2461 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2462 ApiCheck(obj->IsJSFunction(),
2463 "v8::Function::Cast()",
2464 "Could not convert to function");
2468 void v8::String::CheckCast(v8::Value* that) {
2469 if (IsDeadCheck(i::Isolate::Current(), "v8::String::Cast()")) return;
2470 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2471 ApiCheck(obj->IsString(),
2472 "v8::String::Cast()",
2473 "Could not convert to string");
2477 void v8::Number::CheckCast(v8::Value* that) {
2478 if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Cast()")) return;
2479 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2480 ApiCheck(obj->IsNumber(),
2481 "v8::Number::Cast()",
2482 "Could not convert to number");
2486 void v8::Integer::CheckCast(v8::Value* that) {
2487 if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Cast()")) return;
2488 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2489 ApiCheck(obj->IsNumber(),
2490 "v8::Integer::Cast()",
2491 "Could not convert to number");
2495 void v8::Array::CheckCast(Value* that) {
2496 if (IsDeadCheck(i::Isolate::Current(), "v8::Array::Cast()")) return;
2497 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2498 ApiCheck(obj->IsJSArray(),
2499 "v8::Array::Cast()",
2500 "Could not convert to array");
2504 void v8::Date::CheckCast(v8::Value* that) {
2505 i::Isolate* isolate = i::Isolate::Current();
2506 if (IsDeadCheck(isolate, "v8::Date::Cast()")) return;
2507 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2508 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Date_symbol()),
2510 "Could not convert to date");
2514 void v8::StringObject::CheckCast(v8::Value* that) {
2515 i::Isolate* isolate = i::Isolate::Current();
2516 if (IsDeadCheck(isolate, "v8::StringObject::Cast()")) return;
2517 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2518 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->String_symbol()),
2519 "v8::StringObject::Cast()",
2520 "Could not convert to StringObject");
2524 void v8::NumberObject::CheckCast(v8::Value* that) {
2525 i::Isolate* isolate = i::Isolate::Current();
2526 if (IsDeadCheck(isolate, "v8::NumberObject::Cast()")) return;
2527 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2528 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Number_symbol()),
2529 "v8::NumberObject::Cast()",
2530 "Could not convert to NumberObject");
2534 void v8::BooleanObject::CheckCast(v8::Value* that) {
2535 i::Isolate* isolate = i::Isolate::Current();
2536 if (IsDeadCheck(isolate, "v8::BooleanObject::Cast()")) return;
2537 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2538 ApiCheck(obj->HasSpecificClassOf(isolate->heap()->Boolean_symbol()),
2539 "v8::BooleanObject::Cast()",
2540 "Could not convert to BooleanObject");
2544 void v8::RegExp::CheckCast(v8::Value* that) {
2545 if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::Cast()")) return;
2546 i::Handle<i::Object> obj = Utils::OpenHandle(that);
2547 ApiCheck(obj->IsJSRegExp(),
2548 "v8::RegExp::Cast()",
2549 "Could not convert to regular expression");
2553 bool Value::BooleanValue() const {
2554 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2555 if (obj->IsBoolean()) {
2556 return obj->IsTrue();
2558 i::Isolate* isolate = i::Isolate::Current();
2559 if (IsDeadCheck(isolate, "v8::Value::BooleanValue()")) return false;
2560 LOG_API(isolate, "BooleanValue");
2562 i::Handle<i::Object> value = i::Execution::ToBoolean(obj);
2563 return value->IsTrue();
2568 double Value::NumberValue() const {
2569 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2570 i::Handle<i::Object> num;
2571 if (obj->IsNumber()) {
2574 i::Isolate* isolate = i::Isolate::Current();
2575 if (IsDeadCheck(isolate, "v8::Value::NumberValue()")) {
2576 return i::OS::nan_value();
2578 LOG_API(isolate, "NumberValue");
2580 EXCEPTION_PREAMBLE(isolate);
2581 num = i::Execution::ToNumber(obj, &has_pending_exception);
2582 EXCEPTION_BAILOUT_CHECK(isolate, i::OS::nan_value());
2584 return num->Number();
2588 int64_t Value::IntegerValue() const {
2589 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2590 i::Handle<i::Object> num;
2591 if (obj->IsNumber()) {
2594 i::Isolate* isolate = i::Isolate::Current();
2595 if (IsDeadCheck(isolate, "v8::Value::IntegerValue()")) return 0;
2596 LOG_API(isolate, "IntegerValue");
2598 EXCEPTION_PREAMBLE(isolate);
2599 num = i::Execution::ToInteger(obj, &has_pending_exception);
2600 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2603 return i::Smi::cast(*num)->value();
2605 return static_cast<int64_t>(num->Number());
2610 Local<Int32> Value::ToInt32() const {
2611 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2612 i::Handle<i::Object> num;
2616 i::Isolate* isolate = i::Isolate::Current();
2617 if (IsDeadCheck(isolate, "v8::Value::ToInt32()")) return Local<Int32>();
2618 LOG_API(isolate, "ToInt32");
2620 EXCEPTION_PREAMBLE(isolate);
2621 num = i::Execution::ToInt32(obj, &has_pending_exception);
2622 EXCEPTION_BAILOUT_CHECK(isolate, Local<Int32>());
2624 return Local<Int32>(ToApi<Int32>(num));
2628 Local<Uint32> Value::ToUint32() const {
2629 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2630 i::Handle<i::Object> num;
2634 i::Isolate* isolate = i::Isolate::Current();
2635 if (IsDeadCheck(isolate, "v8::Value::ToUint32()")) return Local<Uint32>();
2636 LOG_API(isolate, "ToUInt32");
2638 EXCEPTION_PREAMBLE(isolate);
2639 num = i::Execution::ToUint32(obj, &has_pending_exception);
2640 EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2642 return Local<Uint32>(ToApi<Uint32>(num));
2646 Local<Uint32> Value::ToArrayIndex() const {
2647 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2649 if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
2650 return Local<Uint32>();
2652 i::Isolate* isolate = i::Isolate::Current();
2653 if (IsDeadCheck(isolate, "v8::Value::ToArrayIndex()")) return Local<Uint32>();
2654 LOG_API(isolate, "ToArrayIndex");
2656 EXCEPTION_PREAMBLE(isolate);
2657 i::Handle<i::Object> string_obj =
2658 i::Execution::ToString(obj, &has_pending_exception);
2659 EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
2660 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
2662 if (str->AsArrayIndex(&index)) {
2663 i::Handle<i::Object> value;
2664 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
2665 value = i::Handle<i::Object>(i::Smi::FromInt(index));
2667 value = isolate->factory()->NewNumber(index);
2669 return Utils::Uint32ToLocal(value);
2671 return Local<Uint32>();
2675 int32_t Value::Int32Value() const {
2676 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2678 return i::Smi::cast(*obj)->value();
2680 i::Isolate* isolate = i::Isolate::Current();
2681 if (IsDeadCheck(isolate, "v8::Value::Int32Value()")) return 0;
2682 LOG_API(isolate, "Int32Value (slow)");
2684 EXCEPTION_PREAMBLE(isolate);
2685 i::Handle<i::Object> num =
2686 i::Execution::ToInt32(obj, &has_pending_exception);
2687 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2689 return i::Smi::cast(*num)->value();
2691 return static_cast<int32_t>(num->Number());
2697 bool Value::Equals(Handle<Value> that) const {
2698 i::Isolate* isolate = i::Isolate::Current();
2699 if (IsDeadCheck(isolate, "v8::Value::Equals()")
2700 || EmptyCheck("v8::Value::Equals()", this)
2701 || EmptyCheck("v8::Value::Equals()", that)) {
2704 LOG_API(isolate, "Equals");
2706 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2707 i::Handle<i::Object> other = Utils::OpenHandle(*that);
2708 // If both obj and other are JSObjects, we'd better compare by identity
2709 // immediately when going into JS builtin. The reason is Invoke
2710 // would overwrite global object receiver with global proxy.
2711 if (obj->IsJSObject() && other->IsJSObject()) {
2712 return *obj == *other;
2714 i::Handle<i::Object> args[] = { other };
2715 EXCEPTION_PREAMBLE(isolate);
2716 i::Handle<i::Object> result =
2717 CallV8HeapFunction("EQUALS", obj, ARRAY_SIZE(args), args,
2718 &has_pending_exception);
2719 EXCEPTION_BAILOUT_CHECK(isolate, false);
2720 return *result == i::Smi::FromInt(i::EQUAL);
2724 bool Value::StrictEquals(Handle<Value> that) const {
2725 i::Isolate* isolate = i::Isolate::Current();
2726 if (IsDeadCheck(isolate, "v8::Value::StrictEquals()")
2727 || EmptyCheck("v8::Value::StrictEquals()", this)
2728 || EmptyCheck("v8::Value::StrictEquals()", that)) {
2731 LOG_API(isolate, "StrictEquals");
2732 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2733 i::Handle<i::Object> other = Utils::OpenHandle(*that);
2734 // Must check HeapNumber first, since NaN !== NaN.
2735 if (obj->IsHeapNumber()) {
2736 if (!other->IsNumber()) return false;
2737 double x = obj->Number();
2738 double y = other->Number();
2739 // Must check explicitly for NaN:s on Windows, but -0 works fine.
2740 return x == y && !isnan(x) && !isnan(y);
2741 } else if (*obj == *other) { // Also covers Booleans.
2743 } else if (obj->IsSmi()) {
2744 return other->IsNumber() && obj->Number() == other->Number();
2745 } else if (obj->IsString()) {
2746 return other->IsString() &&
2747 i::String::cast(*obj)->Equals(i::String::cast(*other));
2748 } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
2749 return other->IsUndefined() || other->IsUndetectableObject();
2756 uint32_t Value::Uint32Value() const {
2757 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2759 return i::Smi::cast(*obj)->value();
2761 i::Isolate* isolate = i::Isolate::Current();
2762 if (IsDeadCheck(isolate, "v8::Value::Uint32Value()")) return 0;
2763 LOG_API(isolate, "Uint32Value");
2765 EXCEPTION_PREAMBLE(isolate);
2766 i::Handle<i::Object> num =
2767 i::Execution::ToUint32(obj, &has_pending_exception);
2768 EXCEPTION_BAILOUT_CHECK(isolate, 0);
2770 return i::Smi::cast(*num)->value();
2772 return static_cast<uint32_t>(num->Number());
2778 bool v8::Object::Set(v8::Handle<Value> key, v8::Handle<Value> value,
2779 v8::PropertyAttribute attribs) {
2780 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2781 ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2783 i::HandleScope scope(isolate);
2784 i::Handle<i::Object> self = Utils::OpenHandle(this);
2785 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2786 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2787 EXCEPTION_PREAMBLE(isolate);
2788 i::Handle<i::Object> obj = i::SetProperty(
2792 static_cast<PropertyAttributes>(attribs),
2794 has_pending_exception = obj.is_null();
2795 EXCEPTION_BAILOUT_CHECK(isolate, false);
2800 bool v8::Object::Set(uint32_t index, v8::Handle<Value> value) {
2801 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2802 ON_BAILOUT(isolate, "v8::Object::Set()", return false);
2804 i::HandleScope scope(isolate);
2805 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2806 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2807 EXCEPTION_PREAMBLE(isolate);
2808 i::Handle<i::Object> obj = i::SetElement(
2813 has_pending_exception = obj.is_null();
2814 EXCEPTION_BAILOUT_CHECK(isolate, false);
2819 bool v8::Object::ForceSet(v8::Handle<Value> key,
2820 v8::Handle<Value> value,
2821 v8::PropertyAttribute attribs) {
2822 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2823 ON_BAILOUT(isolate, "v8::Object::ForceSet()", return false);
2825 i::HandleScope scope(isolate);
2826 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2827 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2828 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2829 EXCEPTION_PREAMBLE(isolate);
2830 i::Handle<i::Object> obj = i::ForceSetProperty(
2834 static_cast<PropertyAttributes>(attribs));
2835 has_pending_exception = obj.is_null();
2836 EXCEPTION_BAILOUT_CHECK(isolate, false);
2841 bool v8::Object::ForceDelete(v8::Handle<Value> key) {
2842 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2843 ON_BAILOUT(isolate, "v8::Object::ForceDelete()", return false);
2845 i::HandleScope scope(isolate);
2846 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2847 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2849 // When turning on access checks for a global object deoptimize all functions
2850 // as optimized code does not always handle access checks.
2851 i::Deoptimizer::DeoptimizeGlobalObject(*self);
2853 EXCEPTION_PREAMBLE(isolate);
2854 i::Handle<i::Object> obj = i::ForceDeleteProperty(self, key_obj);
2855 has_pending_exception = obj.is_null();
2856 EXCEPTION_BAILOUT_CHECK(isolate, false);
2857 return obj->IsTrue();
2861 Local<Value> v8::Object::Get(v8::Handle<Value> key) {
2862 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2863 ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2865 i::Handle<i::Object> self = Utils::OpenHandle(this);
2866 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2867 EXCEPTION_PREAMBLE(isolate);
2868 i::Handle<i::Object> result = i::GetProperty(self, key_obj);
2869 has_pending_exception = result.is_null();
2870 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2871 return Utils::ToLocal(result);
2875 Local<Value> v8::Object::Get(uint32_t index) {
2876 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2877 ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
2879 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2880 EXCEPTION_PREAMBLE(isolate);
2881 i::Handle<i::Object> result = i::Object::GetElement(self, index);
2882 has_pending_exception = result.is_null();
2883 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
2884 return Utils::ToLocal(result);
2888 PropertyAttribute v8::Object::GetPropertyAttributes(v8::Handle<Value> key) {
2889 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2890 ON_BAILOUT(isolate, "v8::Object::GetPropertyAttribute()",
2891 return static_cast<PropertyAttribute>(NONE));
2893 i::HandleScope scope(isolate);
2894 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2895 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2896 if (!key_obj->IsString()) {
2897 EXCEPTION_PREAMBLE(isolate);
2898 key_obj = i::Execution::ToString(key_obj, &has_pending_exception);
2899 EXCEPTION_BAILOUT_CHECK(isolate, static_cast<PropertyAttribute>(NONE));
2901 i::Handle<i::String> key_string = i::Handle<i::String>::cast(key_obj);
2902 PropertyAttributes result = self->GetPropertyAttribute(*key_string);
2903 if (result == ABSENT) return static_cast<PropertyAttribute>(NONE);
2904 return static_cast<PropertyAttribute>(result);
2908 Local<Value> v8::Object::GetPrototype() {
2909 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2910 ON_BAILOUT(isolate, "v8::Object::GetPrototype()",
2911 return Local<v8::Value>());
2913 i::Handle<i::Object> self = Utils::OpenHandle(this);
2914 i::Handle<i::Object> result = i::GetPrototype(self);
2915 return Utils::ToLocal(result);
2919 bool v8::Object::SetPrototype(Handle<Value> value) {
2920 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2921 ON_BAILOUT(isolate, "v8::Object::SetPrototype()", return false);
2923 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2924 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2925 // We do not allow exceptions thrown while setting the prototype
2926 // to propagate outside.
2928 EXCEPTION_PREAMBLE(isolate);
2929 i::Handle<i::Object> result = i::SetPrototype(self, value_obj);
2930 has_pending_exception = result.is_null();
2931 EXCEPTION_BAILOUT_CHECK(isolate, false);
2936 Local<Object> v8::Object::FindInstanceInPrototypeChain(
2937 v8::Handle<FunctionTemplate> tmpl) {
2938 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2940 "v8::Object::FindInstanceInPrototypeChain()",
2941 return Local<v8::Object>());
2943 i::JSObject* object = *Utils::OpenHandle(this);
2944 i::FunctionTemplateInfo* tmpl_info = *Utils::OpenHandle(*tmpl);
2945 while (!object->IsInstanceOf(tmpl_info)) {
2946 i::Object* prototype = object->GetPrototype();
2947 if (!prototype->IsJSObject()) return Local<Object>();
2948 object = i::JSObject::cast(prototype);
2950 return Utils::ToLocal(i::Handle<i::JSObject>(object));
2954 Local<Array> v8::Object::GetPropertyNames() {
2955 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2956 ON_BAILOUT(isolate, "v8::Object::GetPropertyNames()",
2957 return Local<v8::Array>());
2959 i::HandleScope scope(isolate);
2960 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2962 i::Handle<i::FixedArray> value =
2963 i::GetKeysInFixedArrayFor(self, i::INCLUDE_PROTOS, &threw);
2964 if (threw) return Local<v8::Array>();
2965 // Because we use caching to speed up enumeration it is important
2966 // to never change the result of the basic enumeration function so
2967 // we clone the result.
2968 i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2969 i::Handle<i::JSArray> result =
2970 isolate->factory()->NewJSArrayWithElements(elms);
2971 return Utils::ToLocal(scope.CloseAndEscape(result));
2975 Local<Array> v8::Object::GetOwnPropertyNames() {
2976 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2977 ON_BAILOUT(isolate, "v8::Object::GetOwnPropertyNames()",
2978 return Local<v8::Array>());
2980 i::HandleScope scope(isolate);
2981 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2983 i::Handle<i::FixedArray> value =
2984 i::GetKeysInFixedArrayFor(self, i::LOCAL_ONLY, &threw);
2985 if (threw) return Local<v8::Array>();
2986 // Because we use caching to speed up enumeration it is important
2987 // to never change the result of the basic enumeration function so
2988 // we clone the result.
2989 i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
2990 i::Handle<i::JSArray> result =
2991 isolate->factory()->NewJSArrayWithElements(elms);
2992 return Utils::ToLocal(scope.CloseAndEscape(result));
2996 Local<String> v8::Object::ObjectProtoToString() {
2997 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
2998 ON_BAILOUT(isolate, "v8::Object::ObjectProtoToString()",
2999 return Local<v8::String>());
3001 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3003 i::Handle<i::Object> name(self->class_name());
3005 // Native implementation of Object.prototype.toString (v8natives.js):
3006 // var c = %ClassOf(this);
3007 // if (c === 'Arguments') c = 'Object';
3008 // return "[object " + c + "]";
3010 if (!name->IsString()) {
3011 return v8::String::New("[object ]");
3014 i::Handle<i::String> class_name = i::Handle<i::String>::cast(name);
3015 if (class_name->IsEqualTo(i::CStrVector("Arguments"))) {
3016 return v8::String::New("[object Object]");
3019 const char* prefix = "[object ";
3020 Local<String> str = Utils::ToLocal(class_name);
3021 const char* postfix = "]";
3023 int prefix_len = i::StrLength(prefix);
3024 int str_len = str->Length();
3025 int postfix_len = i::StrLength(postfix);
3027 int buf_len = prefix_len + str_len + postfix_len;
3028 i::ScopedVector<char> buf(buf_len);
3031 char* ptr = buf.start();
3032 memcpy(ptr, prefix, prefix_len * v8::internal::kCharSize);
3035 // Write real content.
3036 str->WriteAscii(ptr, 0, str_len);
3040 memcpy(ptr, postfix, postfix_len * v8::internal::kCharSize);
3042 // Copy the buffer into a heap-allocated string and return it.
3043 Local<String> result = v8::String::New(buf.start(), buf_len);
3050 Local<String> v8::Object::GetConstructorName() {
3051 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3052 ON_BAILOUT(isolate, "v8::Object::GetConstructorName()",
3053 return Local<v8::String>());
3055 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3056 i::Handle<i::String> name(self->constructor_name());
3057 return Utils::ToLocal(name);
3061 bool v8::Object::Delete(v8::Handle<String> key) {
3062 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3063 ON_BAILOUT(isolate, "v8::Object::Delete()", return false);
3065 i::HandleScope scope(isolate);
3066 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3067 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3068 return i::DeleteProperty(self, key_obj)->IsTrue();
3072 bool v8::Object::Has(v8::Handle<String> key) {
3073 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3074 ON_BAILOUT(isolate, "v8::Object::Has()", return false);
3076 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3077 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3078 return self->HasProperty(*key_obj);
3082 bool v8::Object::Delete(uint32_t index) {
3083 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3084 ON_BAILOUT(isolate, "v8::Object::DeleteProperty()",
3088 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3089 return i::DeleteElement(self, index)->IsTrue();
3093 bool v8::Object::Has(uint32_t index) {
3094 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3095 ON_BAILOUT(isolate, "v8::Object::HasProperty()", return false);
3096 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3097 return self->HasElement(index);
3101 bool Object::SetAccessor(Handle<String> name,
3102 AccessorGetter getter,
3103 AccessorSetter setter,
3104 v8::Handle<Value> data,
3105 AccessControl settings,
3106 PropertyAttribute attributes) {
3107 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3108 ON_BAILOUT(isolate, "v8::Object::SetAccessor()", return false);
3110 i::HandleScope scope(isolate);
3111 i::Handle<i::AccessorInfo> info = MakeAccessorInfo(name,
3112 getter, setter, data,
3113 settings, attributes);
3114 i::Handle<i::Object> result = i::SetAccessor(Utils::OpenHandle(this), info);
3115 return !result.is_null() && !result->IsUndefined();
3119 bool v8::Object::HasOwnProperty(Handle<String> key) {
3120 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3121 ON_BAILOUT(isolate, "v8::Object::HasOwnProperty()",
3123 return Utils::OpenHandle(this)->HasLocalProperty(
3124 *Utils::OpenHandle(*key));
3128 bool v8::Object::HasRealNamedProperty(Handle<String> key) {
3129 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3130 ON_BAILOUT(isolate, "v8::Object::HasRealNamedProperty()",
3132 return Utils::OpenHandle(this)->HasRealNamedProperty(
3133 *Utils::OpenHandle(*key));
3137 bool v8::Object::HasRealIndexedProperty(uint32_t index) {
3138 ON_BAILOUT(Utils::OpenHandle(this)->GetIsolate(),
3139 "v8::Object::HasRealIndexedProperty()",
3141 return Utils::OpenHandle(this)->HasRealElementProperty(index);
3145 bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
3146 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3148 "v8::Object::HasRealNamedCallbackProperty()",
3151 return Utils::OpenHandle(this)->HasRealNamedCallbackProperty(
3152 *Utils::OpenHandle(*key));
3156 bool v8::Object::HasNamedLookupInterceptor() {
3157 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3158 ON_BAILOUT(isolate, "v8::Object::HasNamedLookupInterceptor()",
3160 return Utils::OpenHandle(this)->HasNamedInterceptor();
3164 bool v8::Object::HasIndexedLookupInterceptor() {
3165 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3166 ON_BAILOUT(isolate, "v8::Object::HasIndexedLookupInterceptor()",
3168 return Utils::OpenHandle(this)->HasIndexedInterceptor();
3172 static Local<Value> GetPropertyByLookup(i::Isolate* isolate,
3173 i::Handle<i::JSObject> receiver,
3174 i::Handle<i::String> name,
3175 i::LookupResult* lookup) {
3176 if (!lookup->IsProperty()) {
3177 // No real property was found.
3178 return Local<Value>();
3181 // If the property being looked up is a callback, it can throw
3183 EXCEPTION_PREAMBLE(isolate);
3184 PropertyAttributes ignored;
3185 i::Handle<i::Object> result =
3186 i::Object::GetProperty(receiver, receiver, lookup, name,
3188 has_pending_exception = result.is_null();
3189 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3191 return Utils::ToLocal(result);
3195 Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
3196 Handle<String> key) {
3197 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3199 "v8::Object::GetRealNamedPropertyInPrototypeChain()",
3200 return Local<Value>());
3202 i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3203 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3204 i::LookupResult lookup(isolate);
3205 self_obj->LookupRealNamedPropertyInPrototypes(*key_obj, &lookup);
3206 return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3210 Local<Value> v8::Object::GetRealNamedProperty(Handle<String> key) {
3211 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3212 ON_BAILOUT(isolate, "v8::Object::GetRealNamedProperty()",
3213 return Local<Value>());
3215 i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
3216 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3217 i::LookupResult lookup(isolate);
3218 self_obj->LookupRealNamedProperty(*key_obj, &lookup);
3219 return GetPropertyByLookup(isolate, self_obj, key_obj, &lookup);
3223 // Turns on access checks by copying the map and setting the check flag.
3224 // Because the object gets a new map, existing inline cache caching
3225 // the old map of this object will fail.
3226 void v8::Object::TurnOnAccessCheck() {
3227 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3228 ON_BAILOUT(isolate, "v8::Object::TurnOnAccessCheck()", return);
3230 i::HandleScope scope(isolate);
3231 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3233 // When turning on access checks for a global object deoptimize all functions
3234 // as optimized code does not always handle access checks.
3235 i::Deoptimizer::DeoptimizeGlobalObject(*obj);
3237 i::Handle<i::Map> new_map =
3238 isolate->factory()->CopyMapDropTransitions(i::Handle<i::Map>(obj->map()));
3239 new_map->set_is_access_check_needed(true);
3240 obj->set_map(*new_map);
3244 bool v8::Object::IsDirty() {
3245 return Utils::OpenHandle(this)->IsDirty();
3249 Local<v8::Object> v8::Object::Clone() {
3250 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3251 ON_BAILOUT(isolate, "v8::Object::Clone()", return Local<Object>());
3253 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3254 EXCEPTION_PREAMBLE(isolate);
3255 i::Handle<i::JSObject> result = i::Copy(self);
3256 has_pending_exception = result.is_null();
3257 EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3258 return Utils::ToLocal(result);
3262 static i::Context* GetCreationContext(i::JSObject* object) {
3263 i::Object* constructor = object->map()->constructor();
3264 i::JSFunction* function;
3265 if (!constructor->IsJSFunction()) {
3266 // Functions have null as a constructor,
3267 // but any JSFunction knows its context immediately.
3268 ASSERT(object->IsJSFunction());
3269 function = i::JSFunction::cast(object);
3271 function = i::JSFunction::cast(constructor);
3273 return function->context()->global_context();
3277 Local<v8::Context> v8::Object::CreationContext() {
3278 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3280 "v8::Object::CreationContext()", return Local<v8::Context>());
3282 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3283 i::Context* context = GetCreationContext(*self);
3284 return Utils::ToLocal(i::Handle<i::Context>(context));
3288 int v8::Object::GetIdentityHash() {
3289 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3290 ON_BAILOUT(isolate, "v8::Object::GetIdentityHash()", return 0);
3292 i::HandleScope scope(isolate);
3293 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3294 return i::GetIdentityHash(self);
3298 bool v8::Object::SetHiddenValue(v8::Handle<v8::String> key,
3299 v8::Handle<v8::Value> value) {
3300 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3301 ON_BAILOUT(isolate, "v8::Object::SetHiddenValue()", return false);
3303 i::HandleScope scope(isolate);
3304 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3305 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3306 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
3307 i::Handle<i::Object> result = i::SetHiddenProperty(self, key_obj, value_obj);
3308 return *result == *self;
3312 v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Handle<v8::String> key) {
3313 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3314 ON_BAILOUT(isolate, "v8::Object::GetHiddenValue()",
3315 return Local<v8::Value>());
3317 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3318 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3319 i::Handle<i::Object> result(self->GetHiddenProperty(*key_obj));
3320 if (result->IsUndefined()) return v8::Local<v8::Value>();
3321 return Utils::ToLocal(result);
3325 bool v8::Object::DeleteHiddenValue(v8::Handle<v8::String> key) {
3326 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3327 ON_BAILOUT(isolate, "v8::DeleteHiddenValue()", return false);
3329 i::HandleScope scope(isolate);
3330 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3331 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
3332 self->DeleteHiddenProperty(*key_obj);
3339 static i::ElementsKind GetElementsKindFromExternalArrayType(
3340 ExternalArrayType array_type) {
3341 switch (array_type) {
3342 case kExternalByteArray:
3343 return i::EXTERNAL_BYTE_ELEMENTS;
3345 case kExternalUnsignedByteArray:
3346 return i::EXTERNAL_UNSIGNED_BYTE_ELEMENTS;
3348 case kExternalShortArray:
3349 return i::EXTERNAL_SHORT_ELEMENTS;
3351 case kExternalUnsignedShortArray:
3352 return i::EXTERNAL_UNSIGNED_SHORT_ELEMENTS;
3354 case kExternalIntArray:
3355 return i::EXTERNAL_INT_ELEMENTS;
3357 case kExternalUnsignedIntArray:
3358 return i::EXTERNAL_UNSIGNED_INT_ELEMENTS;
3360 case kExternalFloatArray:
3361 return i::EXTERNAL_FLOAT_ELEMENTS;
3363 case kExternalDoubleArray:
3364 return i::EXTERNAL_DOUBLE_ELEMENTS;
3366 case kExternalPixelArray:
3367 return i::EXTERNAL_PIXEL_ELEMENTS;
3371 return i::DICTIONARY_ELEMENTS;
3375 void PrepareExternalArrayElements(i::Handle<i::JSObject> object,
3377 ExternalArrayType array_type,
3379 i::Isolate* isolate = object->GetIsolate();
3380 i::Handle<i::ExternalArray> array =
3381 isolate->factory()->NewExternalArray(length, array_type, data);
3383 i::Handle<i::Map> external_array_map =
3384 isolate->factory()->GetElementsTransitionMap(
3386 GetElementsKindFromExternalArrayType(array_type));
3388 object->set_map(*external_array_map);
3389 object->set_elements(*array);
3395 void v8::Object::SetIndexedPropertiesToPixelData(uint8_t* data, int length) {
3396 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3397 ON_BAILOUT(isolate, "v8::SetElementsToPixelData()", return);
3399 i::HandleScope scope(isolate);
3400 if (!ApiCheck(length <= i::ExternalPixelArray::kMaxLength,
3401 "v8::Object::SetIndexedPropertiesToPixelData()",
3402 "length exceeds max acceptable value")) {
3405 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3406 if (!ApiCheck(!self->IsJSArray(),
3407 "v8::Object::SetIndexedPropertiesToPixelData()",
3408 "JSArray is not supported")) {
3411 PrepareExternalArrayElements(self, data, kExternalPixelArray, length);
3415 bool v8::Object::HasIndexedPropertiesInPixelData() {
3416 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3417 ON_BAILOUT(self->GetIsolate(), "v8::HasIndexedPropertiesInPixelData()",
3419 return self->HasExternalPixelElements();
3423 uint8_t* v8::Object::GetIndexedPropertiesPixelData() {
3424 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3425 ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelData()",
3427 if (self->HasExternalPixelElements()) {
3428 return i::ExternalPixelArray::cast(self->elements())->
3429 external_pixel_pointer();
3436 int v8::Object::GetIndexedPropertiesPixelDataLength() {
3437 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3438 ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelDataLength()",
3440 if (self->HasExternalPixelElements()) {
3441 return i::ExternalPixelArray::cast(self->elements())->length();
3448 void v8::Object::SetIndexedPropertiesToExternalArrayData(
3450 ExternalArrayType array_type,
3452 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3453 ON_BAILOUT(isolate, "v8::SetIndexedPropertiesToExternalArrayData()", return);
3455 i::HandleScope scope(isolate);
3456 if (!ApiCheck(length <= i::ExternalArray::kMaxLength,
3457 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3458 "length exceeds max acceptable value")) {
3461 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3462 if (!ApiCheck(!self->IsJSArray(),
3463 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
3464 "JSArray is not supported")) {
3467 PrepareExternalArrayElements(self, data, array_type, length);
3471 bool v8::Object::HasIndexedPropertiesInExternalArrayData() {
3472 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3473 ON_BAILOUT(self->GetIsolate(),
3474 "v8::HasIndexedPropertiesInExternalArrayData()",
3476 return self->HasExternalArrayElements();
3480 void* v8::Object::GetIndexedPropertiesExternalArrayData() {
3481 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3482 ON_BAILOUT(self->GetIsolate(),
3483 "v8::GetIndexedPropertiesExternalArrayData()",
3485 if (self->HasExternalArrayElements()) {
3486 return i::ExternalArray::cast(self->elements())->external_pointer();
3493 ExternalArrayType v8::Object::GetIndexedPropertiesExternalArrayDataType() {
3494 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3495 ON_BAILOUT(self->GetIsolate(),
3496 "v8::GetIndexedPropertiesExternalArrayDataType()",
3497 return static_cast<ExternalArrayType>(-1));
3498 switch (self->elements()->map()->instance_type()) {
3499 case i::EXTERNAL_BYTE_ARRAY_TYPE:
3500 return kExternalByteArray;
3501 case i::EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
3502 return kExternalUnsignedByteArray;
3503 case i::EXTERNAL_SHORT_ARRAY_TYPE:
3504 return kExternalShortArray;
3505 case i::EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
3506 return kExternalUnsignedShortArray;
3507 case i::EXTERNAL_INT_ARRAY_TYPE:
3508 return kExternalIntArray;
3509 case i::EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
3510 return kExternalUnsignedIntArray;
3511 case i::EXTERNAL_FLOAT_ARRAY_TYPE:
3512 return kExternalFloatArray;
3513 case i::EXTERNAL_DOUBLE_ARRAY_TYPE:
3514 return kExternalDoubleArray;
3515 case i::EXTERNAL_PIXEL_ARRAY_TYPE:
3516 return kExternalPixelArray;
3518 return static_cast<ExternalArrayType>(-1);
3523 int v8::Object::GetIndexedPropertiesExternalArrayDataLength() {
3524 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3525 ON_BAILOUT(self->GetIsolate(),
3526 "v8::GetIndexedPropertiesExternalArrayDataLength()",
3528 if (self->HasExternalArrayElements()) {
3529 return i::ExternalArray::cast(self->elements())->length();
3536 bool v8::Object::IsCallable() {
3537 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3538 ON_BAILOUT(isolate, "v8::Object::IsCallable()", return false);
3540 i::HandleScope scope(isolate);
3541 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3542 if (obj->IsJSFunction()) return true;
3543 return i::Execution::GetFunctionDelegate(obj)->IsJSFunction();
3547 Local<v8::Value> Object::CallAsFunction(v8::Handle<v8::Object> recv,
3549 v8::Handle<v8::Value> argv[]) {
3550 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3551 ON_BAILOUT(isolate, "v8::Object::CallAsFunction()",
3552 return Local<v8::Value>());
3553 LOG_API(isolate, "Object::CallAsFunction");
3555 i::HandleScope scope(isolate);
3556 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3557 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3558 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3559 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3560 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>();
3561 if (obj->IsJSFunction()) {
3562 fun = i::Handle<i::JSFunction>::cast(obj);
3564 EXCEPTION_PREAMBLE(isolate);
3565 i::Handle<i::Object> delegate =
3566 i::Execution::TryGetFunctionDelegate(obj, &has_pending_exception);
3567 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3568 fun = i::Handle<i::JSFunction>::cast(delegate);
3571 EXCEPTION_PREAMBLE(isolate);
3572 i::Handle<i::Object> returned =
3573 i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3574 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
3575 return Utils::ToLocal(scope.CloseAndEscape(returned));
3579 Local<v8::Value> Object::CallAsConstructor(int argc,
3580 v8::Handle<v8::Value> argv[]) {
3581 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3582 ON_BAILOUT(isolate, "v8::Object::CallAsConstructor()",
3583 return Local<v8::Object>());
3584 LOG_API(isolate, "Object::CallAsConstructor");
3586 i::HandleScope scope(isolate);
3587 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
3588 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3589 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3590 if (obj->IsJSFunction()) {
3591 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(obj);
3592 EXCEPTION_PREAMBLE(isolate);
3593 i::Handle<i::Object> returned =
3594 i::Execution::New(fun, argc, args, &has_pending_exception);
3595 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3596 return Utils::ToLocal(scope.CloseAndEscape(
3597 i::Handle<i::JSObject>::cast(returned)));
3599 EXCEPTION_PREAMBLE(isolate);
3600 i::Handle<i::Object> delegate =
3601 i::Execution::TryGetConstructorDelegate(obj, &has_pending_exception);
3602 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3603 if (!delegate->IsUndefined()) {
3604 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(delegate);
3605 EXCEPTION_PREAMBLE(isolate);
3606 i::Handle<i::Object> returned =
3607 i::Execution::Call(fun, obj, argc, args, &has_pending_exception);
3608 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3609 ASSERT(!delegate->IsUndefined());
3610 return Utils::ToLocal(scope.CloseAndEscape(returned));
3612 return Local<v8::Object>();
3616 Local<v8::Object> Function::NewInstance() const {
3617 return NewInstance(0, NULL);
3621 Local<v8::Object> Function::NewInstance(int argc,
3622 v8::Handle<v8::Value> argv[]) const {
3623 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3624 ON_BAILOUT(isolate, "v8::Function::NewInstance()",
3625 return Local<v8::Object>());
3626 LOG_API(isolate, "Function::NewInstance");
3629 i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
3630 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3631 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3632 EXCEPTION_PREAMBLE(isolate);
3633 i::Handle<i::Object> returned =
3634 i::Execution::New(function, argc, args, &has_pending_exception);
3635 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
3636 return scope.Close(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
3640 Local<v8::Value> Function::Call(v8::Handle<v8::Object> recv, int argc,
3641 v8::Handle<v8::Value> argv[]) {
3642 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3643 ON_BAILOUT(isolate, "v8::Function::Call()", return Local<v8::Value>());
3644 LOG_API(isolate, "Function::Call");
3646 i::Object* raw_result = NULL;
3648 i::HandleScope scope(isolate);
3649 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
3650 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
3651 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
3652 i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
3653 EXCEPTION_PREAMBLE(isolate);
3654 i::Handle<i::Object> returned =
3655 i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
3656 EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
3657 raw_result = *returned;
3659 i::Handle<i::Object> result(raw_result);
3660 return Utils::ToLocal(result);
3664 void Function::SetName(v8::Handle<v8::String> name) {
3665 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3668 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3669 func->shared()->set_name(*Utils::OpenHandle(*name));
3673 Handle<Value> Function::GetName() const {
3674 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3675 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name()));
3679 ScriptOrigin Function::GetScriptOrigin() const {
3680 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3681 if (func->shared()->script()->IsScript()) {
3682 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
3683 v8::ScriptOrigin origin(
3684 Utils::ToLocal(i::Handle<i::Object>(script->name())),
3685 v8::Integer::New(script->line_offset()->value()),
3686 v8::Integer::New(script->column_offset()->value()));
3689 return v8::ScriptOrigin(Handle<Value>());
3693 const int Function::kLineOffsetNotFound = -1;
3696 int Function::GetScriptLineNumber() const {
3697 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
3698 if (func->shared()->script()->IsScript()) {
3699 i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
3700 return i::GetScriptLineNumber(script, func->shared()->start_position());
3702 return kLineOffsetNotFound;
3706 int String::Length() const {
3707 i::Handle<i::String> str = Utils::OpenHandle(this);
3708 if (IsDeadCheck(str->GetIsolate(), "v8::String::Length()")) return 0;
3709 return str->length();
3713 int String::Utf8Length() const {
3714 i::Handle<i::String> str = Utils::OpenHandle(this);
3715 if (IsDeadCheck(str->GetIsolate(), "v8::String::Utf8Length()")) return 0;
3716 return str->Utf8Length();
3720 uint32_t String::Hash() const {
3721 i::Handle<i::String> str = Utils::OpenHandle(this);
3722 if (IsDeadCheck(str->GetIsolate(), "v8::String::Hash()")) return 0;
3727 String::CompleteHashData String::CompleteHash() const {
3728 i::Handle<i::String> str = Utils::OpenHandle(this);
3729 if (IsDeadCheck(str->GetIsolate(), "v8::String::CompleteHash()")) return CompleteHashData();
3730 CompleteHashData result;
3731 result.length = str->length();
3732 result.hash = str->Hash();
3733 if (str->IsSeqString())
3734 result.symbol_id = i::SeqString::cast(*str)->symbol_id();
3739 uint32_t String::ComputeHash(uint16_t *string, int length) {
3740 return i::HashSequentialString<i::uc16>(string, length) >> i::String::kHashShift;
3744 uint32_t String::ComputeHash(char *string, int length) {
3745 return i::HashSequentialString<char>(string, length) >> i::String::kHashShift;
3749 uint16_t String::GetCharacter(int index)
3751 i::Handle<i::String> str = Utils::OpenHandle(this);
3752 return str->Get(index);
3756 bool String::Equals(uint16_t *string, int length) {
3757 i::Handle<i::String> str = Utils::OpenHandle(this);
3758 if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3759 return str->SlowEqualsExternal(string, length);
3763 bool String::Equals(char *string, int length)
3765 i::Handle<i::String> str = Utils::OpenHandle(this);
3766 if (IsDeadCheck(str->GetIsolate(), "v8::String::Equals()")) return 0;
3767 return str->SlowEqualsExternal(string, length);
3771 int String::WriteUtf8(char* buffer,
3774 int options) const {
3775 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3776 if (IsDeadCheck(isolate, "v8::String::WriteUtf8()")) return 0;
3777 LOG_API(isolate, "String::WriteUtf8");
3779 i::Handle<i::String> str = Utils::OpenHandle(this);
3780 if (str->IsAsciiRepresentation()) {
3782 if (capacity == -1) {
3783 capacity = str->length() + 1;
3784 len = str->length();
3786 len = i::Min(capacity, str->length());
3788 i::String::WriteToFlat(*str, buffer, 0, len);
3789 if (nchars_ref != NULL) *nchars_ref = len;
3790 if (!(options & NO_NULL_TERMINATION) && capacity > len) {
3797 i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3798 isolate->string_tracker()->RecordWrite(str);
3799 if (options & HINT_MANY_WRITES_EXPECTED) {
3800 // Flatten the string for efficiency. This applies whether we are
3801 // using StringInputBuffer or Get(i) to access the characters.
3804 write_input_buffer.Reset(0, *str);
3805 int len = str->length();
3806 // Encode the first K - 3 bytes directly into the buffer since we
3807 // know there's room for them. If no capacity is given we copy all
3809 int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
3813 for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
3814 i::uc32 c = write_input_buffer.GetNext();
3815 int written = unibrow::Utf8::Encode(buffer + pos, c);
3820 // For the last characters we need to check the length for each one
3821 // because they may be longer than the remaining space in the
3823 char intermediate[unibrow::Utf8::kMaxEncodedSize];
3824 for (; i < len && pos < capacity; i++) {
3825 i::uc32 c = write_input_buffer.GetNext();
3826 int written = unibrow::Utf8::Encode(intermediate, c);
3827 if (pos + written <= capacity) {
3828 for (int j = 0; j < written; j++)
3829 buffer[pos + j] = intermediate[j];
3833 // We've reached the end of the buffer
3838 if (nchars_ref != NULL) *nchars_ref = nchars;
3839 if (!(options & NO_NULL_TERMINATION) &&
3840 (i == len && (capacity == -1 || pos < capacity)))
3841 buffer[pos++] = '\0';
3846 int String::WriteAscii(char* buffer,
3849 int options) const {
3850 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3851 if (IsDeadCheck(isolate, "v8::String::WriteAscii()")) return 0;
3852 LOG_API(isolate, "String::WriteAscii");
3854 i::StringInputBuffer& write_input_buffer = *isolate->write_input_buffer();
3855 ASSERT(start >= 0 && length >= -1);
3856 i::Handle<i::String> str = Utils::OpenHandle(this);
3857 isolate->string_tracker()->RecordWrite(str);
3858 if (options & HINT_MANY_WRITES_EXPECTED) {
3859 // Flatten the string for efficiency. This applies whether we are
3860 // using StringInputBuffer or Get(i) to access the characters.
3864 if ( (length == -1) || (length > str->length() - start) )
3865 end = str->length() - start;
3866 if (end < 0) return 0;
3867 write_input_buffer.Reset(start, *str);
3869 for (i = 0; i < end; i++) {
3870 char c = static_cast<char>(write_input_buffer.GetNext());
3871 if (c == '\0') c = ' ';
3874 if (!(options & NO_NULL_TERMINATION) && (length == -1 || i < length))
3880 int String::Write(uint16_t* buffer,
3883 int options) const {
3884 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
3885 if (IsDeadCheck(isolate, "v8::String::Write()")) return 0;
3886 LOG_API(isolate, "String::Write");
3888 ASSERT(start >= 0 && length >= -1);
3889 i::Handle<i::String> str = Utils::OpenHandle(this);
3890 isolate->string_tracker()->RecordWrite(str);
3891 if (options & HINT_MANY_WRITES_EXPECTED) {
3892 // Flatten the string for efficiency. This applies whether we are
3893 // using StringInputBuffer or Get(i) to access the characters.
3896 int end = start + length;
3897 if ((length == -1) || (length > str->length() - start) )
3898 end = str->length();
3899 if (end < 0) return 0;
3900 i::String::WriteToFlat(*str, buffer, start, end);
3901 if (!(options & NO_NULL_TERMINATION) &&
3902 (length == -1 || end - start < length)) {
3903 buffer[end - start] = '\0';
3909 bool v8::String::IsExternal() const {
3910 i::Handle<i::String> str = Utils::OpenHandle(this);
3911 if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternal()")) {
3914 EnsureInitializedForIsolate(str->GetIsolate(), "v8::String::IsExternal()");
3915 return i::StringShape(*str).IsExternalTwoByte();
3919 bool v8::String::IsExternalAscii() const {
3920 i::Handle<i::String> str = Utils::OpenHandle(this);
3921 if (IsDeadCheck(str->GetIsolate(), "v8::String::IsExternalAscii()")) {
3924 return i::StringShape(*str).IsExternalAscii();
3928 void v8::String::VerifyExternalStringResource(
3929 v8::String::ExternalStringResource* value) const {
3930 i::Handle<i::String> str = Utils::OpenHandle(this);
3931 const v8::String::ExternalStringResource* expected;
3932 if (i::StringShape(*str).IsExternalTwoByte()) {
3933 const void* resource =
3934 i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
3935 expected = reinterpret_cast<const ExternalStringResource*>(resource);
3939 CHECK_EQ(expected, value);
3943 const v8::String::ExternalAsciiStringResource*
3944 v8::String::GetExternalAsciiStringResource() const {
3945 i::Handle<i::String> str = Utils::OpenHandle(this);
3946 if (IsDeadCheck(str->GetIsolate(),
3947 "v8::String::GetExternalAsciiStringResource()")) {
3950 if (i::StringShape(*str).IsExternalAscii()) {
3951 const void* resource =
3952 i::Handle<i::ExternalAsciiString>::cast(str)->resource();
3953 return reinterpret_cast<const ExternalAsciiStringResource*>(resource);
3960 double Number::Value() const {
3961 if (IsDeadCheck(i::Isolate::Current(), "v8::Number::Value()")) return 0;
3962 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3963 return obj->Number();
3967 bool Boolean::Value() const {
3968 if (IsDeadCheck(i::Isolate::Current(), "v8::Boolean::Value()")) return false;
3969 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3970 return obj->IsTrue();
3974 int64_t Integer::Value() const {
3975 if (IsDeadCheck(i::Isolate::Current(), "v8::Integer::Value()")) return 0;
3976 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3978 return i::Smi::cast(*obj)->value();
3980 return static_cast<int64_t>(obj->Number());
3985 int32_t Int32::Value() const {
3986 if (IsDeadCheck(i::Isolate::Current(), "v8::Int32::Value()")) return 0;
3987 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3989 return i::Smi::cast(*obj)->value();
3991 return static_cast<int32_t>(obj->Number());
3996 uint32_t Uint32::Value() const {
3997 if (IsDeadCheck(i::Isolate::Current(), "v8::Uint32::Value()")) return 0;
3998 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4000 return i::Smi::cast(*obj)->value();
4002 return static_cast<uint32_t>(obj->Number());
4007 int v8::Object::InternalFieldCount() {
4008 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4009 if (IsDeadCheck(obj->GetIsolate(), "v8::Object::InternalFieldCount()")) {
4012 return obj->GetInternalFieldCount();
4016 Local<Value> v8::Object::CheckedGetInternalField(int index) {
4017 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4018 if (IsDeadCheck(obj->GetIsolate(), "v8::Object::GetInternalField()")) {
4019 return Local<Value>();
4021 if (!ApiCheck(index < obj->GetInternalFieldCount(),
4022 "v8::Object::GetInternalField()",
4023 "Reading internal field out of bounds")) {
4024 return Local<Value>();
4026 i::Handle<i::Object> value(obj->GetInternalField(index));
4027 Local<Value> result = Utils::ToLocal(value);
4029 Local<Value> unchecked = UncheckedGetInternalField(index);
4030 ASSERT(unchecked.IsEmpty() || (unchecked == result));
4036 void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
4037 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4038 i::Isolate* isolate = obj->GetIsolate();
4039 if (IsDeadCheck(isolate, "v8::Object::SetInternalField()")) {
4042 if (!ApiCheck(index < obj->GetInternalFieldCount(),
4043 "v8::Object::SetInternalField()",
4044 "Writing internal field out of bounds")) {
4048 i::Handle<i::Object> val = Utils::OpenHandle(*value);
4049 obj->SetInternalField(index, *val);
4053 static bool CanBeEncodedAsSmi(void* ptr) {
4054 const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4055 return ((address & i::kEncodablePointerMask) == 0);
4059 static i::Smi* EncodeAsSmi(void* ptr) {
4060 ASSERT(CanBeEncodedAsSmi(ptr));
4061 const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
4062 i::Smi* result = reinterpret_cast<i::Smi*>(address << i::kPointerToSmiShift);
4063 ASSERT(i::Internals::HasSmiTag(result));
4064 ASSERT_EQ(result, i::Smi::FromInt(result->value()));
4065 ASSERT_EQ(ptr, i::Internals::GetExternalPointerFromSmi(result));
4070 void v8::Object::SetPointerInInternalField(int index, void* value) {
4071 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4073 if (CanBeEncodedAsSmi(value)) {
4074 Utils::OpenHandle(this)->SetInternalField(index, EncodeAsSmi(value));
4077 i::Handle<i::Foreign> foreign =
4078 isolate->factory()->NewForeign(
4079 reinterpret_cast<i::Address>(value), i::TENURED);
4080 if (!foreign.is_null())
4081 Utils::OpenHandle(this)->SetInternalField(index, *foreign);
4083 ASSERT_EQ(value, GetPointerFromInternalField(index));
4087 void v8::Object::SetExternalResource(v8::Object::ExternalResource *resource) {
4088 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4090 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4091 if (CanBeEncodedAsSmi(resource)) {
4092 obj->SetExternalResourceObject(EncodeAsSmi(resource));
4094 obj->SetExternalResourceObject(*isolate->factory()->NewForeign(static_cast<i::Address>((void *)resource)));
4096 if (!obj->IsSymbol()) {
4097 isolate->heap()->external_string_table()->AddObject(*obj);
4102 v8::Object::ExternalResource *v8::Object::GetExternalResource() {
4103 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4104 i::Object* value = obj->GetExternalResourceObject();
4105 if (value->IsSmi()) {
4106 return reinterpret_cast<v8::Object::ExternalResource*>(i::Internals::GetExternalPointerFromSmi(value));
4107 } else if (value->IsForeign()) {
4108 return reinterpret_cast<v8::Object::ExternalResource*>(i::Foreign::cast(value)->address());
4115 // --- E n v i r o n m e n t ---
4118 bool v8::V8::Initialize() {
4119 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
4120 if (isolate != NULL && isolate->IsInitialized()) {
4123 return InitializeHelper();
4127 void v8::V8::SetEntropySource(EntropySource source) {
4128 i::V8::SetEntropySource(source);
4132 bool v8::V8::Dispose() {
4133 i::Isolate* isolate = i::Isolate::Current();
4134 if (!ApiCheck(isolate != NULL && isolate->IsDefaultIsolate(),
4135 "v8::V8::Dispose()",
4136 "Use v8::Isolate::Dispose() for a non-default isolate.")) {
4144 HeapStatistics::HeapStatistics(): total_heap_size_(0),
4145 total_heap_size_executable_(0),
4147 heap_size_limit_(0) { }
4150 void v8::V8::GetHeapStatistics(HeapStatistics* heap_statistics) {
4151 if (!i::Isolate::Current()->IsInitialized()) {
4152 // Isolate is unitialized thus heap is not configured yet.
4153 heap_statistics->set_total_heap_size(0);
4154 heap_statistics->set_total_heap_size_executable(0);
4155 heap_statistics->set_used_heap_size(0);
4156 heap_statistics->set_heap_size_limit(0);
4160 i::Heap* heap = i::Isolate::Current()->heap();
4161 heap_statistics->set_total_heap_size(heap->CommittedMemory());
4162 heap_statistics->set_total_heap_size_executable(
4163 heap->CommittedMemoryExecutable());
4164 heap_statistics->set_used_heap_size(heap->SizeOfObjects());
4165 heap_statistics->set_heap_size_limit(heap->MaxReserved());
4169 bool v8::V8::IdleNotification() {
4170 // Returning true tells the caller that it need not
4171 // continue to call IdleNotification.
4172 i::Isolate* isolate = i::Isolate::Current();
4173 if (isolate == NULL || !isolate->IsInitialized()) return true;
4174 return i::V8::IdleNotification();
4178 void v8::V8::LowMemoryNotification() {
4179 i::Isolate* isolate = i::Isolate::Current();
4180 if (isolate == NULL || !isolate->IsInitialized()) return;
4181 isolate->heap()->CollectAllAvailableGarbage();
4185 int v8::V8::ContextDisposedNotification() {
4186 i::Isolate* isolate = i::Isolate::Current();
4187 if (!isolate->IsInitialized()) return 0;
4188 return isolate->heap()->NotifyContextDisposed();
4192 const char* v8::V8::GetVersion() {
4193 return i::Version::GetVersion();
4197 static i::Handle<i::FunctionTemplateInfo>
4198 EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
4199 if (templ->constructor()->IsUndefined()) {
4200 Local<FunctionTemplate> constructor = FunctionTemplate::New();
4201 Utils::OpenHandle(*constructor)->set_instance_template(*templ);
4202 templ->set_constructor(*Utils::OpenHandle(*constructor));
4204 return i::Handle<i::FunctionTemplateInfo>(
4205 i::FunctionTemplateInfo::cast(templ->constructor()));
4209 Persistent<Context> v8::Context::New(
4210 v8::ExtensionConfiguration* extensions,
4211 v8::Handle<ObjectTemplate> global_template,
4212 v8::Handle<Value> global_object) {
4213 i::Isolate* isolate = i::Isolate::Current();
4214 EnsureInitializedForIsolate(isolate, "v8::Context::New()");
4215 LOG_API(isolate, "Context::New");
4216 ON_BAILOUT(isolate, "v8::Context::New()", return Persistent<Context>());
4218 // Enter V8 via an ENTER_V8 scope.
4219 i::Handle<i::Context> env;
4222 v8::Handle<ObjectTemplate> proxy_template = global_template;
4223 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
4224 i::Handle<i::FunctionTemplateInfo> global_constructor;
4226 if (!global_template.IsEmpty()) {
4227 // Make sure that the global_template has a constructor.
4228 global_constructor =
4229 EnsureConstructor(Utils::OpenHandle(*global_template));
4231 // Create a fresh template for the global proxy object.
4232 proxy_template = ObjectTemplate::New();
4234 EnsureConstructor(Utils::OpenHandle(*proxy_template));
4236 // Set the global template to be the prototype template of
4237 // global proxy template.
4238 proxy_constructor->set_prototype_template(
4239 *Utils::OpenHandle(*global_template));
4241 // Migrate security handlers from global_template to
4242 // proxy_template. Temporarily removing access check
4243 // information from the global template.
4244 if (!global_constructor->access_check_info()->IsUndefined()) {
4245 proxy_constructor->set_access_check_info(
4246 global_constructor->access_check_info());
4247 proxy_constructor->set_needs_access_check(
4248 global_constructor->needs_access_check());
4249 global_constructor->set_needs_access_check(false);
4250 global_constructor->set_access_check_info(
4251 isolate->heap()->undefined_value());
4255 // Create the environment.
4256 env = isolate->bootstrapper()->CreateEnvironment(
4258 Utils::OpenHandle(*global_object),
4262 // Restore the access check info on the global template.
4263 if (!global_template.IsEmpty()) {
4264 ASSERT(!global_constructor.is_null());
4265 ASSERT(!proxy_constructor.is_null());
4266 global_constructor->set_access_check_info(
4267 proxy_constructor->access_check_info());
4268 global_constructor->set_needs_access_check(
4269 proxy_constructor->needs_access_check());
4271 isolate->runtime_profiler()->Reset();
4275 if (env.is_null()) {
4276 return Persistent<Context>();
4278 return Persistent<Context>(Utils::ToLocal(env));
4282 void v8::Context::SetSecurityToken(Handle<Value> token) {
4283 i::Isolate* isolate = i::Isolate::Current();
4284 if (IsDeadCheck(isolate, "v8::Context::SetSecurityToken()")) {
4288 i::Handle<i::Context> env = Utils::OpenHandle(this);
4289 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
4290 env->set_security_token(*token_handle);
4294 void v8::Context::UseDefaultSecurityToken() {
4295 i::Isolate* isolate = i::Isolate::Current();
4296 if (IsDeadCheck(isolate,
4297 "v8::Context::UseDefaultSecurityToken()")) {
4301 i::Handle<i::Context> env = Utils::OpenHandle(this);
4302 env->set_security_token(env->global());
4306 Handle<Value> v8::Context::GetSecurityToken() {
4307 i::Isolate* isolate = i::Isolate::Current();
4308 if (IsDeadCheck(isolate, "v8::Context::GetSecurityToken()")) {
4309 return Handle<Value>();
4311 i::Handle<i::Context> env = Utils::OpenHandle(this);
4312 i::Object* security_token = env->security_token();
4313 i::Handle<i::Object> token_handle(security_token);
4314 return Utils::ToLocal(token_handle);
4318 bool Context::HasOutOfMemoryException() {
4319 i::Handle<i::Context> env = Utils::OpenHandle(this);
4320 return env->has_out_of_memory();
4324 bool Context::InContext() {
4325 return i::Isolate::Current()->context() != NULL;
4329 v8::Local<v8::Context> Context::GetEntered() {
4330 i::Isolate* isolate = i::Isolate::Current();
4331 if (!EnsureInitializedForIsolate(isolate, "v8::Context::GetEntered()")) {
4332 return Local<Context>();
4334 i::Handle<i::Object> last =
4335 isolate->handle_scope_implementer()->LastEnteredContext();
4336 if (last.is_null()) return Local<Context>();
4337 i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
4338 return Utils::ToLocal(context);
4342 v8::Local<v8::Context> Context::GetCurrent() {
4343 i::Isolate* isolate = i::Isolate::Current();
4344 if (IsDeadCheck(isolate, "v8::Context::GetCurrent()")) {
4345 return Local<Context>();
4347 i::Handle<i::Object> current = isolate->global_context();
4348 if (current.is_null()) return Local<Context>();
4349 i::Handle<i::Context> context = i::Handle<i::Context>::cast(current);
4350 return Utils::ToLocal(context);
4354 v8::Local<v8::Context> Context::GetCalling() {
4355 i::Isolate* isolate = i::Isolate::Current();
4356 if (IsDeadCheck(isolate, "v8::Context::GetCalling()")) {
4357 return Local<Context>();
4359 i::Handle<i::Object> calling =
4360 isolate->GetCallingGlobalContext();
4361 if (calling.is_null()) return Local<Context>();
4362 i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
4363 return Utils::ToLocal(context);
4367 v8::Local<v8::Object> Context::GetCallingQmlGlobal() {
4368 i::Isolate* isolate = i::Isolate::Current();
4369 if (IsDeadCheck(isolate, "v8::Context::GetCallingQmlGlobal()")) {
4370 return Local<Object>();
4373 i::Context *context = isolate->context();
4374 if (!context->qml_global()->IsUndefined()) {
4375 i::Handle<i::Object> qmlglobal(context->qml_global());
4376 return Utils::ToLocal(i::Handle<i::JSObject>::cast(qmlglobal));
4379 i::JavaScriptFrameIterator it;
4380 if (it.done()) return Local<Object>();
4381 context = i::Context::cast(it.frame()->context());
4382 if (!context->qml_global()->IsUndefined()) {
4383 i::Handle<i::Object> qmlglobal(context->qml_global());
4384 return Utils::ToLocal(i::Handle<i::JSObject>::cast(qmlglobal));
4386 return Local<Object>();
4390 v8::Local<v8::Value> Context::GetCallingScriptData()
4392 i::Isolate* isolate = i::Isolate::Current();
4393 if (IsDeadCheck(isolate, "v8::Context::GetCallingScriptData()")) {
4394 return Local<Object>();
4397 i::JavaScriptFrameIterator it;
4398 if (it.done()) return Local<Object>();
4399 i::Handle<i::Script> script(i::Script::cast(i::JSFunction::cast(it.frame()->function())->shared()->script()));
4400 return Utils::ToLocal(i::Handle<i::Object>(script->data()));
4403 v8::Local<v8::Object> Context::Global() {
4404 if (IsDeadCheck(i::Isolate::Current(), "v8::Context::Global()")) {
4405 return Local<v8::Object>();
4407 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4408 i::Handle<i::Context> context =
4409 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4410 i::Handle<i::Object> global(context->global_proxy());
4411 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
4415 void Context::DetachGlobal() {
4416 i::Isolate* isolate = i::Isolate::Current();
4417 if (IsDeadCheck(isolate, "v8::Context::DetachGlobal()")) return;
4419 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4420 i::Handle<i::Context> context =
4421 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4422 isolate->bootstrapper()->DetachGlobal(context);
4426 void Context::ReattachGlobal(Handle<Object> global_object) {
4427 i::Isolate* isolate = i::Isolate::Current();
4428 if (IsDeadCheck(isolate, "v8::Context::ReattachGlobal()")) return;
4430 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4431 i::Handle<i::Context> context =
4432 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4433 isolate->bootstrapper()->ReattachGlobal(
4435 Utils::OpenHandle(*global_object));
4439 void Context::AllowCodeGenerationFromStrings(bool allow) {
4440 i::Isolate* isolate = i::Isolate::Current();
4441 if (IsDeadCheck(isolate, "v8::Context::AllowCodeGenerationFromStrings()")) {
4445 i::Object** ctx = reinterpret_cast<i::Object**>(this);
4446 i::Handle<i::Context> context =
4447 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
4448 context->set_allow_code_gen_from_strings(
4449 allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
4453 void V8::SetWrapperClassId(i::Object** global_handle, uint16_t class_id) {
4454 i::GlobalHandles::SetWrapperClassId(global_handle, class_id);
4458 Local<v8::Object> ObjectTemplate::NewInstance() {
4459 i::Isolate* isolate = i::Isolate::Current();
4460 ON_BAILOUT(isolate, "v8::ObjectTemplate::NewInstance()",
4461 return Local<v8::Object>());
4462 LOG_API(isolate, "ObjectTemplate::NewInstance");
4464 EXCEPTION_PREAMBLE(isolate);
4465 i::Handle<i::Object> obj =
4466 i::Execution::InstantiateObject(Utils::OpenHandle(this),
4467 &has_pending_exception);
4468 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
4469 return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
4473 Local<v8::Function> FunctionTemplate::GetFunction() {
4474 i::Isolate* isolate = i::Isolate::Current();
4475 ON_BAILOUT(isolate, "v8::FunctionTemplate::GetFunction()",
4476 return Local<v8::Function>());
4477 LOG_API(isolate, "FunctionTemplate::GetFunction");
4479 EXCEPTION_PREAMBLE(isolate);
4480 i::Handle<i::Object> obj =
4481 i::Execution::InstantiateFunction(Utils::OpenHandle(this),
4482 &has_pending_exception);
4483 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Function>());
4484 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
4488 bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
4489 ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
4491 i::Object* obj = *Utils::OpenHandle(*value);
4492 return obj->IsInstanceOf(*Utils::OpenHandle(this));
4496 static Local<External> ExternalNewImpl(void* data) {
4497 return Utils::ToLocal(FACTORY->NewForeign(static_cast<i::Address>(data)));
4500 static void* ExternalValueImpl(i::Handle<i::Object> obj) {
4501 return reinterpret_cast<void*>(i::Foreign::cast(*obj)->address());
4505 Local<Value> v8::External::Wrap(void* data) {
4506 i::Isolate* isolate = i::Isolate::Current();
4507 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4508 EnsureInitializedForIsolate(isolate, "v8::External::Wrap()");
4509 LOG_API(isolate, "External::Wrap");
4512 v8::Local<v8::Value> result = CanBeEncodedAsSmi(data)
4513 ? Utils::ToLocal(i::Handle<i::Object>(EncodeAsSmi(data)))
4514 : v8::Local<v8::Value>(ExternalNewImpl(data));
4516 ASSERT_EQ(data, Unwrap(result));
4521 void* v8::Object::SlowGetPointerFromInternalField(int index) {
4522 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
4523 i::Object* value = obj->GetInternalField(index);
4524 if (value->IsSmi()) {
4525 return i::Internals::GetExternalPointerFromSmi(value);
4526 } else if (value->IsForeign()) {
4527 return reinterpret_cast<void*>(i::Foreign::cast(value)->address());
4534 void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
4535 if (IsDeadCheck(i::Isolate::Current(), "v8::External::Unwrap()")) return 0;
4536 i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
4539 result = i::Internals::GetExternalPointerFromSmi(*obj);
4540 } else if (obj->IsForeign()) {
4541 result = ExternalValueImpl(obj);
4545 ASSERT_EQ(result, QuickUnwrap(wrapper));
4550 Local<External> v8::External::New(void* data) {
4551 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
4552 i::Isolate* isolate = i::Isolate::Current();
4553 EnsureInitializedForIsolate(isolate, "v8::External::New()");
4554 LOG_API(isolate, "External::New");
4556 return ExternalNewImpl(data);
4560 void* External::Value() const {
4561 if (IsDeadCheck(i::Isolate::Current(), "v8::External::Value()")) return 0;
4562 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4563 return ExternalValueImpl(obj);
4567 Local<String> v8::String::Empty() {
4568 i::Isolate* isolate = i::Isolate::Current();
4569 EnsureInitializedForIsolate(isolate, "v8::String::Empty()");
4570 LOG_API(isolate, "String::Empty()");
4571 return Utils::ToLocal(isolate->factory()->empty_symbol());
4575 Local<String> v8::String::New(const char* data, int length) {
4576 i::Isolate* isolate = i::Isolate::Current();
4577 EnsureInitializedForIsolate(isolate, "v8::String::New()");
4578 LOG_API(isolate, "String::New(char)");
4579 if (length == 0) return Empty();
4581 if (length == -1) length = i::StrLength(data);
4582 i::Handle<i::String> result =
4583 isolate->factory()->NewStringFromUtf8(
4584 i::Vector<const char>(data, length));
4585 return Utils::ToLocal(result);
4589 Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
4590 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
4591 i::Isolate* isolate = left_string->GetIsolate();
4592 EnsureInitializedForIsolate(isolate, "v8::String::New()");
4593 LOG_API(isolate, "String::New(char)");
4595 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
4596 i::Handle<i::String> result = isolate->factory()->NewConsString(left_string,
4598 return Utils::ToLocal(result);
4602 Local<String> v8::String::NewUndetectable(const char* data, int length) {
4603 i::Isolate* isolate = i::Isolate::Current();
4604 EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4605 LOG_API(isolate, "String::NewUndetectable(char)");
4607 if (length == -1) length = i::StrLength(data);
4608 i::Handle<i::String> result =
4609 isolate->factory()->NewStringFromUtf8(
4610 i::Vector<const char>(data, length));
4611 result->MarkAsUndetectable();
4612 return Utils::ToLocal(result);
4616 static int TwoByteStringLength(const uint16_t* data) {
4618 while (data[length] != '\0') length++;
4623 Local<String> v8::String::New(const uint16_t* data, int length) {
4624 i::Isolate* isolate = i::Isolate::Current();
4625 EnsureInitializedForIsolate(isolate, "v8::String::New()");
4626 LOG_API(isolate, "String::New(uint16_)");
4627 if (length == 0) return Empty();
4629 if (length == -1) length = TwoByteStringLength(data);
4630 i::Handle<i::String> result =
4631 isolate->factory()->NewStringFromTwoByte(
4632 i::Vector<const uint16_t>(data, length));
4633 return Utils::ToLocal(result);
4637 Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
4638 i::Isolate* isolate = i::Isolate::Current();
4639 EnsureInitializedForIsolate(isolate, "v8::String::NewUndetectable()");
4640 LOG_API(isolate, "String::NewUndetectable(uint16_)");
4642 if (length == -1) length = TwoByteStringLength(data);
4643 i::Handle<i::String> result =
4644 isolate->factory()->NewStringFromTwoByte(
4645 i::Vector<const uint16_t>(data, length));
4646 result->MarkAsUndetectable();
4647 return Utils::ToLocal(result);
4651 i::Handle<i::String> NewExternalStringHandle(i::Isolate* isolate,
4652 v8::String::ExternalStringResource* resource) {
4653 i::Handle<i::String> result =
4654 isolate->factory()->NewExternalStringFromTwoByte(resource);
4659 i::Handle<i::String> NewExternalAsciiStringHandle(i::Isolate* isolate,
4660 v8::String::ExternalAsciiStringResource* resource) {
4661 i::Handle<i::String> result =
4662 isolate->factory()->NewExternalStringFromAscii(resource);
4667 Local<String> v8::String::NewExternal(
4668 v8::String::ExternalStringResource* resource) {
4669 i::Isolate* isolate = i::Isolate::Current();
4670 EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4671 LOG_API(isolate, "String::NewExternal");
4673 i::Handle<i::String> result = NewExternalStringHandle(isolate, resource);
4674 isolate->heap()->external_string_table()->AddString(*result);
4675 return Utils::ToLocal(result);
4679 bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
4680 i::Handle<i::String> obj = Utils::OpenHandle(this);
4681 i::Isolate* isolate = obj->GetIsolate();
4682 if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4683 if (i::StringShape(*obj).IsExternalTwoByte()) {
4684 return false; // Already an external string.
4687 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4690 if (isolate->heap()->IsInGCPostProcessing()) {
4693 bool result = obj->MakeExternal(resource);
4694 if (result && !obj->IsSymbol()) {
4695 isolate->heap()->external_string_table()->AddString(*obj);
4701 Local<String> v8::String::NewExternal(
4702 v8::String::ExternalAsciiStringResource* resource) {
4703 i::Isolate* isolate = i::Isolate::Current();
4704 EnsureInitializedForIsolate(isolate, "v8::String::NewExternal()");
4705 LOG_API(isolate, "String::NewExternal");
4707 i::Handle<i::String> result = NewExternalAsciiStringHandle(isolate, resource);
4708 isolate->heap()->external_string_table()->AddString(*result);
4709 return Utils::ToLocal(result);
4713 bool v8::String::MakeExternal(
4714 v8::String::ExternalAsciiStringResource* resource) {
4715 i::Handle<i::String> obj = Utils::OpenHandle(this);
4716 i::Isolate* isolate = obj->GetIsolate();
4717 if (IsDeadCheck(isolate, "v8::String::MakeExternal()")) return false;
4718 if (i::StringShape(*obj).IsExternalTwoByte()) {
4719 return false; // Already an external string.
4722 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4725 if (isolate->heap()->IsInGCPostProcessing()) {
4728 bool result = obj->MakeExternal(resource);
4729 if (result && !obj->IsSymbol()) {
4730 isolate->heap()->external_string_table()->AddString(*obj);
4736 bool v8::String::CanMakeExternal() {
4737 if (!internal::FLAG_clever_optimizations) return false;
4738 i::Handle<i::String> obj = Utils::OpenHandle(this);
4739 i::Isolate* isolate = obj->GetIsolate();
4740 if (IsDeadCheck(isolate, "v8::String::CanMakeExternal()")) return false;
4741 if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
4744 int size = obj->Size(); // Byte size of the original string.
4745 if (size < i::ExternalString::kSize)
4747 i::StringShape shape(*obj);
4748 return !shape.IsExternal();
4752 Local<v8::Object> v8::Object::New() {
4753 i::Isolate* isolate = i::Isolate::Current();
4754 EnsureInitializedForIsolate(isolate, "v8::Object::New()");
4755 LOG_API(isolate, "Object::New");
4757 i::Handle<i::JSObject> obj =
4758 isolate->factory()->NewJSObject(isolate->object_function());
4759 return Utils::ToLocal(obj);
4763 Local<v8::Value> v8::NumberObject::New(double value) {
4764 i::Isolate* isolate = i::Isolate::Current();
4765 EnsureInitializedForIsolate(isolate, "v8::NumberObject::New()");
4766 LOG_API(isolate, "NumberObject::New");
4768 i::Handle<i::Object> number = isolate->factory()->NewNumber(value);
4769 i::Handle<i::Object> obj = isolate->factory()->ToObject(number);
4770 return Utils::ToLocal(obj);
4774 double v8::NumberObject::NumberValue() const {
4775 i::Isolate* isolate = i::Isolate::Current();
4776 if (IsDeadCheck(isolate, "v8::NumberObject::NumberValue()")) return 0;
4777 LOG_API(isolate, "NumberObject::NumberValue");
4778 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4779 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4780 return jsvalue->value()->Number();
4784 Local<v8::Value> v8::BooleanObject::New(bool value) {
4785 i::Isolate* isolate = i::Isolate::Current();
4786 EnsureInitializedForIsolate(isolate, "v8::BooleanObject::New()");
4787 LOG_API(isolate, "BooleanObject::New");
4789 i::Handle<i::Object> boolean(value ? isolate->heap()->true_value()
4790 : isolate->heap()->false_value());
4791 i::Handle<i::Object> obj = isolate->factory()->ToObject(boolean);
4792 return Utils::ToLocal(obj);
4796 bool v8::BooleanObject::BooleanValue() const {
4797 i::Isolate* isolate = i::Isolate::Current();
4798 if (IsDeadCheck(isolate, "v8::BooleanObject::BooleanValue()")) return 0;
4799 LOG_API(isolate, "BooleanObject::BooleanValue");
4800 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4801 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4802 return jsvalue->value()->IsTrue();
4806 Local<v8::Value> v8::StringObject::New(Handle<String> value) {
4807 i::Isolate* isolate = i::Isolate::Current();
4808 EnsureInitializedForIsolate(isolate, "v8::StringObject::New()");
4809 LOG_API(isolate, "StringObject::New");
4811 i::Handle<i::Object> obj =
4812 isolate->factory()->ToObject(Utils::OpenHandle(*value));
4813 return Utils::ToLocal(obj);
4817 Local<v8::String> v8::StringObject::StringValue() const {
4818 i::Isolate* isolate = i::Isolate::Current();
4819 if (IsDeadCheck(isolate, "v8::StringObject::StringValue()")) {
4820 return Local<v8::String>();
4822 LOG_API(isolate, "StringObject::StringValue");
4823 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4824 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4825 return Utils::ToLocal(
4826 i::Handle<i::String>(i::String::cast(jsvalue->value())));
4830 Local<v8::Value> v8::Date::New(double time) {
4831 i::Isolate* isolate = i::Isolate::Current();
4832 EnsureInitializedForIsolate(isolate, "v8::Date::New()");
4833 LOG_API(isolate, "Date::New");
4835 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
4836 time = i::OS::nan_value();
4839 EXCEPTION_PREAMBLE(isolate);
4840 i::Handle<i::Object> obj =
4841 i::Execution::NewDate(time, &has_pending_exception);
4842 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Value>());
4843 return Utils::ToLocal(obj);
4847 double v8::Date::NumberValue() const {
4848 i::Isolate* isolate = i::Isolate::Current();
4849 if (IsDeadCheck(isolate, "v8::Date::NumberValue()")) return 0;
4850 LOG_API(isolate, "Date::NumberValue");
4851 i::Handle<i::Object> obj = Utils::OpenHandle(this);
4852 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
4853 return jsvalue->value()->Number();
4857 void v8::Date::DateTimeConfigurationChangeNotification() {
4858 i::Isolate* isolate = i::Isolate::Current();
4859 ON_BAILOUT(isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
4861 LOG_API(isolate, "Date::DateTimeConfigurationChangeNotification");
4864 i::HandleScope scope(isolate);
4865 // Get the function ResetDateCache (defined in date-delay.js).
4866 i::Handle<i::String> func_name_str =
4867 isolate->factory()->LookupAsciiSymbol("ResetDateCache");
4868 i::MaybeObject* result =
4869 isolate->js_builtins_object()->GetProperty(*func_name_str);
4870 i::Object* object_func;
4871 if (!result->ToObject(&object_func)) {
4875 if (object_func->IsJSFunction()) {
4876 i::Handle<i::JSFunction> func =
4877 i::Handle<i::JSFunction>(i::JSFunction::cast(object_func));
4879 // Call ResetDateCache(0 but expect no exceptions:
4880 bool caught_exception = false;
4881 i::Execution::TryCall(func,
4882 isolate->js_builtins_object(),
4890 static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
4893 if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
4894 if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
4895 if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
4896 ASSERT(num_flags <= static_cast<int>(ARRAY_SIZE(flags_buf)));
4897 return FACTORY->LookupSymbol(
4898 i::Vector<const char>(flags_buf, num_flags));
4902 Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
4904 i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
4905 EnsureInitializedForIsolate(isolate, "v8::RegExp::New()");
4906 LOG_API(isolate, "RegExp::New");
4908 EXCEPTION_PREAMBLE(isolate);
4909 i::Handle<i::JSRegExp> obj = i::Execution::NewJSRegExp(
4910 Utils::OpenHandle(*pattern),
4911 RegExpFlagsToString(flags),
4912 &has_pending_exception);
4913 EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::RegExp>());
4914 return Utils::ToLocal(i::Handle<i::JSRegExp>::cast(obj));
4918 Local<v8::String> v8::RegExp::GetSource() const {
4919 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4920 if (IsDeadCheck(isolate, "v8::RegExp::GetSource()")) {
4921 return Local<v8::String>();
4923 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4924 return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
4928 // Assert that the static flags cast in GetFlags is valid.
4929 #define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
4930 STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
4931 static_cast<int>(i::JSRegExp::internal_flag))
4932 REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
4933 REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
4934 REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
4935 REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
4936 #undef REGEXP_FLAG_ASSERT_EQ
4938 v8::RegExp::Flags v8::RegExp::GetFlags() const {
4939 if (IsDeadCheck(i::Isolate::Current(), "v8::RegExp::GetFlags()")) {
4940 return v8::RegExp::kNone;
4942 i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
4943 return static_cast<RegExp::Flags>(obj->GetFlags().value());
4947 Local<v8::Array> v8::Array::New(int length) {
4948 i::Isolate* isolate = i::Isolate::Current();
4949 EnsureInitializedForIsolate(isolate, "v8::Array::New()");
4950 LOG_API(isolate, "Array::New");
4952 int real_length = length > 0 ? length : 0;
4953 i::Handle<i::JSArray> obj = isolate->factory()->NewJSArray(real_length);
4954 i::Handle<i::Object> length_obj =
4955 isolate->factory()->NewNumberFromInt(real_length);
4956 obj->set_length(*length_obj);
4957 return Utils::ToLocal(obj);
4961 uint32_t v8::Array::Length() const {
4962 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4963 if (IsDeadCheck(isolate, "v8::Array::Length()")) return 0;
4964 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
4965 i::Object* length = obj->length();
4966 if (length->IsSmi()) {
4967 return i::Smi::cast(length)->value();
4969 return static_cast<uint32_t>(length->Number());
4974 Local<Object> Array::CloneElementAt(uint32_t index) {
4975 i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
4976 ON_BAILOUT(isolate, "v8::Array::CloneElementAt()", return Local<Object>());
4977 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
4978 if (!self->HasFastElements()) {
4979 return Local<Object>();
4981 i::FixedArray* elms = i::FixedArray::cast(self->elements());
4982 i::Object* paragon = elms->get(index);
4983 if (!paragon->IsJSObject()) {
4984 return Local<Object>();
4986 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
4987 EXCEPTION_PREAMBLE(isolate);
4989 i::Handle<i::JSObject> result = i::Copy(paragon_handle);
4990 has_pending_exception = result.is_null();
4991 EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
4992 return Utils::ToLocal(result);
4996 Local<String> v8::String::NewSymbol(const char* data, int length) {
4997 i::Isolate* isolate = i::Isolate::Current();
4998 EnsureInitializedForIsolate(isolate, "v8::String::NewSymbol()");
4999 LOG_API(isolate, "String::NewSymbol(char)");
5001 if (length == -1) length = i::StrLength(data);
5002 i::Handle<i::String> result =
5003 isolate->factory()->LookupSymbol(i::Vector<const char>(data, length));
5004 return Utils::ToLocal(result);
5008 Local<Number> v8::Number::New(double value) {
5009 i::Isolate* isolate = i::Isolate::Current();
5010 EnsureInitializedForIsolate(isolate, "v8::Number::New()");
5012 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
5013 value = i::OS::nan_value();
5016 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5017 return Utils::NumberToLocal(result);
5021 Local<Integer> v8::Integer::New(int32_t value) {
5022 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5023 EnsureInitializedForIsolate(isolate, "v8::Integer::New()");
5024 if (i::Smi::IsValid(value)) {
5025 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
5029 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5030 return Utils::IntegerToLocal(result);
5034 Local<Integer> Integer::NewFromUnsigned(uint32_t value) {
5035 bool fits_into_int32_t = (value & (1 << 31)) == 0;
5036 if (fits_into_int32_t) {
5037 return Integer::New(static_cast<int32_t>(value));
5039 i::Isolate* isolate = i::Isolate::Current();
5041 i::Handle<i::Object> result = isolate->factory()->NewNumber(value);
5042 return Utils::IntegerToLocal(result);
5046 void V8::IgnoreOutOfMemoryException() {
5047 EnterIsolateIfNeeded()->set_ignore_out_of_memory(true);
5051 bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
5052 i::Isolate* isolate = i::Isolate::Current();
5053 EnsureInitializedForIsolate(isolate, "v8::V8::AddMessageListener()");
5054 ON_BAILOUT(isolate, "v8::V8::AddMessageListener()", return false);
5056 i::HandleScope scope(isolate);
5057 NeanderArray listeners(isolate->factory()->message_listeners());
5058 NeanderObject obj(2);
5059 obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
5060 obj.set(1, data.IsEmpty() ?
5061 isolate->heap()->undefined_value() :
5062 *Utils::OpenHandle(*data));
5063 listeners.add(obj.value());
5068 void V8::RemoveMessageListeners(MessageCallback that) {
5069 i::Isolate* isolate = i::Isolate::Current();
5070 EnsureInitializedForIsolate(isolate, "v8::V8::RemoveMessageListener()");
5071 ON_BAILOUT(isolate, "v8::V8::RemoveMessageListeners()", return);
5073 i::HandleScope scope(isolate);
5074 NeanderArray listeners(isolate->factory()->message_listeners());
5075 for (int i = 0; i < listeners.length(); i++) {
5076 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
5078 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
5079 i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
5080 if (callback_obj->address() == FUNCTION_ADDR(that)) {
5081 listeners.set(i, isolate->heap()->undefined_value());
5087 void V8::SetCaptureStackTraceForUncaughtExceptions(
5090 StackTrace::StackTraceOptions options) {
5091 i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
5098 void V8::SetCounterFunction(CounterLookupCallback callback) {
5099 i::Isolate* isolate = EnterIsolateIfNeeded();
5100 if (IsDeadCheck(isolate, "v8::V8::SetCounterFunction()")) return;
5101 isolate->stats_table()->SetCounterFunction(callback);
5104 void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
5105 i::Isolate* isolate = EnterIsolateIfNeeded();
5106 if (IsDeadCheck(isolate, "v8::V8::SetCreateHistogramFunction()")) return;
5107 isolate->stats_table()->SetCreateHistogramFunction(callback);
5110 void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
5111 i::Isolate* isolate = EnterIsolateIfNeeded();
5112 if (IsDeadCheck(isolate, "v8::V8::SetAddHistogramSampleFunction()")) return;
5113 isolate->stats_table()->
5114 SetAddHistogramSampleFunction(callback);
5117 void V8::EnableSlidingStateWindow() {
5118 i::Isolate* isolate = i::Isolate::Current();
5119 if (IsDeadCheck(isolate, "v8::V8::EnableSlidingStateWindow()")) return;
5120 isolate->logger()->EnableSlidingStateWindow();
5124 void V8::SetFailedAccessCheckCallbackFunction(
5125 FailedAccessCheckCallback callback) {
5126 i::Isolate* isolate = i::Isolate::Current();
5127 if (IsDeadCheck(isolate, "v8::V8::SetFailedAccessCheckCallbackFunction()")) {
5130 isolate->SetFailedAccessCheckCallback(callback);
5134 void V8::SetUserObjectComparisonCallbackFunction(
5135 UserObjectComparisonCallback callback) {
5136 i::Isolate* isolate = i::Isolate::Current();
5137 if (IsDeadCheck(isolate, "v8::V8::SetUserObjectComparisonCallbackFunction()")) {
5140 isolate->SetUserObjectComparisonCallback(callback);
5144 void V8::AddObjectGroup(Persistent<Value>* objects,
5146 RetainedObjectInfo* info) {
5147 i::Isolate* isolate = i::Isolate::Current();
5148 if (IsDeadCheck(isolate, "v8::V8::AddObjectGroup()")) return;
5149 STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5150 isolate->global_handles()->AddObjectGroup(
5151 reinterpret_cast<i::Object***>(objects), length, info);
5155 void V8::AddImplicitReferences(Persistent<Object> parent,
5156 Persistent<Value>* children,
5158 i::Isolate* isolate = i::Isolate::Current();
5159 if (IsDeadCheck(isolate, "v8::V8::AddImplicitReferences()")) return;
5160 STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
5161 isolate->global_handles()->AddImplicitReferences(
5162 i::Handle<i::HeapObject>::cast(Utils::OpenHandle(*parent)).location(),
5163 reinterpret_cast<i::Object***>(children), length);
5167 int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
5168 i::Isolate* isolate = i::Isolate::Current();
5169 if (IsDeadCheck(isolate, "v8::V8::AdjustAmountOfExternalAllocatedMemory()")) {
5172 return isolate->heap()->AdjustAmountOfExternalAllocatedMemory(
5177 void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
5178 i::Isolate* isolate = i::Isolate::Current();
5179 if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCPrologueCallback()")) return;
5180 isolate->heap()->SetGlobalGCPrologueCallback(callback);
5184 void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
5185 i::Isolate* isolate = i::Isolate::Current();
5186 if (IsDeadCheck(isolate, "v8::V8::SetGlobalGCEpilogueCallback()")) return;
5187 isolate->heap()->SetGlobalGCEpilogueCallback(callback);
5191 void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
5192 i::Isolate* isolate = i::Isolate::Current();
5193 if (IsDeadCheck(isolate, "v8::V8::AddGCPrologueCallback()")) return;
5194 isolate->heap()->AddGCPrologueCallback(callback, gc_type);
5198 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
5199 i::Isolate* isolate = i::Isolate::Current();
5200 if (IsDeadCheck(isolate, "v8::V8::RemoveGCPrologueCallback()")) return;
5201 isolate->heap()->RemoveGCPrologueCallback(callback);
5205 void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
5206 i::Isolate* isolate = i::Isolate::Current();
5207 if (IsDeadCheck(isolate, "v8::V8::AddGCEpilogueCallback()")) return;
5208 isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
5212 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
5213 i::Isolate* isolate = i::Isolate::Current();
5214 if (IsDeadCheck(isolate, "v8::V8::RemoveGCEpilogueCallback()")) return;
5215 isolate->heap()->RemoveGCEpilogueCallback(callback);
5219 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
5221 AllocationAction action) {
5222 i::Isolate* isolate = i::Isolate::Current();
5223 if (IsDeadCheck(isolate, "v8::V8::AddMemoryAllocationCallback()")) return;
5224 isolate->memory_allocator()->AddMemoryAllocationCallback(
5225 callback, space, action);
5229 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
5230 i::Isolate* isolate = i::Isolate::Current();
5231 if (IsDeadCheck(isolate, "v8::V8::RemoveMemoryAllocationCallback()")) return;
5232 isolate->memory_allocator()->RemoveMemoryAllocationCallback(
5237 void V8::PauseProfiler() {
5238 i::Isolate* isolate = i::Isolate::Current();
5239 isolate->logger()->PauseProfiler();
5243 void V8::ResumeProfiler() {
5244 i::Isolate* isolate = i::Isolate::Current();
5245 isolate->logger()->ResumeProfiler();
5249 bool V8::IsProfilerPaused() {
5250 i::Isolate* isolate = i::Isolate::Current();
5251 return isolate->logger()->IsProfilerPaused();
5255 int V8::GetCurrentThreadId() {
5256 i::Isolate* isolate = i::Isolate::Current();
5257 EnsureInitializedForIsolate(isolate, "V8::GetCurrentThreadId()");
5258 return isolate->thread_id().ToInteger();
5262 void V8::TerminateExecution(int thread_id) {
5263 i::Isolate* isolate = i::Isolate::Current();
5264 if (!isolate->IsInitialized()) return;
5265 API_ENTRY_CHECK(isolate, "V8::TerminateExecution()");
5266 // If the thread_id identifies the current thread just terminate
5267 // execution right away. Otherwise, ask the thread manager to
5268 // terminate the thread with the given id if any.
5269 i::ThreadId internal_tid = i::ThreadId::FromInteger(thread_id);
5270 if (isolate->thread_id().Equals(internal_tid)) {
5271 isolate->stack_guard()->TerminateExecution();
5273 isolate->thread_manager()->TerminateExecution(internal_tid);
5278 void V8::TerminateExecution(Isolate* isolate) {
5279 // If no isolate is supplied, use the default isolate.
5280 if (isolate != NULL) {
5281 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->TerminateExecution();
5283 i::Isolate::GetDefaultIsolateStackGuard()->TerminateExecution();
5288 bool V8::IsExecutionTerminating(Isolate* isolate) {
5289 i::Isolate* i_isolate = isolate != NULL ?
5290 reinterpret_cast<i::Isolate*>(isolate) : i::Isolate::Current();
5291 return IsExecutionTerminatingCheck(i_isolate);
5295 Isolate* Isolate::GetCurrent() {
5296 i::Isolate* isolate = i::Isolate::UncheckedCurrent();
5297 return reinterpret_cast<Isolate*>(isolate);
5301 Isolate* Isolate::New() {
5302 i::Isolate* isolate = new i::Isolate();
5303 return reinterpret_cast<Isolate*>(isolate);
5307 void Isolate::Dispose() {
5308 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5309 if (!ApiCheck(!isolate->IsInUse(),
5310 "v8::Isolate::Dispose()",
5311 "Disposing the isolate that is entered by a thread.")) {
5314 isolate->TearDown();
5318 void Isolate::Enter() {
5319 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5324 void Isolate::Exit() {
5325 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5330 void Isolate::SetData(void* data) {
5331 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5332 isolate->SetData(data);
5335 void* Isolate::GetData() {
5336 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
5337 return isolate->GetData();
5341 String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj)
5342 : str_(NULL), length_(0) {
5343 i::Isolate* isolate = i::Isolate::Current();
5344 if (IsDeadCheck(isolate, "v8::String::Utf8Value::Utf8Value()")) return;
5345 if (obj.IsEmpty()) return;
5347 i::HandleScope scope(isolate);
5349 Handle<String> str = obj->ToString();
5350 if (str.IsEmpty()) return;
5351 length_ = str->Utf8Length();
5352 str_ = i::NewArray<char>(length_ + 1);
5353 str->WriteUtf8(str_);
5357 String::Utf8Value::~Utf8Value() {
5358 i::DeleteArray(str_);
5362 String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj)
5363 : str_(NULL), length_(0) {
5364 i::Isolate* isolate = i::Isolate::Current();
5365 if (IsDeadCheck(isolate, "v8::String::AsciiValue::AsciiValue()")) return;
5366 if (obj.IsEmpty()) return;
5368 i::HandleScope scope(isolate);
5370 Handle<String> str = obj->ToString();
5371 if (str.IsEmpty()) return;
5372 length_ = str->Length();
5373 str_ = i::NewArray<char>(length_ + 1);
5374 str->WriteAscii(str_);
5378 String::AsciiValue::~AsciiValue() {
5379 i::DeleteArray(str_);
5383 String::Value::Value(v8::Handle<v8::Value> obj)
5384 : str_(NULL), length_(0) {
5385 i::Isolate* isolate = i::Isolate::Current();
5386 if (IsDeadCheck(isolate, "v8::String::Value::Value()")) return;
5387 if (obj.IsEmpty()) return;
5389 i::HandleScope scope(isolate);
5391 Handle<String> str = obj->ToString();
5392 if (str.IsEmpty()) return;
5393 length_ = str->Length();
5394 str_ = i::NewArray<uint16_t>(length_ + 1);
5399 String::Value::~Value() {
5400 i::DeleteArray(str_);
5403 Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
5404 i::Isolate* isolate = i::Isolate::Current();
5405 LOG_API(isolate, "RangeError");
5406 ON_BAILOUT(isolate, "v8::Exception::RangeError()", return Local<Value>());
5410 i::HandleScope scope(isolate);
5411 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5412 i::Handle<i::Object> result = isolate->factory()->NewRangeError(message);
5415 i::Handle<i::Object> result(error);
5416 return Utils::ToLocal(result);
5419 Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
5420 i::Isolate* isolate = i::Isolate::Current();
5421 LOG_API(isolate, "ReferenceError");
5422 ON_BAILOUT(isolate, "v8::Exception::ReferenceError()", return Local<Value>());
5426 i::HandleScope scope(isolate);
5427 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5428 i::Handle<i::Object> result =
5429 isolate->factory()->NewReferenceError(message);
5432 i::Handle<i::Object> result(error);
5433 return Utils::ToLocal(result);
5436 Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
5437 i::Isolate* isolate = i::Isolate::Current();
5438 LOG_API(isolate, "SyntaxError");
5439 ON_BAILOUT(isolate, "v8::Exception::SyntaxError()", return Local<Value>());
5443 i::HandleScope scope(isolate);
5444 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5445 i::Handle<i::Object> result = isolate->factory()->NewSyntaxError(message);
5448 i::Handle<i::Object> result(error);
5449 return Utils::ToLocal(result);
5452 Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
5453 i::Isolate* isolate = i::Isolate::Current();
5454 LOG_API(isolate, "TypeError");
5455 ON_BAILOUT(isolate, "v8::Exception::TypeError()", return Local<Value>());
5459 i::HandleScope scope(isolate);
5460 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5461 i::Handle<i::Object> result = isolate->factory()->NewTypeError(message);
5464 i::Handle<i::Object> result(error);
5465 return Utils::ToLocal(result);
5468 Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
5469 i::Isolate* isolate = i::Isolate::Current();
5470 LOG_API(isolate, "Error");
5471 ON_BAILOUT(isolate, "v8::Exception::Error()", return Local<Value>());
5475 i::HandleScope scope(isolate);
5476 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
5477 i::Handle<i::Object> result = isolate->factory()->NewError(message);
5480 i::Handle<i::Object> result(error);
5481 return Utils::ToLocal(result);
5485 // --- D e b u g S u p p o r t ---
5487 #ifdef ENABLE_DEBUGGER_SUPPORT
5489 static void EventCallbackWrapper(const v8::Debug::EventDetails& event_details) {
5490 i::Isolate* isolate = i::Isolate::Current();
5491 if (isolate->debug_event_callback() != NULL) {
5492 isolate->debug_event_callback()(event_details.GetEvent(),
5493 event_details.GetExecutionState(),
5494 event_details.GetEventData(),
5495 event_details.GetCallbackData());
5500 bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
5501 i::Isolate* isolate = i::Isolate::Current();
5502 EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener()");
5503 ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5506 isolate->set_debug_event_callback(that);
5508 i::HandleScope scope(isolate);
5509 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5512 isolate->factory()->NewForeign(FUNCTION_ADDR(EventCallbackWrapper));
5514 isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5519 bool Debug::SetDebugEventListener2(EventCallback2 that, Handle<Value> data) {
5520 i::Isolate* isolate = i::Isolate::Current();
5521 EnsureInitializedForIsolate(isolate, "v8::Debug::SetDebugEventListener2()");
5522 ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener2()", return false);
5524 i::HandleScope scope(isolate);
5525 i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
5527 foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
5529 isolate->debugger()->SetEventListener(foreign, Utils::OpenHandle(*data));
5534 bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
5535 Handle<Value> data) {
5536 i::Isolate* isolate = i::Isolate::Current();
5537 ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
5539 isolate->debugger()->SetEventListener(Utils::OpenHandle(*that),
5540 Utils::OpenHandle(*data));
5545 void Debug::DebugBreak(Isolate* isolate) {
5546 // If no isolate is supplied, use the default isolate.
5547 if (isolate != NULL) {
5548 reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->DebugBreak();
5550 i::Isolate::GetDefaultIsolateStackGuard()->DebugBreak();
5555 void Debug::CancelDebugBreak(Isolate* isolate) {
5556 // If no isolate is supplied, use the default isolate.
5557 if (isolate != NULL) {
5558 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5559 internal_isolate->stack_guard()->Continue(i::DEBUGBREAK);
5561 i::Isolate::GetDefaultIsolateStackGuard()->Continue(i::DEBUGBREAK);
5566 void Debug::DebugBreakForCommand(ClientData* data, Isolate* isolate) {
5567 // If no isolate is supplied, use the default isolate.
5568 if (isolate != NULL) {
5569 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5570 internal_isolate->debugger()->EnqueueDebugCommand(data);
5572 i::Isolate::GetDefaultIsolateDebugger()->EnqueueDebugCommand(data);
5577 static void MessageHandlerWrapper(const v8::Debug::Message& message) {
5578 i::Isolate* isolate = i::Isolate::Current();
5579 if (isolate->message_handler()) {
5580 v8::String::Value json(message.GetJSON());
5581 (isolate->message_handler())(*json, json.length(), message.GetClientData());
5586 void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
5587 bool message_handler_thread) {
5588 i::Isolate* isolate = i::Isolate::Current();
5589 EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5592 // Message handler thread not supported any more. Parameter temporally left in
5593 // the API for client compatibility reasons.
5594 CHECK(!message_handler_thread);
5596 // TODO(sgjesse) support the old message handler API through a simple wrapper.
5597 isolate->set_message_handler(handler);
5598 if (handler != NULL) {
5599 isolate->debugger()->SetMessageHandler(MessageHandlerWrapper);
5601 isolate->debugger()->SetMessageHandler(NULL);
5606 void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
5607 i::Isolate* isolate = i::Isolate::Current();
5608 EnsureInitializedForIsolate(isolate, "v8::Debug::SetMessageHandler");
5610 isolate->debugger()->SetMessageHandler(handler);
5614 void Debug::SendCommand(const uint16_t* command, int length,
5615 ClientData* client_data,
5617 // If no isolate is supplied, use the default isolate.
5618 if (isolate != NULL) {
5619 i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
5620 internal_isolate->debugger()->ProcessCommand(
5621 i::Vector<const uint16_t>(command, length), client_data);
5623 i::Isolate::GetDefaultIsolateDebugger()->ProcessCommand(
5624 i::Vector<const uint16_t>(command, length), client_data);
5629 void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
5631 i::Isolate* isolate = i::Isolate::Current();
5632 EnsureInitializedForIsolate(isolate, "v8::Debug::SetHostDispatchHandler");
5634 isolate->debugger()->SetHostDispatchHandler(handler, period);
5638 void Debug::SetDebugMessageDispatchHandler(
5639 DebugMessageDispatchHandler handler, bool provide_locker) {
5640 i::Isolate* isolate = i::Isolate::Current();
5641 EnsureInitializedForIsolate(isolate,
5642 "v8::Debug::SetDebugMessageDispatchHandler");
5644 isolate->debugger()->SetDebugMessageDispatchHandler(
5645 handler, provide_locker);
5649 Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
5650 v8::Handle<v8::Value> data) {
5651 i::Isolate* isolate = i::Isolate::Current();
5652 if (!isolate->IsInitialized()) return Local<Value>();
5653 ON_BAILOUT(isolate, "v8::Debug::Call()", return Local<Value>());
5655 i::Handle<i::Object> result;
5656 EXCEPTION_PREAMBLE(isolate);
5657 if (data.IsEmpty()) {
5658 result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5659 isolate->factory()->undefined_value(),
5660 &has_pending_exception);
5662 result = isolate->debugger()->Call(Utils::OpenHandle(*fun),
5663 Utils::OpenHandle(*data),
5664 &has_pending_exception);
5666 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5667 return Utils::ToLocal(result);
5671 Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
5672 i::Isolate* isolate = i::Isolate::Current();
5673 if (!isolate->IsInitialized()) return Local<Value>();
5674 ON_BAILOUT(isolate, "v8::Debug::GetMirror()", return Local<Value>());
5676 v8::HandleScope scope;
5677 i::Debug* isolate_debug = isolate->debug();
5678 isolate_debug->Load();
5679 i::Handle<i::JSObject> debug(isolate_debug->debug_context()->global());
5680 i::Handle<i::String> name =
5681 isolate->factory()->LookupAsciiSymbol("MakeMirror");
5682 i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
5683 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
5684 v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
5685 const int kArgc = 1;
5686 v8::Handle<v8::Value> argv[kArgc] = { obj };
5687 EXCEPTION_PREAMBLE(isolate);
5688 v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
5691 EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
5692 return scope.Close(result);
5696 bool Debug::EnableAgent(const char* name, int port, bool wait_for_connection) {
5697 return i::Isolate::Current()->debugger()->StartAgent(name, port,
5698 wait_for_connection);
5702 void Debug::DisableAgent() {
5703 return i::Isolate::Current()->debugger()->StopAgent();
5707 void Debug::ProcessDebugMessages() {
5708 i::Execution::ProcessDebugMesssages(true);
5711 Local<Context> Debug::GetDebugContext() {
5712 i::Isolate* isolate = i::Isolate::Current();
5713 EnsureInitializedForIsolate(isolate, "v8::Debug::GetDebugContext()");
5715 return Utils::ToLocal(i::Isolate::Current()->debugger()->GetDebugContext());
5718 #endif // ENABLE_DEBUGGER_SUPPORT
5721 Handle<String> CpuProfileNode::GetFunctionName() const {
5722 i::Isolate* isolate = i::Isolate::Current();
5723 IsDeadCheck(isolate, "v8::CpuProfileNode::GetFunctionName");
5724 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5725 const i::CodeEntry* entry = node->entry();
5726 if (!entry->has_name_prefix()) {
5727 return Handle<String>(ToApi<String>(
5728 isolate->factory()->LookupAsciiSymbol(entry->name())));
5730 return Handle<String>(ToApi<String>(isolate->factory()->NewConsString(
5731 isolate->factory()->LookupAsciiSymbol(entry->name_prefix()),
5732 isolate->factory()->LookupAsciiSymbol(entry->name()))));
5737 Handle<String> CpuProfileNode::GetScriptResourceName() const {
5738 i::Isolate* isolate = i::Isolate::Current();
5739 IsDeadCheck(isolate, "v8::CpuProfileNode::GetScriptResourceName");
5740 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
5741 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5742 node->entry()->resource_name())));
5746 int CpuProfileNode::GetLineNumber() const {
5747 i::Isolate* isolate = i::Isolate::Current();
5748 IsDeadCheck(isolate, "v8::CpuProfileNode::GetLineNumber");
5749 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
5753 double CpuProfileNode::GetTotalTime() const {
5754 i::Isolate* isolate = i::Isolate::Current();
5755 IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalTime");
5756 return reinterpret_cast<const i::ProfileNode*>(this)->GetTotalMillis();
5760 double CpuProfileNode::GetSelfTime() const {
5761 i::Isolate* isolate = i::Isolate::Current();
5762 IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfTime");
5763 return reinterpret_cast<const i::ProfileNode*>(this)->GetSelfMillis();
5767 double CpuProfileNode::GetTotalSamplesCount() const {
5768 i::Isolate* isolate = i::Isolate::Current();
5769 IsDeadCheck(isolate, "v8::CpuProfileNode::GetTotalSamplesCount");
5770 return reinterpret_cast<const i::ProfileNode*>(this)->total_ticks();
5774 double CpuProfileNode::GetSelfSamplesCount() const {
5775 i::Isolate* isolate = i::Isolate::Current();
5776 IsDeadCheck(isolate, "v8::CpuProfileNode::GetSelfSamplesCount");
5777 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
5781 unsigned CpuProfileNode::GetCallUid() const {
5782 i::Isolate* isolate = i::Isolate::Current();
5783 IsDeadCheck(isolate, "v8::CpuProfileNode::GetCallUid");
5784 return reinterpret_cast<const i::ProfileNode*>(this)->entry()->GetCallUid();
5788 int CpuProfileNode::GetChildrenCount() const {
5789 i::Isolate* isolate = i::Isolate::Current();
5790 IsDeadCheck(isolate, "v8::CpuProfileNode::GetChildrenCount");
5791 return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
5795 const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
5796 i::Isolate* isolate = i::Isolate::Current();
5797 IsDeadCheck(isolate, "v8::CpuProfileNode::GetChild");
5798 const i::ProfileNode* child =
5799 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
5800 return reinterpret_cast<const CpuProfileNode*>(child);
5804 void CpuProfile::Delete() {
5805 i::Isolate* isolate = i::Isolate::Current();
5806 IsDeadCheck(isolate, "v8::CpuProfile::Delete");
5807 i::CpuProfiler::DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
5808 if (i::CpuProfiler::GetProfilesCount() == 0 &&
5809 !i::CpuProfiler::HasDetachedProfiles()) {
5810 // If this was the last profile, clean up all accessory data as well.
5811 i::CpuProfiler::DeleteAllProfiles();
5816 unsigned CpuProfile::GetUid() const {
5817 i::Isolate* isolate = i::Isolate::Current();
5818 IsDeadCheck(isolate, "v8::CpuProfile::GetUid");
5819 return reinterpret_cast<const i::CpuProfile*>(this)->uid();
5823 Handle<String> CpuProfile::GetTitle() const {
5824 i::Isolate* isolate = i::Isolate::Current();
5825 IsDeadCheck(isolate, "v8::CpuProfile::GetTitle");
5826 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5827 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5828 profile->title())));
5832 const CpuProfileNode* CpuProfile::GetBottomUpRoot() const {
5833 i::Isolate* isolate = i::Isolate::Current();
5834 IsDeadCheck(isolate, "v8::CpuProfile::GetBottomUpRoot");
5835 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5836 return reinterpret_cast<const CpuProfileNode*>(profile->bottom_up()->root());
5840 const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
5841 i::Isolate* isolate = i::Isolate::Current();
5842 IsDeadCheck(isolate, "v8::CpuProfile::GetTopDownRoot");
5843 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
5844 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
5848 int CpuProfiler::GetProfilesCount() {
5849 i::Isolate* isolate = i::Isolate::Current();
5850 IsDeadCheck(isolate, "v8::CpuProfiler::GetProfilesCount");
5851 return i::CpuProfiler::GetProfilesCount();
5855 const CpuProfile* CpuProfiler::GetProfile(int index,
5856 Handle<Value> security_token) {
5857 i::Isolate* isolate = i::Isolate::Current();
5858 IsDeadCheck(isolate, "v8::CpuProfiler::GetProfile");
5859 return reinterpret_cast<const CpuProfile*>(
5860 i::CpuProfiler::GetProfile(
5861 security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5866 const CpuProfile* CpuProfiler::FindProfile(unsigned uid,
5867 Handle<Value> security_token) {
5868 i::Isolate* isolate = i::Isolate::Current();
5869 IsDeadCheck(isolate, "v8::CpuProfiler::FindProfile");
5870 return reinterpret_cast<const CpuProfile*>(
5871 i::CpuProfiler::FindProfile(
5872 security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5877 void CpuProfiler::StartProfiling(Handle<String> title) {
5878 i::Isolate* isolate = i::Isolate::Current();
5879 IsDeadCheck(isolate, "v8::CpuProfiler::StartProfiling");
5880 i::CpuProfiler::StartProfiling(*Utils::OpenHandle(*title));
5884 const CpuProfile* CpuProfiler::StopProfiling(Handle<String> title,
5885 Handle<Value> security_token) {
5886 i::Isolate* isolate = i::Isolate::Current();
5887 IsDeadCheck(isolate, "v8::CpuProfiler::StopProfiling");
5888 return reinterpret_cast<const CpuProfile*>(
5889 i::CpuProfiler::StopProfiling(
5890 security_token.IsEmpty() ? NULL : *Utils::OpenHandle(*security_token),
5891 *Utils::OpenHandle(*title)));
5895 void CpuProfiler::DeleteAllProfiles() {
5896 i::Isolate* isolate = i::Isolate::Current();
5897 IsDeadCheck(isolate, "v8::CpuProfiler::DeleteAllProfiles");
5898 i::CpuProfiler::DeleteAllProfiles();
5902 static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
5903 return const_cast<i::HeapGraphEdge*>(
5904 reinterpret_cast<const i::HeapGraphEdge*>(edge));
5908 HeapGraphEdge::Type HeapGraphEdge::GetType() const {
5909 i::Isolate* isolate = i::Isolate::Current();
5910 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetType");
5911 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
5915 Handle<Value> HeapGraphEdge::GetName() const {
5916 i::Isolate* isolate = i::Isolate::Current();
5917 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetName");
5918 i::HeapGraphEdge* edge = ToInternal(this);
5919 switch (edge->type()) {
5920 case i::HeapGraphEdge::kContextVariable:
5921 case i::HeapGraphEdge::kInternal:
5922 case i::HeapGraphEdge::kProperty:
5923 case i::HeapGraphEdge::kShortcut:
5924 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5926 case i::HeapGraphEdge::kElement:
5927 case i::HeapGraphEdge::kHidden:
5928 return Handle<Number>(ToApi<Number>(isolate->factory()->NewNumberFromInt(
5930 default: UNREACHABLE();
5932 return v8::Undefined();
5936 const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
5937 i::Isolate* isolate = i::Isolate::Current();
5938 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetFromNode");
5939 const i::HeapEntry* from = ToInternal(this)->From();
5940 return reinterpret_cast<const HeapGraphNode*>(from);
5944 const HeapGraphNode* HeapGraphEdge::GetToNode() const {
5945 i::Isolate* isolate = i::Isolate::Current();
5946 IsDeadCheck(isolate, "v8::HeapGraphEdge::GetToNode");
5947 const i::HeapEntry* to = ToInternal(this)->to();
5948 return reinterpret_cast<const HeapGraphNode*>(to);
5952 static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
5953 return const_cast<i::HeapEntry*>(
5954 reinterpret_cast<const i::HeapEntry*>(entry));
5958 HeapGraphNode::Type HeapGraphNode::GetType() const {
5959 i::Isolate* isolate = i::Isolate::Current();
5960 IsDeadCheck(isolate, "v8::HeapGraphNode::GetType");
5961 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
5965 Handle<String> HeapGraphNode::GetName() const {
5966 i::Isolate* isolate = i::Isolate::Current();
5967 IsDeadCheck(isolate, "v8::HeapGraphNode::GetName");
5968 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
5969 ToInternal(this)->name())));
5973 uint64_t HeapGraphNode::GetId() const {
5974 i::Isolate* isolate = i::Isolate::Current();
5975 IsDeadCheck(isolate, "v8::HeapGraphNode::GetId");
5976 return ToInternal(this)->id();
5980 int HeapGraphNode::GetSelfSize() const {
5981 i::Isolate* isolate = i::Isolate::Current();
5982 IsDeadCheck(isolate, "v8::HeapGraphNode::GetSelfSize");
5983 return ToInternal(this)->self_size();
5987 int HeapGraphNode::GetRetainedSize(bool exact) const {
5988 i::Isolate* isolate = i::Isolate::Current();
5989 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainedSize");
5990 return ToInternal(this)->RetainedSize(exact);
5994 int HeapGraphNode::GetChildrenCount() const {
5995 i::Isolate* isolate = i::Isolate::Current();
5996 IsDeadCheck(isolate, "v8::HeapSnapshot::GetChildrenCount");
5997 return ToInternal(this)->children().length();
6001 const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
6002 i::Isolate* isolate = i::Isolate::Current();
6003 IsDeadCheck(isolate, "v8::HeapSnapshot::GetChild");
6004 return reinterpret_cast<const HeapGraphEdge*>(
6005 &ToInternal(this)->children()[index]);
6009 int HeapGraphNode::GetRetainersCount() const {
6010 i::Isolate* isolate = i::Isolate::Current();
6011 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainersCount");
6012 return ToInternal(this)->retainers().length();
6016 const HeapGraphEdge* HeapGraphNode::GetRetainer(int index) const {
6017 i::Isolate* isolate = i::Isolate::Current();
6018 IsDeadCheck(isolate, "v8::HeapSnapshot::GetRetainer");
6019 return reinterpret_cast<const HeapGraphEdge*>(
6020 ToInternal(this)->retainers()[index]);
6024 const HeapGraphNode* HeapGraphNode::GetDominatorNode() const {
6025 i::Isolate* isolate = i::Isolate::Current();
6026 IsDeadCheck(isolate, "v8::HeapSnapshot::GetDominatorNode");
6027 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->dominator());
6031 v8::Handle<v8::Value> HeapGraphNode::GetHeapValue() const {
6032 i::Isolate* isolate = i::Isolate::Current();
6033 IsDeadCheck(isolate, "v8::HeapGraphNode::GetHeapValue");
6034 i::Handle<i::HeapObject> object = ToInternal(this)->GetHeapObject();
6035 return v8::Handle<Value>(!object.is_null() ?
6036 ToApi<Value>(object) : ToApi<Value>(
6037 isolate->factory()->undefined_value()));
6041 static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
6042 return const_cast<i::HeapSnapshot*>(
6043 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
6047 void HeapSnapshot::Delete() {
6048 i::Isolate* isolate = i::Isolate::Current();
6049 IsDeadCheck(isolate, "v8::HeapSnapshot::Delete");
6050 if (i::HeapProfiler::GetSnapshotsCount() > 1) {
6051 ToInternal(this)->Delete();
6053 // If this is the last snapshot, clean up all accessory data as well.
6054 i::HeapProfiler::DeleteAllSnapshots();
6059 HeapSnapshot::Type HeapSnapshot::GetType() const {
6060 i::Isolate* isolate = i::Isolate::Current();
6061 IsDeadCheck(isolate, "v8::HeapSnapshot::GetType");
6062 return static_cast<HeapSnapshot::Type>(ToInternal(this)->type());
6066 unsigned HeapSnapshot::GetUid() const {
6067 i::Isolate* isolate = i::Isolate::Current();
6068 IsDeadCheck(isolate, "v8::HeapSnapshot::GetUid");
6069 return ToInternal(this)->uid();
6073 Handle<String> HeapSnapshot::GetTitle() const {
6074 i::Isolate* isolate = i::Isolate::Current();
6075 IsDeadCheck(isolate, "v8::HeapSnapshot::GetTitle");
6076 return Handle<String>(ToApi<String>(isolate->factory()->LookupAsciiSymbol(
6077 ToInternal(this)->title())));
6081 const HeapGraphNode* HeapSnapshot::GetRoot() const {
6082 i::Isolate* isolate = i::Isolate::Current();
6083 IsDeadCheck(isolate, "v8::HeapSnapshot::GetHead");
6084 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
6088 const HeapGraphNode* HeapSnapshot::GetNodeById(uint64_t id) const {
6089 i::Isolate* isolate = i::Isolate::Current();
6090 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodeById");
6091 return reinterpret_cast<const HeapGraphNode*>(
6092 ToInternal(this)->GetEntryById(id));
6096 int HeapSnapshot::GetNodesCount() const {
6097 i::Isolate* isolate = i::Isolate::Current();
6098 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNodesCount");
6099 return ToInternal(this)->entries()->length();
6103 const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
6104 i::Isolate* isolate = i::Isolate::Current();
6105 IsDeadCheck(isolate, "v8::HeapSnapshot::GetNode");
6106 return reinterpret_cast<const HeapGraphNode*>(
6107 ToInternal(this)->entries()->at(index));
6111 void HeapSnapshot::Serialize(OutputStream* stream,
6112 HeapSnapshot::SerializationFormat format) const {
6113 i::Isolate* isolate = i::Isolate::Current();
6114 IsDeadCheck(isolate, "v8::HeapSnapshot::Serialize");
6115 ApiCheck(format == kJSON,
6116 "v8::HeapSnapshot::Serialize",
6117 "Unknown serialization format");
6118 ApiCheck(stream->GetOutputEncoding() == OutputStream::kAscii,
6119 "v8::HeapSnapshot::Serialize",
6120 "Unsupported output encoding");
6121 ApiCheck(stream->GetChunkSize() > 0,
6122 "v8::HeapSnapshot::Serialize",
6123 "Invalid stream chunk size");
6124 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
6125 serializer.Serialize(stream);
6129 int HeapProfiler::GetSnapshotsCount() {
6130 i::Isolate* isolate = i::Isolate::Current();
6131 IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshotsCount");
6132 return i::HeapProfiler::GetSnapshotsCount();
6136 const HeapSnapshot* HeapProfiler::GetSnapshot(int index) {
6137 i::Isolate* isolate = i::Isolate::Current();
6138 IsDeadCheck(isolate, "v8::HeapProfiler::GetSnapshot");
6139 return reinterpret_cast<const HeapSnapshot*>(
6140 i::HeapProfiler::GetSnapshot(index));
6144 const HeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {
6145 i::Isolate* isolate = i::Isolate::Current();
6146 IsDeadCheck(isolate, "v8::HeapProfiler::FindSnapshot");
6147 return reinterpret_cast<const HeapSnapshot*>(
6148 i::HeapProfiler::FindSnapshot(uid));
6152 const HeapSnapshot* HeapProfiler::TakeSnapshot(Handle<String> title,
6153 HeapSnapshot::Type type,
6154 ActivityControl* control) {
6155 i::Isolate* isolate = i::Isolate::Current();
6156 IsDeadCheck(isolate, "v8::HeapProfiler::TakeSnapshot");
6157 i::HeapSnapshot::Type internal_type = i::HeapSnapshot::kFull;
6159 case HeapSnapshot::kFull:
6160 internal_type = i::HeapSnapshot::kFull;
6165 return reinterpret_cast<const HeapSnapshot*>(
6166 i::HeapProfiler::TakeSnapshot(
6167 *Utils::OpenHandle(*title), internal_type, control));
6171 void HeapProfiler::DeleteAllSnapshots() {
6172 i::Isolate* isolate = i::Isolate::Current();
6173 IsDeadCheck(isolate, "v8::HeapProfiler::DeleteAllSnapshots");
6174 i::HeapProfiler::DeleteAllSnapshots();
6178 void HeapProfiler::DefineWrapperClass(uint16_t class_id,
6179 WrapperInfoCallback callback) {
6180 i::Isolate::Current()->heap_profiler()->DefineWrapperClass(class_id,
6186 v8::Testing::StressType internal::Testing::stress_type_ =
6187 v8::Testing::kStressTypeOpt;
6190 void Testing::SetStressRunType(Testing::StressType type) {
6191 internal::Testing::set_stress_type(type);
6194 int Testing::GetStressRuns() {
6195 if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
6197 // In debug mode the code runs much slower so stressing will only make two
6206 static void SetFlagsFromString(const char* flags) {
6207 V8::SetFlagsFromString(flags, i::StrLength(flags));
6211 void Testing::PrepareStressRun(int run) {
6212 static const char* kLazyOptimizations =
6213 "--prepare-always-opt --nolimit-inlining "
6214 "--noalways-opt --noopt-eagerly";
6215 static const char* kEagerOptimizations = "--opt-eagerly";
6216 static const char* kForcedOptimizations = "--always-opt";
6218 // If deoptimization stressed turn on frequent deoptimization. If no value
6219 // is spefified through --deopt-every-n-times use a default default value.
6220 static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
6221 if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
6222 internal::FLAG_deopt_every_n_times == 0) {
6223 SetFlagsFromString(kDeoptEvery13Times);
6227 // As stressing in debug mode only make two runs skip the deopt stressing
6229 if (run == GetStressRuns() - 1) {
6230 SetFlagsFromString(kForcedOptimizations);
6232 SetFlagsFromString(kEagerOptimizations);
6233 SetFlagsFromString(kLazyOptimizations);
6236 if (run == GetStressRuns() - 1) {
6237 SetFlagsFromString(kForcedOptimizations);
6238 } else if (run == GetStressRuns() - 2) {
6239 SetFlagsFromString(kEagerOptimizations);
6241 SetFlagsFromString(kLazyOptimizations);
6247 void Testing::DeoptimizeAll() {
6248 internal::Deoptimizer::DeoptimizeAll();
6252 namespace internal {
6255 void HandleScopeImplementer::FreeThreadResources() {
6260 char* HandleScopeImplementer::ArchiveThread(char* storage) {
6261 v8::ImplementationUtilities::HandleScopeData* current =
6262 isolate_->handle_scope_data();
6263 handle_scope_data_ = *current;
6264 memcpy(storage, this, sizeof(*this));
6266 ResetAfterArchive();
6267 current->Initialize();
6269 return storage + ArchiveSpacePerThread();
6273 int HandleScopeImplementer::ArchiveSpacePerThread() {
6274 return sizeof(HandleScopeImplementer);
6278 char* HandleScopeImplementer::RestoreThread(char* storage) {
6279 memcpy(this, storage, sizeof(*this));
6280 *isolate_->handle_scope_data() = handle_scope_data_;
6281 return storage + ArchiveSpacePerThread();
6285 void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
6286 // Iterate over all handles in the blocks except for the last.
6287 for (int i = blocks()->length() - 2; i >= 0; --i) {
6288 Object** block = blocks()->at(i);
6289 v->VisitPointers(block, &block[kHandleBlockSize]);
6292 // Iterate over live handles in the last block (if any).
6293 if (!blocks()->is_empty()) {
6294 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
6297 if (!saved_contexts_.is_empty()) {
6298 Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
6299 v->VisitPointers(start, start + saved_contexts_.length());
6304 void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
6305 v8::ImplementationUtilities::HandleScopeData* current =
6306 isolate_->handle_scope_data();
6307 handle_scope_data_ = *current;
6312 char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
6313 HandleScopeImplementer* scope_implementer =
6314 reinterpret_cast<HandleScopeImplementer*>(storage);
6315 scope_implementer->IterateThis(v);
6316 return storage + ArchiveSpacePerThread();
6319 } } // namespace v8::internal