blob: fd3d921734f1d14cea49acf6da0f964531fced8c [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "compiler.h"
34#include "debug.h"
35#include "execution.h"
36#include "global-handles.h"
37#include "platform.h"
38#include "serialize.h"
39#include "snapshot.h"
40#include "v8threads.h"
41#include "version.h"
42
43
44#define LOG_API(expr) LOG(ApiEntryCall(expr))
45
46#ifdef ENABLE_HEAP_PROTECTION
47#define ENTER_V8 i::VMState __state__(i::OTHER)
48#define LEAVE_V8 i::VMState __state__(i::EXTERNAL)
49#else
50#define ENTER_V8 ((void) 0)
51#define LEAVE_V8 ((void) 0)
52#endif
53
54namespace v8 {
55
56
57#define ON_BAILOUT(location, code) \
58 if (IsDeadCheck(location)) { \
59 code; \
60 UNREACHABLE(); \
61 }
62
63
64#define EXCEPTION_PREAMBLE() \
65 thread_local.IncrementCallDepth(); \
66 ASSERT(!i::Top::external_caught_exception()); \
67 bool has_pending_exception = false
68
69
70#define EXCEPTION_BAILOUT_CHECK(value) \
71 do { \
72 thread_local.DecrementCallDepth(); \
73 if (has_pending_exception) { \
74 if (thread_local.CallDepthIsZero() && i::Top::is_out_of_memory()) { \
75 if (!thread_local.ignore_out_of_memory()) \
76 i::V8::FatalProcessOutOfMemory(NULL); \
77 } \
78 bool call_depth_is_zero = thread_local.CallDepthIsZero(); \
79 i::Top::OptionalRescheduleException(call_depth_is_zero); \
80 return value; \
81 } \
82 } while (false)
83
84
85#define API_ENTRY_CHECK(msg) \
86 do { \
87 if (v8::Locker::IsActive()) { \
88 ApiCheck(i::ThreadManager::IsLockedByCurrentThread(), \
89 msg, \
90 "Entering the V8 API without proper locking in place"); \
91 } \
92 } while (false)
93
94// --- D a t a t h a t i s s p e c i f i c t o a t h r e a d ---
95
96
97static i::HandleScopeImplementer thread_local;
98
99
100// --- E x c e p t i o n B e h a v i o r ---
101
102
103static FatalErrorCallback exception_behavior = NULL;
104int i::Internals::kJSObjectType = JS_OBJECT_TYPE;
105int i::Internals::kFirstNonstringType = FIRST_NONSTRING_TYPE;
106int i::Internals::kProxyType = PROXY_TYPE;
107
108static void DefaultFatalErrorHandler(const char* location,
109 const char* message) {
110 ENTER_V8;
111 API_Fatal(location, message);
112}
113
114
115
116static FatalErrorCallback& GetFatalErrorHandler() {
117 if (exception_behavior == NULL) {
118 exception_behavior = DefaultFatalErrorHandler;
119 }
120 return exception_behavior;
121}
122
123
124
125// When V8 cannot allocated memory FatalProcessOutOfMemory is called.
126// The default fatal error handler is called and execution is stopped.
127void i::V8::FatalProcessOutOfMemory(const char* location) {
128 i::V8::SetFatalError();
129 FatalErrorCallback callback = GetFatalErrorHandler();
130 {
131 LEAVE_V8;
132 callback(location, "Allocation failed - process out of memory");
133 }
134 // If the callback returns, we stop execution.
135 UNREACHABLE();
136}
137
138
139void V8::SetFatalErrorHandler(FatalErrorCallback that) {
140 exception_behavior = that;
141}
142
143
144bool Utils::ReportApiFailure(const char* location, const char* message) {
145 FatalErrorCallback callback = GetFatalErrorHandler();
146 callback(location, message);
147 i::V8::SetFatalError();
148 return false;
149}
150
151
152bool V8::IsDead() {
153 return i::V8::IsDead();
154}
155
156
157static inline bool ApiCheck(bool condition,
158 const char* location,
159 const char* message) {
160 return condition ? true : Utils::ReportApiFailure(location, message);
161}
162
163
164static bool ReportV8Dead(const char* location) {
165 FatalErrorCallback callback = GetFatalErrorHandler();
166 callback(location, "V8 is no longer usable");
167 return true;
168}
169
170
171static bool ReportEmptyHandle(const char* location) {
172 FatalErrorCallback callback = GetFatalErrorHandler();
173 callback(location, "Reading from empty handle");
174 return true;
175}
176
177
178/**
179 * IsDeadCheck checks that the vm is usable. If, for instance, the vm has been
180 * out of memory at some point this check will fail. It should be called on
181 * entry to all methods that touch anything in the heap, except destructors
182 * which you sometimes can't avoid calling after the vm has crashed. Functions
183 * that call EnsureInitialized or ON_BAILOUT don't have to also call
184 * IsDeadCheck. ON_BAILOUT has the advantage over EnsureInitialized that you
185 * can arrange to return if the VM is dead. This is needed to ensure that no VM
186 * heap allocations are attempted on a dead VM. EnsureInitialized has the
187 * advantage over ON_BAILOUT that it actually initializes the VM if this has not
188 * yet been done.
189 */
190static inline bool IsDeadCheck(const char* location) {
191 return !i::V8::IsRunning()
192 && i::V8::IsDead() ? ReportV8Dead(location) : false;
193}
194
195
196static inline bool EmptyCheck(const char* location, v8::Handle<v8::Data> obj) {
197 return obj.IsEmpty() ? ReportEmptyHandle(location) : false;
198}
199
200
201static inline bool EmptyCheck(const char* location, const v8::Data* obj) {
202 return (obj == 0) ? ReportEmptyHandle(location) : false;
203}
204
205// --- S t a t i c s ---
206
207
208static i::StringInputBuffer write_input_buffer;
209
210
211static inline bool EnsureInitialized(const char* location) {
212 if (i::V8::IsRunning()) {
213 return true;
214 }
215 if (IsDeadCheck(location)) {
216 return false;
217 }
218 return ApiCheck(v8::V8::Initialize(), location, "Error initializing V8");
219}
220
221
222ImplementationUtilities::HandleScopeData*
223 ImplementationUtilities::CurrentHandleScope() {
224 return &i::HandleScope::current_;
225}
226
227
228#ifdef DEBUG
229void ImplementationUtilities::ZapHandleRange(i::Object** begin,
230 i::Object** end) {
231 i::HandleScope::ZapRange(begin, end);
232}
233#endif
234
235
236v8::Handle<v8::Primitive> ImplementationUtilities::Undefined() {
237 if (!EnsureInitialized("v8::Undefined()")) return v8::Handle<v8::Primitive>();
238 return v8::Handle<Primitive>(ToApi<Primitive>(i::Factory::undefined_value()));
239}
240
241
242v8::Handle<v8::Primitive> ImplementationUtilities::Null() {
243 if (!EnsureInitialized("v8::Null()")) return v8::Handle<v8::Primitive>();
244 return v8::Handle<Primitive>(ToApi<Primitive>(i::Factory::null_value()));
245}
246
247
248v8::Handle<v8::Boolean> ImplementationUtilities::True() {
249 if (!EnsureInitialized("v8::True()")) return v8::Handle<v8::Boolean>();
250 return v8::Handle<v8::Boolean>(ToApi<Boolean>(i::Factory::true_value()));
251}
252
253
254v8::Handle<v8::Boolean> ImplementationUtilities::False() {
255 if (!EnsureInitialized("v8::False()")) return v8::Handle<v8::Boolean>();
256 return v8::Handle<v8::Boolean>(ToApi<Boolean>(i::Factory::false_value()));
257}
258
259
260void V8::SetFlagsFromString(const char* str, int length) {
261 i::FlagList::SetFlagsFromString(str, length);
262}
263
264
265void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
266 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
267}
268
269
270v8::Handle<Value> ThrowException(v8::Handle<v8::Value> value) {
271 if (IsDeadCheck("v8::ThrowException()")) return v8::Handle<Value>();
272 ENTER_V8;
273 // If we're passed an empty handle, we throw an undefined exception
274 // to deal more gracefully with out of memory situations.
275 if (value.IsEmpty()) {
276 i::Top::ScheduleThrow(i::Heap::undefined_value());
277 } else {
278 i::Top::ScheduleThrow(*Utils::OpenHandle(*value));
279 }
280 return v8::Undefined();
281}
282
283
284RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
285
286
287RegisteredExtension::RegisteredExtension(Extension* extension)
288 : extension_(extension), state_(UNVISITED) { }
289
290
291void RegisteredExtension::Register(RegisteredExtension* that) {
292 that->next_ = RegisteredExtension::first_extension_;
293 RegisteredExtension::first_extension_ = that;
294}
295
296
297void RegisterExtension(Extension* that) {
298 RegisteredExtension* extension = new RegisteredExtension(that);
299 RegisteredExtension::Register(extension);
300}
301
302
303Extension::Extension(const char* name,
304 const char* source,
305 int dep_count,
306 const char** deps)
307 : name_(name),
308 source_(source),
309 dep_count_(dep_count),
310 deps_(deps),
311 auto_enable_(false) { }
312
313
314v8::Handle<Primitive> Undefined() {
315 LOG_API("Undefined");
316 return ImplementationUtilities::Undefined();
317}
318
319
320v8::Handle<Primitive> Null() {
321 LOG_API("Null");
322 return ImplementationUtilities::Null();
323}
324
325
326v8::Handle<Boolean> True() {
327 LOG_API("True");
328 return ImplementationUtilities::True();
329}
330
331
332v8::Handle<Boolean> False() {
333 LOG_API("False");
334 return ImplementationUtilities::False();
335}
336
337
338ResourceConstraints::ResourceConstraints()
339 : max_young_space_size_(0),
340 max_old_space_size_(0),
341 stack_limit_(NULL) { }
342
343
344bool SetResourceConstraints(ResourceConstraints* constraints) {
345 int semispace_size = constraints->max_young_space_size();
346 int old_gen_size = constraints->max_old_space_size();
347 if (semispace_size != 0 || old_gen_size != 0) {
348 bool result = i::Heap::ConfigureHeap(semispace_size, old_gen_size);
349 if (!result) return false;
350 }
351 if (constraints->stack_limit() != NULL) {
352 uintptr_t limit = reinterpret_cast<uintptr_t>(constraints->stack_limit());
353 i::StackGuard::SetStackLimit(limit);
354 }
355 return true;
356}
357
358
359i::Object** V8::GlobalizeReference(i::Object** obj) {
360 if (IsDeadCheck("V8::Persistent::New")) return NULL;
361 LOG_API("Persistent::New");
362 i::Handle<i::Object> result =
363 i::GlobalHandles::Create(*obj);
364 return result.location();
365}
366
367
368void V8::MakeWeak(i::Object** object, void* parameters,
369 WeakReferenceCallback callback) {
370 LOG_API("MakeWeak");
371 i::GlobalHandles::MakeWeak(object, parameters, callback);
372}
373
374
375void V8::ClearWeak(i::Object** obj) {
376 LOG_API("ClearWeak");
377 i::GlobalHandles::ClearWeakness(obj);
378}
379
380
381bool V8::IsGlobalNearDeath(i::Object** obj) {
382 LOG_API("IsGlobalNearDeath");
383 if (!i::V8::IsRunning()) return false;
384 return i::GlobalHandles::IsNearDeath(obj);
385}
386
387
388bool V8::IsGlobalWeak(i::Object** obj) {
389 LOG_API("IsGlobalWeak");
390 if (!i::V8::IsRunning()) return false;
391 return i::GlobalHandles::IsWeak(obj);
392}
393
394
395void V8::DisposeGlobal(i::Object** obj) {
396 LOG_API("DisposeGlobal");
397 if (!i::V8::IsRunning()) return;
398 if ((*obj)->IsGlobalContext()) i::Heap::NotifyContextDisposed();
399 i::GlobalHandles::Destroy(obj);
400}
401
402// --- H a n d l e s ---
403
404
405HandleScope::HandleScope() : is_closed_(false) {
406 API_ENTRY_CHECK("HandleScope::HandleScope");
407 i::HandleScope::Enter(&previous_);
408}
409
410
411HandleScope::~HandleScope() {
412 if (!is_closed_) {
413 i::HandleScope::Leave(&previous_);
414 }
415}
416
417
418int HandleScope::NumberOfHandles() {
419 return i::HandleScope::NumberOfHandles();
420}
421
422
423i::Object** v8::HandleScope::CreateHandle(i::Object* value) {
424 return i::HandleScope::CreateHandle(value);
425}
426
427
428void Context::Enter() {
429 if (IsDeadCheck("v8::Context::Enter()")) return;
430 ENTER_V8;
431 i::Handle<i::Context> env = Utils::OpenHandle(this);
432 thread_local.EnterContext(env);
433
434 thread_local.SaveContext(i::Top::context());
435 i::Top::set_context(*env);
436}
437
438
439void Context::Exit() {
440 if (!i::V8::IsRunning()) return;
441 if (!ApiCheck(thread_local.LeaveLastContext(),
442 "v8::Context::Exit()",
443 "Cannot exit non-entered context")) {
444 return;
445 }
446
447 // Content of 'last_context' could be NULL.
448 i::Context* last_context = thread_local.RestoreContext();
449 i::Top::set_context(last_context);
450}
451
452
453void Context::SetData(v8::Handle<Value> data) {
454 if (IsDeadCheck("v8::Context::SetData()")) return;
455 ENTER_V8;
456 {
457 HandleScope scope;
458 i::Handle<i::Context> env = Utils::OpenHandle(this);
459 i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
460 ASSERT(env->IsGlobalContext());
461 if (env->IsGlobalContext()) {
462 env->set_data(*raw_data);
463 }
464 }
465}
466
467
468v8::Local<v8::Value> Context::GetData() {
469 if (IsDeadCheck("v8::Context::GetData()")) return v8::Local<Value>();
470 ENTER_V8;
471 i::Object* raw_result = NULL;
472 {
473 HandleScope scope;
474 i::Handle<i::Context> env = Utils::OpenHandle(this);
475 ASSERT(env->IsGlobalContext());
476 if (env->IsGlobalContext()) {
477 raw_result = env->data();
478 } else {
479 return Local<Value>();
480 }
481 }
482 i::Handle<i::Object> result(raw_result);
483 return Utils::ToLocal(result);
484}
485
486
487i::Object** v8::HandleScope::RawClose(i::Object** value) {
488 if (!ApiCheck(!is_closed_,
489 "v8::HandleScope::Close()",
490 "Local scope has already been closed")) {
491 return 0;
492 }
493 LOG_API("CloseHandleScope");
494
495 // Read the result before popping the handle block.
496 i::Object* result = *value;
497 is_closed_ = true;
498 i::HandleScope::Leave(&previous_);
499
500 // Allocate a new handle on the previous handle block.
501 i::Handle<i::Object> handle(result);
502 return handle.location();
503}
504
505
506// --- N e a n d e r ---
507
508
509// A constructor cannot easily return an error value, therefore it is necessary
510// to check for a dead VM with ON_BAILOUT before constructing any Neander
511// objects. To remind you about this there is no HandleScope in the
512// NeanderObject constructor. When you add one to the site calling the
513// constructor you should check that you ensured the VM was not dead first.
514NeanderObject::NeanderObject(int size) {
515 EnsureInitialized("v8::Nowhere");
516 ENTER_V8;
517 value_ = i::Factory::NewNeanderObject();
518 i::Handle<i::FixedArray> elements = i::Factory::NewFixedArray(size);
519 value_->set_elements(*elements);
520}
521
522
523int NeanderObject::size() {
524 return i::FixedArray::cast(value_->elements())->length();
525}
526
527
528NeanderArray::NeanderArray() : obj_(2) {
529 obj_.set(0, i::Smi::FromInt(0));
530}
531
532
533int NeanderArray::length() {
534 return i::Smi::cast(obj_.get(0))->value();
535}
536
537
538i::Object* NeanderArray::get(int offset) {
539 ASSERT(0 <= offset);
540 ASSERT(offset < length());
541 return obj_.get(offset + 1);
542}
543
544
545// This method cannot easily return an error value, therefore it is necessary
546// to check for a dead VM with ON_BAILOUT before calling it. To remind you
547// about this there is no HandleScope in this method. When you add one to the
548// site calling this method you should check that you ensured the VM was not
549// dead first.
550void NeanderArray::add(i::Handle<i::Object> value) {
551 int length = this->length();
552 int size = obj_.size();
553 if (length == size - 1) {
554 i::Handle<i::FixedArray> new_elms = i::Factory::NewFixedArray(2 * size);
555 for (int i = 0; i < length; i++)
556 new_elms->set(i + 1, get(i));
557 obj_.value()->set_elements(*new_elms);
558 }
559 obj_.set(length + 1, *value);
560 obj_.set(0, i::Smi::FromInt(length + 1));
561}
562
563
564void NeanderArray::set(int index, i::Object* value) {
565 if (index < 0 || index >= this->length()) return;
566 obj_.set(index + 1, value);
567}
568
569
570// --- T e m p l a t e ---
571
572
573static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
574 that->set_tag(i::Smi::FromInt(type));
575}
576
577
578void Template::Set(v8::Handle<String> name, v8::Handle<Data> value,
579 v8::PropertyAttribute attribute) {
580 if (IsDeadCheck("v8::Template::SetProperty()")) return;
581 ENTER_V8;
582 HandleScope scope;
583 i::Handle<i::Object> list(Utils::OpenHandle(this)->property_list());
584 if (list->IsUndefined()) {
585 list = NeanderArray().value();
586 Utils::OpenHandle(this)->set_property_list(*list);
587 }
588 NeanderArray array(list);
589 array.add(Utils::OpenHandle(*name));
590 array.add(Utils::OpenHandle(*value));
591 array.add(Utils::OpenHandle(*v8::Integer::New(attribute)));
592}
593
594
595// --- F u n c t i o n T e m p l a t e ---
596static void InitializeFunctionTemplate(
597 i::Handle<i::FunctionTemplateInfo> info) {
598 info->set_tag(i::Smi::FromInt(Consts::FUNCTION_TEMPLATE));
599 info->set_flag(0);
600}
601
602
603Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
604 if (IsDeadCheck("v8::FunctionTemplate::PrototypeTemplate()")) {
605 return Local<ObjectTemplate>();
606 }
607 ENTER_V8;
608 i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template());
609 if (result->IsUndefined()) {
610 result = Utils::OpenHandle(*ObjectTemplate::New());
611 Utils::OpenHandle(this)->set_prototype_template(*result);
612 }
613 return Local<ObjectTemplate>(ToApi<ObjectTemplate>(result));
614}
615
616
617void FunctionTemplate::Inherit(v8::Handle<FunctionTemplate> value) {
618 if (IsDeadCheck("v8::FunctionTemplate::Inherit()")) return;
619 ENTER_V8;
620 Utils::OpenHandle(this)->set_parent_template(*Utils::OpenHandle(*value));
621}
622
623
624// To distinguish the function templates, so that we can find them in the
625// function cache of the global context.
626static int next_serial_number = 0;
627
628
629Local<FunctionTemplate> FunctionTemplate::New(InvocationCallback callback,
630 v8::Handle<Value> data, v8::Handle<Signature> signature) {
631 EnsureInitialized("v8::FunctionTemplate::New()");
632 LOG_API("FunctionTemplate::New");
633 ENTER_V8;
634 i::Handle<i::Struct> struct_obj =
635 i::Factory::NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
636 i::Handle<i::FunctionTemplateInfo> obj =
637 i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
638 InitializeFunctionTemplate(obj);
639 obj->set_serial_number(i::Smi::FromInt(next_serial_number++));
640 if (callback != 0) {
641 if (data.IsEmpty()) data = v8::Undefined();
642 Utils::ToLocal(obj)->SetCallHandler(callback, data);
643 }
644 obj->set_undetectable(false);
645 obj->set_needs_access_check(false);
646
647 if (!signature.IsEmpty())
648 obj->set_signature(*Utils::OpenHandle(*signature));
649 return Utils::ToLocal(obj);
650}
651
652
653Local<Signature> Signature::New(Handle<FunctionTemplate> receiver,
654 int argc, Handle<FunctionTemplate> argv[]) {
655 EnsureInitialized("v8::Signature::New()");
656 LOG_API("Signature::New");
657 ENTER_V8;
658 i::Handle<i::Struct> struct_obj =
659 i::Factory::NewStruct(i::SIGNATURE_INFO_TYPE);
660 i::Handle<i::SignatureInfo> obj =
661 i::Handle<i::SignatureInfo>::cast(struct_obj);
662 if (!receiver.IsEmpty()) obj->set_receiver(*Utils::OpenHandle(*receiver));
663 if (argc > 0) {
664 i::Handle<i::FixedArray> args = i::Factory::NewFixedArray(argc);
665 for (int i = 0; i < argc; i++) {
666 if (!argv[i].IsEmpty())
667 args->set(i, *Utils::OpenHandle(*argv[i]));
668 }
669 obj->set_args(*args);
670 }
671 return Utils::ToLocal(obj);
672}
673
674
675Local<TypeSwitch> TypeSwitch::New(Handle<FunctionTemplate> type) {
676 Handle<FunctionTemplate> types[1] = { type };
677 return TypeSwitch::New(1, types);
678}
679
680
681Local<TypeSwitch> TypeSwitch::New(int argc, Handle<FunctionTemplate> types[]) {
682 EnsureInitialized("v8::TypeSwitch::New()");
683 LOG_API("TypeSwitch::New");
684 ENTER_V8;
685 i::Handle<i::FixedArray> vector = i::Factory::NewFixedArray(argc);
686 for (int i = 0; i < argc; i++)
687 vector->set(i, *Utils::OpenHandle(*types[i]));
688 i::Handle<i::Struct> struct_obj =
689 i::Factory::NewStruct(i::TYPE_SWITCH_INFO_TYPE);
690 i::Handle<i::TypeSwitchInfo> obj =
691 i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
692 obj->set_types(*vector);
693 return Utils::ToLocal(obj);
694}
695
696
697int TypeSwitch::match(v8::Handle<Value> value) {
698 LOG_API("TypeSwitch::match");
699 i::Handle<i::Object> obj = Utils::OpenHandle(*value);
700 i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
701 i::FixedArray* types = i::FixedArray::cast(info->types());
702 for (int i = 0; i < types->length(); i++) {
703 if (obj->IsInstanceOf(i::FunctionTemplateInfo::cast(types->get(i))))
704 return i + 1;
705 }
706 return 0;
707}
708
709
710void FunctionTemplate::SetCallHandler(InvocationCallback callback,
711 v8::Handle<Value> data) {
712 if (IsDeadCheck("v8::FunctionTemplate::SetCallHandler()")) return;
713 ENTER_V8;
714 HandleScope scope;
715 i::Handle<i::Struct> struct_obj =
716 i::Factory::NewStruct(i::CALL_HANDLER_INFO_TYPE);
717 i::Handle<i::CallHandlerInfo> obj =
718 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
719 obj->set_callback(*FromCData(callback));
720 if (data.IsEmpty()) data = v8::Undefined();
721 obj->set_data(*Utils::OpenHandle(*data));
722 Utils::OpenHandle(this)->set_call_code(*obj);
723}
724
725
726void FunctionTemplate::AddInstancePropertyAccessor(
727 v8::Handle<String> name,
728 AccessorGetter getter,
729 AccessorSetter setter,
730 v8::Handle<Value> data,
731 v8::AccessControl settings,
732 v8::PropertyAttribute attributes) {
733 if (IsDeadCheck("v8::FunctionTemplate::AddInstancePropertyAccessor()")) {
734 return;
735 }
736 ENTER_V8;
737 HandleScope scope;
738 i::Handle<i::AccessorInfo> obj = i::Factory::NewAccessorInfo();
739 ASSERT(getter != NULL);
740 obj->set_getter(*FromCData(getter));
741 obj->set_setter(*FromCData(setter));
742 if (data.IsEmpty()) data = v8::Undefined();
743 obj->set_data(*Utils::OpenHandle(*data));
744 obj->set_name(*Utils::OpenHandle(*name));
745 if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
746 if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
747 if (settings & PROHIBITS_OVERWRITING) obj->set_prohibits_overwriting(true);
748 obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
749
750 i::Handle<i::Object> list(Utils::OpenHandle(this)->property_accessors());
751 if (list->IsUndefined()) {
752 list = NeanderArray().value();
753 Utils::OpenHandle(this)->set_property_accessors(*list);
754 }
755 NeanderArray array(list);
756 array.add(obj);
757}
758
759
760Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
761 if (IsDeadCheck("v8::FunctionTemplate::InstanceTemplate()")
762 || EmptyCheck("v8::FunctionTemplate::InstanceTemplate()", this))
763 return Local<ObjectTemplate>();
764 ENTER_V8;
765 if (Utils::OpenHandle(this)->instance_template()->IsUndefined()) {
766 Local<ObjectTemplate> templ =
767 ObjectTemplate::New(v8::Handle<FunctionTemplate>(this));
768 Utils::OpenHandle(this)->set_instance_template(*Utils::OpenHandle(*templ));
769 }
770 i::Handle<i::ObjectTemplateInfo> result(i::ObjectTemplateInfo::cast(
771 Utils::OpenHandle(this)->instance_template()));
772 return Utils::ToLocal(result);
773}
774
775
776void FunctionTemplate::SetClassName(Handle<String> name) {
777 if (IsDeadCheck("v8::FunctionTemplate::SetClassName()")) return;
778 ENTER_V8;
779 Utils::OpenHandle(this)->set_class_name(*Utils::OpenHandle(*name));
780}
781
782
783void FunctionTemplate::SetHiddenPrototype(bool value) {
784 if (IsDeadCheck("v8::FunctionTemplate::SetHiddenPrototype()")) return;
785 ENTER_V8;
786 Utils::OpenHandle(this)->set_hidden_prototype(value);
787}
788
789
790void FunctionTemplate::SetNamedInstancePropertyHandler(
791 NamedPropertyGetter getter,
792 NamedPropertySetter setter,
793 NamedPropertyQuery query,
794 NamedPropertyDeleter remover,
795 NamedPropertyEnumerator enumerator,
796 Handle<Value> data) {
797 if (IsDeadCheck("v8::FunctionTemplate::SetNamedInstancePropertyHandler()")) {
798 return;
799 }
800 ENTER_V8;
801 HandleScope scope;
802 i::Handle<i::Struct> struct_obj =
803 i::Factory::NewStruct(i::INTERCEPTOR_INFO_TYPE);
804 i::Handle<i::InterceptorInfo> obj =
805 i::Handle<i::InterceptorInfo>::cast(struct_obj);
806 if (getter != 0) obj->set_getter(*FromCData(getter));
807 if (setter != 0) obj->set_setter(*FromCData(setter));
808 if (query != 0) obj->set_query(*FromCData(query));
809 if (remover != 0) obj->set_deleter(*FromCData(remover));
810 if (enumerator != 0) obj->set_enumerator(*FromCData(enumerator));
811 if (data.IsEmpty()) data = v8::Undefined();
812 obj->set_data(*Utils::OpenHandle(*data));
813 Utils::OpenHandle(this)->set_named_property_handler(*obj);
814}
815
816
817void FunctionTemplate::SetIndexedInstancePropertyHandler(
818 IndexedPropertyGetter getter,
819 IndexedPropertySetter setter,
820 IndexedPropertyQuery query,
821 IndexedPropertyDeleter remover,
822 IndexedPropertyEnumerator enumerator,
823 Handle<Value> data) {
824 if (IsDeadCheck(
825 "v8::FunctionTemplate::SetIndexedInstancePropertyHandler()")) {
826 return;
827 }
828 ENTER_V8;
829 HandleScope scope;
830 i::Handle<i::Struct> struct_obj =
831 i::Factory::NewStruct(i::INTERCEPTOR_INFO_TYPE);
832 i::Handle<i::InterceptorInfo> obj =
833 i::Handle<i::InterceptorInfo>::cast(struct_obj);
834 if (getter != 0) obj->set_getter(*FromCData(getter));
835 if (setter != 0) obj->set_setter(*FromCData(setter));
836 if (query != 0) obj->set_query(*FromCData(query));
837 if (remover != 0) obj->set_deleter(*FromCData(remover));
838 if (enumerator != 0) obj->set_enumerator(*FromCData(enumerator));
839 if (data.IsEmpty()) data = v8::Undefined();
840 obj->set_data(*Utils::OpenHandle(*data));
841 Utils::OpenHandle(this)->set_indexed_property_handler(*obj);
842}
843
844
845void FunctionTemplate::SetInstanceCallAsFunctionHandler(
846 InvocationCallback callback,
847 Handle<Value> data) {
848 if (IsDeadCheck("v8::FunctionTemplate::SetInstanceCallAsFunctionHandler()")) {
849 return;
850 }
851 ENTER_V8;
852 HandleScope scope;
853 i::Handle<i::Struct> struct_obj =
854 i::Factory::NewStruct(i::CALL_HANDLER_INFO_TYPE);
855 i::Handle<i::CallHandlerInfo> obj =
856 i::Handle<i::CallHandlerInfo>::cast(struct_obj);
857 obj->set_callback(*FromCData(callback));
858 if (data.IsEmpty()) data = v8::Undefined();
859 obj->set_data(*Utils::OpenHandle(*data));
860 Utils::OpenHandle(this)->set_instance_call_handler(*obj);
861}
862
863
864// --- O b j e c t T e m p l a t e ---
865
866
867Local<ObjectTemplate> ObjectTemplate::New() {
868 return New(Local<FunctionTemplate>());
869}
870
871
872Local<ObjectTemplate> ObjectTemplate::New(
873 v8::Handle<FunctionTemplate> constructor) {
874 if (IsDeadCheck("v8::ObjectTemplate::New()")) return Local<ObjectTemplate>();
875 EnsureInitialized("v8::ObjectTemplate::New()");
876 LOG_API("ObjectTemplate::New");
877 ENTER_V8;
878 i::Handle<i::Struct> struct_obj =
879 i::Factory::NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
880 i::Handle<i::ObjectTemplateInfo> obj =
881 i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
882 InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
883 if (!constructor.IsEmpty())
884 obj->set_constructor(*Utils::OpenHandle(*constructor));
885 obj->set_internal_field_count(i::Smi::FromInt(0));
886 return Utils::ToLocal(obj);
887}
888
889
890// Ensure that the object template has a constructor. If no
891// constructor is available we create one.
892static void EnsureConstructor(ObjectTemplate* object_template) {
893 if (Utils::OpenHandle(object_template)->constructor()->IsUndefined()) {
894 Local<FunctionTemplate> templ = FunctionTemplate::New();
895 i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
896 constructor->set_instance_template(*Utils::OpenHandle(object_template));
897 Utils::OpenHandle(object_template)->set_constructor(*constructor);
898 }
899}
900
901
902void ObjectTemplate::SetAccessor(v8::Handle<String> name,
903 AccessorGetter getter,
904 AccessorSetter setter,
905 v8::Handle<Value> data,
906 AccessControl settings,
907 PropertyAttribute attribute) {
908 if (IsDeadCheck("v8::ObjectTemplate::SetAccessor()")) return;
909 ENTER_V8;
910 HandleScope scope;
911 EnsureConstructor(this);
912 i::FunctionTemplateInfo* constructor =
913 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
914 i::Handle<i::FunctionTemplateInfo> cons(constructor);
915 Utils::ToLocal(cons)->AddInstancePropertyAccessor(name,
916 getter,
917 setter,
918 data,
919 settings,
920 attribute);
921}
922
923
924void ObjectTemplate::SetNamedPropertyHandler(NamedPropertyGetter getter,
925 NamedPropertySetter setter,
926 NamedPropertyQuery query,
927 NamedPropertyDeleter remover,
928 NamedPropertyEnumerator enumerator,
929 Handle<Value> data) {
930 if (IsDeadCheck("v8::ObjectTemplate::SetNamedPropertyHandler()")) return;
931 ENTER_V8;
932 HandleScope scope;
933 EnsureConstructor(this);
934 i::FunctionTemplateInfo* constructor =
935 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
936 i::Handle<i::FunctionTemplateInfo> cons(constructor);
937 Utils::ToLocal(cons)->SetNamedInstancePropertyHandler(getter,
938 setter,
939 query,
940 remover,
941 enumerator,
942 data);
943}
944
945
946void ObjectTemplate::MarkAsUndetectable() {
947 if (IsDeadCheck("v8::ObjectTemplate::MarkAsUndetectable()")) return;
948 ENTER_V8;
949 HandleScope scope;
950 EnsureConstructor(this);
951 i::FunctionTemplateInfo* constructor =
952 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
953 i::Handle<i::FunctionTemplateInfo> cons(constructor);
954 cons->set_undetectable(true);
955}
956
957
958void ObjectTemplate::SetAccessCheckCallbacks(
959 NamedSecurityCallback named_callback,
960 IndexedSecurityCallback indexed_callback,
961 Handle<Value> data,
962 bool turned_on_by_default) {
963 if (IsDeadCheck("v8::ObjectTemplate::SetAccessCheckCallbacks()")) return;
964 ENTER_V8;
965 HandleScope scope;
966 EnsureConstructor(this);
967
968 i::Handle<i::Struct> struct_info =
969 i::Factory::NewStruct(i::ACCESS_CHECK_INFO_TYPE);
970 i::Handle<i::AccessCheckInfo> info =
971 i::Handle<i::AccessCheckInfo>::cast(struct_info);
972 info->set_named_callback(*FromCData(named_callback));
973 info->set_indexed_callback(*FromCData(indexed_callback));
974 if (data.IsEmpty()) data = v8::Undefined();
975 info->set_data(*Utils::OpenHandle(*data));
976
977 i::FunctionTemplateInfo* constructor =
978 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
979 i::Handle<i::FunctionTemplateInfo> cons(constructor);
980 cons->set_access_check_info(*info);
981 cons->set_needs_access_check(turned_on_by_default);
982}
983
984
985void ObjectTemplate::SetIndexedPropertyHandler(
986 IndexedPropertyGetter getter,
987 IndexedPropertySetter setter,
988 IndexedPropertyQuery query,
989 IndexedPropertyDeleter remover,
990 IndexedPropertyEnumerator enumerator,
991 Handle<Value> data) {
992 if (IsDeadCheck("v8::ObjectTemplate::SetIndexedPropertyHandler()")) return;
993 ENTER_V8;
994 HandleScope scope;
995 EnsureConstructor(this);
996 i::FunctionTemplateInfo* constructor =
997 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
998 i::Handle<i::FunctionTemplateInfo> cons(constructor);
999 Utils::ToLocal(cons)->SetIndexedInstancePropertyHandler(getter,
1000 setter,
1001 query,
1002 remover,
1003 enumerator,
1004 data);
1005}
1006
1007
1008void ObjectTemplate::SetCallAsFunctionHandler(InvocationCallback callback,
1009 Handle<Value> data) {
1010 if (IsDeadCheck("v8::ObjectTemplate::SetCallAsFunctionHandler()")) return;
1011 ENTER_V8;
1012 HandleScope scope;
1013 EnsureConstructor(this);
1014 i::FunctionTemplateInfo* constructor =
1015 i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
1016 i::Handle<i::FunctionTemplateInfo> cons(constructor);
1017 Utils::ToLocal(cons)->SetInstanceCallAsFunctionHandler(callback, data);
1018}
1019
1020
1021int ObjectTemplate::InternalFieldCount() {
1022 if (IsDeadCheck("v8::ObjectTemplate::InternalFieldCount()")) {
1023 return 0;
1024 }
1025 return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
1026}
1027
1028
1029void ObjectTemplate::SetInternalFieldCount(int value) {
1030 if (IsDeadCheck("v8::ObjectTemplate::SetInternalFieldCount()")) return;
1031 if (!ApiCheck(i::Smi::IsValid(value),
1032 "v8::ObjectTemplate::SetInternalFieldCount()",
1033 "Invalid internal field count")) {
1034 return;
1035 }
1036 ENTER_V8;
1037 if (value > 0) {
1038 // The internal field count is set by the constructor function's
1039 // construct code, so we ensure that there is a constructor
1040 // function to do the setting.
1041 EnsureConstructor(this);
1042 }
1043 Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
1044}
1045
1046
1047// --- S c r i p t D a t a ---
1048
1049
1050ScriptData* ScriptData::PreCompile(const char* input, int length) {
1051 unibrow::Utf8InputBuffer<> buf(input, length);
1052 return i::PreParse(i::Handle<i::String>(), &buf, NULL);
1053}
1054
1055
1056ScriptData* ScriptData::New(unsigned* data, int length) {
1057 return new i::ScriptDataImpl(i::Vector<unsigned>(data, length));
1058}
1059
1060
1061// --- S c r i p t ---
1062
1063
1064Local<Script> Script::New(v8::Handle<String> source,
1065 v8::ScriptOrigin* origin,
1066 v8::ScriptData* script_data) {
1067 ON_BAILOUT("v8::Script::New()", return Local<Script>());
1068 LOG_API("Script::New");
1069 ENTER_V8;
1070 i::Handle<i::String> str = Utils::OpenHandle(*source);
1071 i::Handle<i::Object> name_obj;
1072 int line_offset = 0;
1073 int column_offset = 0;
1074 if (origin != NULL) {
1075 if (!origin->ResourceName().IsEmpty()) {
1076 name_obj = Utils::OpenHandle(*origin->ResourceName());
1077 }
1078 if (!origin->ResourceLineOffset().IsEmpty()) {
1079 line_offset = static_cast<int>(origin->ResourceLineOffset()->Value());
1080 }
1081 if (!origin->ResourceColumnOffset().IsEmpty()) {
1082 column_offset = static_cast<int>(origin->ResourceColumnOffset()->Value());
1083 }
1084 }
1085 EXCEPTION_PREAMBLE();
1086 i::ScriptDataImpl* pre_data = static_cast<i::ScriptDataImpl*>(script_data);
1087 // We assert that the pre-data is sane, even though we can actually
1088 // handle it if it turns out not to be in release mode.
1089 ASSERT(pre_data == NULL || pre_data->SanityCheck());
1090 // If the pre-data isn't sane we simply ignore it
1091 if (pre_data != NULL && !pre_data->SanityCheck()) {
1092 pre_data = NULL;
1093 }
1094 i::Handle<i::JSFunction> boilerplate = i::Compiler::Compile(str,
1095 name_obj,
1096 line_offset,
1097 column_offset,
1098 NULL,
1099 pre_data);
1100 has_pending_exception = boilerplate.is_null();
1101 EXCEPTION_BAILOUT_CHECK(Local<Script>());
1102 return Local<Script>(ToApi<Script>(boilerplate));
1103}
1104
1105
1106Local<Script> Script::New(v8::Handle<String> source,
1107 v8::Handle<Value> file_name) {
1108 ScriptOrigin origin(file_name);
1109 return New(source, &origin);
1110}
1111
1112
1113Local<Script> Script::Compile(v8::Handle<String> source,
1114 v8::ScriptOrigin* origin,
1115 v8::ScriptData* script_data) {
1116 ON_BAILOUT("v8::Script::Compile()", return Local<Script>());
1117 LOG_API("Script::Compile");
1118 ENTER_V8;
1119 Local<Script> generic = New(source, origin, script_data);
1120 if (generic.IsEmpty())
1121 return generic;
1122 i::Handle<i::JSFunction> boilerplate = Utils::OpenHandle(*generic);
1123 i::Handle<i::JSFunction> result =
1124 i::Factory::NewFunctionFromBoilerplate(boilerplate,
1125 i::Top::global_context());
1126 return Local<Script>(ToApi<Script>(result));
1127}
1128
1129
1130Local<Script> Script::Compile(v8::Handle<String> source,
1131 v8::Handle<Value> file_name) {
1132 ScriptOrigin origin(file_name);
1133 return Compile(source, &origin);
1134}
1135
1136
1137Local<Value> Script::Run() {
1138 ON_BAILOUT("v8::Script::Run()", return Local<Value>());
1139 LOG_API("Script::Run");
1140 ENTER_V8;
1141 i::Object* raw_result = NULL;
1142 {
1143 HandleScope scope;
1144 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
1145 if (fun->IsBoilerplate()) {
1146 fun = i::Factory::NewFunctionFromBoilerplate(fun,
1147 i::Top::global_context());
1148 }
1149 EXCEPTION_PREAMBLE();
1150 i::Handle<i::Object> receiver(i::Top::context()->global_proxy());
1151 i::Handle<i::Object> result =
1152 i::Execution::Call(fun, receiver, 0, NULL, &has_pending_exception);
1153 EXCEPTION_BAILOUT_CHECK(Local<Value>());
1154 raw_result = *result;
1155 }
1156 i::Handle<i::Object> result(raw_result);
1157 return Utils::ToLocal(result);
1158}
1159
1160
1161Local<Value> Script::Id() {
1162 ON_BAILOUT("v8::Script::Id()", return Local<Value>());
1163 LOG_API("Script::Id");
1164 i::Object* raw_id = NULL;
1165 {
1166 HandleScope scope;
1167 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
1168 i::Handle<i::Script> script(i::Script::cast(fun->shared()->script()));
1169 i::Handle<i::Object> id(script->id());
1170 raw_id = *id;
1171 }
1172 i::Handle<i::Object> id(raw_id);
1173 return Utils::ToLocal(id);
1174}
1175
1176
1177void Script::SetData(v8::Handle<Value> data) {
1178 ON_BAILOUT("v8::Script::SetData()", return);
1179 LOG_API("Script::SetData");
1180 {
1181 HandleScope scope;
1182 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
1183 i::Handle<i::Object> raw_data = Utils::OpenHandle(*data);
1184 i::Handle<i::Script> script(i::Script::cast(fun->shared()->script()));
1185 script->set_data(*raw_data);
1186 }
1187}
1188
1189
1190// --- E x c e p t i o n s ---
1191
1192
1193v8::TryCatch::TryCatch()
1194 : next_(i::Top::try_catch_handler()),
1195 exception_(i::Heap::the_hole_value()),
1196 message_(i::Smi::FromInt(0)),
1197 is_verbose_(false),
1198 can_continue_(true),
1199 capture_message_(true),
1200 js_handler_(NULL) {
1201 i::Top::RegisterTryCatchHandler(this);
1202}
1203
1204
1205v8::TryCatch::~TryCatch() {
1206 i::Top::UnregisterTryCatchHandler(this);
1207}
1208
1209
1210bool v8::TryCatch::HasCaught() const {
1211 return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
1212}
1213
1214
1215bool v8::TryCatch::CanContinue() const {
1216 return can_continue_;
1217}
1218
1219
1220v8::Local<Value> v8::TryCatch::Exception() const {
1221 if (HasCaught()) {
1222 // Check for out of memory exception.
1223 i::Object* exception = reinterpret_cast<i::Object*>(exception_);
1224 return v8::Utils::ToLocal(i::Handle<i::Object>(exception));
1225 } else {
1226 return v8::Local<Value>();
1227 }
1228}
1229
1230
1231v8::Local<Value> v8::TryCatch::StackTrace() const {
1232 if (HasCaught()) {
1233 i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
1234 if (!raw_obj->IsJSObject()) return v8::Local<Value>();
1235 v8::HandleScope scope;
1236 i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj));
1237 i::Handle<i::String> name = i::Factory::LookupAsciiSymbol("stack");
1238 if (!obj->HasProperty(*name))
1239 return v8::Local<Value>();
1240 return scope.Close(v8::Utils::ToLocal(i::GetProperty(obj, name)));
1241 } else {
1242 return v8::Local<Value>();
1243 }
1244}
1245
1246
1247v8::Local<v8::Message> v8::TryCatch::Message() const {
1248 if (HasCaught() && message_ != i::Smi::FromInt(0)) {
1249 i::Object* message = reinterpret_cast<i::Object*>(message_);
1250 return v8::Utils::MessageToLocal(i::Handle<i::Object>(message));
1251 } else {
1252 return v8::Local<v8::Message>();
1253 }
1254}
1255
1256
1257void v8::TryCatch::Reset() {
1258 exception_ = i::Heap::the_hole_value();
1259 message_ = i::Smi::FromInt(0);
1260}
1261
1262
1263void v8::TryCatch::SetVerbose(bool value) {
1264 is_verbose_ = value;
1265}
1266
1267
1268void v8::TryCatch::SetCaptureMessage(bool value) {
1269 capture_message_ = value;
1270}
1271
1272
1273// --- M e s s a g e ---
1274
1275
1276Local<String> Message::Get() const {
1277 ON_BAILOUT("v8::Message::Get()", return Local<String>());
1278 ENTER_V8;
1279 HandleScope scope;
1280 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1281 i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(obj);
1282 Local<String> result = Utils::ToLocal(raw_result);
1283 return scope.Close(result);
1284}
1285
1286
1287v8::Handle<Value> Message::GetScriptResourceName() const {
1288 if (IsDeadCheck("v8::Message::GetScriptResourceName()")) {
1289 return Local<String>();
1290 }
1291 ENTER_V8;
1292 HandleScope scope;
1293 i::Handle<i::JSObject> obj =
1294 i::Handle<i::JSObject>::cast(Utils::OpenHandle(this));
1295 // Return this.script.name.
1296 i::Handle<i::JSValue> script =
1297 i::Handle<i::JSValue>::cast(GetProperty(obj, "script"));
1298 i::Handle<i::Object> resource_name(i::Script::cast(script->value())->name());
1299 return scope.Close(Utils::ToLocal(resource_name));
1300}
1301
1302
1303v8::Handle<Value> Message::GetScriptData() const {
1304 if (IsDeadCheck("v8::Message::GetScriptResourceData()")) {
1305 return Local<Value>();
1306 }
1307 ENTER_V8;
1308 HandleScope scope;
1309 i::Handle<i::JSObject> obj =
1310 i::Handle<i::JSObject>::cast(Utils::OpenHandle(this));
1311 // Return this.script.data.
1312 i::Handle<i::JSValue> script =
1313 i::Handle<i::JSValue>::cast(GetProperty(obj, "script"));
1314 i::Handle<i::Object> data(i::Script::cast(script->value())->data());
1315 return scope.Close(Utils::ToLocal(data));
1316}
1317
1318
1319static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1320 i::Handle<i::Object> recv,
1321 int argc,
1322 i::Object** argv[],
1323 bool* has_pending_exception) {
1324 i::Handle<i::String> fmt_str = i::Factory::LookupAsciiSymbol(name);
1325 i::Object* object_fun = i::Top::builtins()->GetProperty(*fmt_str);
1326 i::Handle<i::JSFunction> fun =
1327 i::Handle<i::JSFunction>(i::JSFunction::cast(object_fun));
1328 i::Handle<i::Object> value =
1329 i::Execution::Call(fun, recv, argc, argv, has_pending_exception);
1330 return value;
1331}
1332
1333
1334static i::Handle<i::Object> CallV8HeapFunction(const char* name,
1335 i::Handle<i::Object> data,
1336 bool* has_pending_exception) {
1337 i::Object** argv[1] = { data.location() };
1338 return CallV8HeapFunction(name,
1339 i::Top::builtins(),
1340 1,
1341 argv,
1342 has_pending_exception);
1343}
1344
1345
1346int Message::GetLineNumber() const {
1347 ON_BAILOUT("v8::Message::GetLineNumber()", return -1);
1348 ENTER_V8;
1349 HandleScope scope;
1350 EXCEPTION_PREAMBLE();
1351 i::Handle<i::Object> result = CallV8HeapFunction("GetLineNumber",
1352 Utils::OpenHandle(this),
1353 &has_pending_exception);
1354 EXCEPTION_BAILOUT_CHECK(0);
1355 return static_cast<int>(result->Number());
1356}
1357
1358
1359int Message::GetStartPosition() const {
1360 if (IsDeadCheck("v8::Message::GetStartPosition()")) return 0;
1361 ENTER_V8;
1362 HandleScope scope;
1363
1364 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1365 return static_cast<int>(GetProperty(data_obj, "startPos")->Number());
1366}
1367
1368
1369int Message::GetEndPosition() const {
1370 if (IsDeadCheck("v8::Message::GetEndPosition()")) return 0;
1371 ENTER_V8;
1372 HandleScope scope;
1373 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1374 return static_cast<int>(GetProperty(data_obj, "endPos")->Number());
1375}
1376
1377
1378int Message::GetStartColumn() const {
1379 if (IsDeadCheck("v8::Message::GetStartColumn()")) return 0;
1380 ENTER_V8;
1381 HandleScope scope;
1382 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1383 EXCEPTION_PREAMBLE();
1384 i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1385 "GetPositionInLine",
1386 data_obj,
1387 &has_pending_exception);
1388 EXCEPTION_BAILOUT_CHECK(0);
1389 return static_cast<int>(start_col_obj->Number());
1390}
1391
1392
1393int Message::GetEndColumn() const {
1394 if (IsDeadCheck("v8::Message::GetEndColumn()")) return 0;
1395 ENTER_V8;
1396 HandleScope scope;
1397 i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
1398 EXCEPTION_PREAMBLE();
1399 i::Handle<i::Object> start_col_obj = CallV8HeapFunction(
1400 "GetPositionInLine",
1401 data_obj,
1402 &has_pending_exception);
1403 EXCEPTION_BAILOUT_CHECK(0);
1404 int start = static_cast<int>(GetProperty(data_obj, "startPos")->Number());
1405 int end = static_cast<int>(GetProperty(data_obj, "endPos")->Number());
1406 return static_cast<int>(start_col_obj->Number()) + (end - start);
1407}
1408
1409
1410Local<String> Message::GetSourceLine() const {
1411 ON_BAILOUT("v8::Message::GetSourceLine()", return Local<String>());
1412 ENTER_V8;
1413 HandleScope scope;
1414 EXCEPTION_PREAMBLE();
1415 i::Handle<i::Object> result = CallV8HeapFunction("GetSourceLine",
1416 Utils::OpenHandle(this),
1417 &has_pending_exception);
1418 EXCEPTION_BAILOUT_CHECK(Local<v8::String>());
1419 if (result->IsString()) {
1420 return scope.Close(Utils::ToLocal(i::Handle<i::String>::cast(result)));
1421 } else {
1422 return Local<String>();
1423 }
1424}
1425
1426
1427void Message::PrintCurrentStackTrace(FILE* out) {
1428 if (IsDeadCheck("v8::Message::PrintCurrentStackTrace()")) return;
1429 ENTER_V8;
1430 i::Top::PrintCurrentStackTrace(out);
1431}
1432
1433
1434// --- D a t a ---
1435
1436bool Value::IsUndefined() const {
1437 if (IsDeadCheck("v8::Value::IsUndefined()")) return false;
1438 return Utils::OpenHandle(this)->IsUndefined();
1439}
1440
1441
1442bool Value::IsNull() const {
1443 if (IsDeadCheck("v8::Value::IsNull()")) return false;
1444 return Utils::OpenHandle(this)->IsNull();
1445}
1446
1447
1448bool Value::IsTrue() const {
1449 if (IsDeadCheck("v8::Value::IsTrue()")) return false;
1450 return Utils::OpenHandle(this)->IsTrue();
1451}
1452
1453
1454bool Value::IsFalse() const {
1455 if (IsDeadCheck("v8::Value::IsFalse()")) return false;
1456 return Utils::OpenHandle(this)->IsFalse();
1457}
1458
1459
1460bool Value::IsFunction() const {
1461 if (IsDeadCheck("v8::Value::IsFunction()")) return false;
1462 return Utils::OpenHandle(this)->IsJSFunction();
1463}
1464
1465
1466bool Value::FullIsString() const {
1467 if (IsDeadCheck("v8::Value::IsString()")) return false;
1468 bool result = Utils::OpenHandle(this)->IsString();
1469 ASSERT_EQ(result, QuickIsString());
1470 return result;
1471}
1472
1473
1474bool Value::IsArray() const {
1475 if (IsDeadCheck("v8::Value::IsArray()")) return false;
1476 return Utils::OpenHandle(this)->IsJSArray();
1477}
1478
1479
1480bool Value::IsObject() const {
1481 if (IsDeadCheck("v8::Value::IsObject()")) return false;
1482 return Utils::OpenHandle(this)->IsJSObject();
1483}
1484
1485
1486bool Value::IsNumber() const {
1487 if (IsDeadCheck("v8::Value::IsNumber()")) return false;
1488 return Utils::OpenHandle(this)->IsNumber();
1489}
1490
1491
1492bool Value::IsBoolean() const {
1493 if (IsDeadCheck("v8::Value::IsBoolean()")) return false;
1494 return Utils::OpenHandle(this)->IsBoolean();
1495}
1496
1497
1498bool Value::IsExternal() const {
1499 if (IsDeadCheck("v8::Value::IsExternal()")) return false;
1500 return Utils::OpenHandle(this)->IsProxy();
1501}
1502
1503
1504bool Value::IsInt32() const {
1505 if (IsDeadCheck("v8::Value::IsInt32()")) return false;
1506 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1507 if (obj->IsSmi()) return true;
1508 if (obj->IsNumber()) {
1509 double value = obj->Number();
1510 return i::FastI2D(i::FastD2I(value)) == value;
1511 }
1512 return false;
1513}
1514
1515
1516bool Value::IsDate() const {
1517 if (IsDeadCheck("v8::Value::IsDate()")) return false;
1518 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1519 return obj->HasSpecificClassOf(i::Heap::Date_symbol());
1520}
1521
1522
1523Local<String> Value::ToString() const {
1524 if (IsDeadCheck("v8::Value::ToString()")) return Local<String>();
1525 LOG_API("ToString");
1526 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1527 i::Handle<i::Object> str;
1528 if (obj->IsString()) {
1529 str = obj;
1530 } else {
1531 ENTER_V8;
1532 EXCEPTION_PREAMBLE();
1533 str = i::Execution::ToString(obj, &has_pending_exception);
1534 EXCEPTION_BAILOUT_CHECK(Local<String>());
1535 }
1536 return Local<String>(ToApi<String>(str));
1537}
1538
1539
1540Local<String> Value::ToDetailString() const {
1541 if (IsDeadCheck("v8::Value::ToDetailString()")) return Local<String>();
1542 LOG_API("ToDetailString");
1543 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1544 i::Handle<i::Object> str;
1545 if (obj->IsString()) {
1546 str = obj;
1547 } else {
1548 ENTER_V8;
1549 EXCEPTION_PREAMBLE();
1550 str = i::Execution::ToDetailString(obj, &has_pending_exception);
1551 EXCEPTION_BAILOUT_CHECK(Local<String>());
1552 }
1553 return Local<String>(ToApi<String>(str));
1554}
1555
1556
1557Local<v8::Object> Value::ToObject() const {
1558 if (IsDeadCheck("v8::Value::ToObject()")) return Local<v8::Object>();
1559 LOG_API("ToObject");
1560 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1561 i::Handle<i::Object> val;
1562 if (obj->IsJSObject()) {
1563 val = obj;
1564 } else {
1565 ENTER_V8;
1566 EXCEPTION_PREAMBLE();
1567 val = i::Execution::ToObject(obj, &has_pending_exception);
1568 EXCEPTION_BAILOUT_CHECK(Local<v8::Object>());
1569 }
1570 return Local<v8::Object>(ToApi<Object>(val));
1571}
1572
1573
1574Local<Boolean> Value::ToBoolean() const {
1575 if (IsDeadCheck("v8::Value::ToBoolean()")) return Local<Boolean>();
1576 LOG_API("ToBoolean");
1577 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1578 if (obj->IsBoolean()) {
1579 return Local<Boolean>(ToApi<Boolean>(obj));
1580 } else {
1581 ENTER_V8;
1582 i::Handle<i::Object> val = i::Execution::ToBoolean(obj);
1583 return Local<Boolean>(ToApi<Boolean>(val));
1584 }
1585}
1586
1587
1588Local<Number> Value::ToNumber() const {
1589 if (IsDeadCheck("v8::Value::ToNumber()")) return Local<Number>();
1590 LOG_API("ToNumber");
1591 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1592 i::Handle<i::Object> num;
1593 if (obj->IsNumber()) {
1594 num = obj;
1595 } else {
1596 ENTER_V8;
1597 EXCEPTION_PREAMBLE();
1598 num = i::Execution::ToNumber(obj, &has_pending_exception);
1599 EXCEPTION_BAILOUT_CHECK(Local<Number>());
1600 }
1601 return Local<Number>(ToApi<Number>(num));
1602}
1603
1604
1605Local<Integer> Value::ToInteger() const {
1606 if (IsDeadCheck("v8::Value::ToInteger()")) return Local<Integer>();
1607 LOG_API("ToInteger");
1608 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1609 i::Handle<i::Object> num;
1610 if (obj->IsSmi()) {
1611 num = obj;
1612 } else {
1613 ENTER_V8;
1614 EXCEPTION_PREAMBLE();
1615 num = i::Execution::ToInteger(obj, &has_pending_exception);
1616 EXCEPTION_BAILOUT_CHECK(Local<Integer>());
1617 }
1618 return Local<Integer>(ToApi<Integer>(num));
1619}
1620
1621
1622void External::CheckCast(v8::Value* that) {
1623 if (IsDeadCheck("v8::External::Cast()")) return;
1624 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1625 ApiCheck(obj->IsProxy(),
1626 "v8::External::Cast()",
1627 "Could not convert to external");
1628}
1629
1630
1631void v8::Object::CheckCast(Value* that) {
1632 if (IsDeadCheck("v8::Object::Cast()")) return;
1633 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1634 ApiCheck(obj->IsJSObject(),
1635 "v8::Object::Cast()",
1636 "Could not convert to object");
1637}
1638
1639
1640void v8::Function::CheckCast(Value* that) {
1641 if (IsDeadCheck("v8::Function::Cast()")) return;
1642 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1643 ApiCheck(obj->IsJSFunction(),
1644 "v8::Function::Cast()",
1645 "Could not convert to function");
1646}
1647
1648
1649void v8::String::CheckCast(v8::Value* that) {
1650 if (IsDeadCheck("v8::String::Cast()")) return;
1651 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1652 ApiCheck(obj->IsString(),
1653 "v8::String::Cast()",
1654 "Could not convert to string");
1655}
1656
1657
1658void v8::Number::CheckCast(v8::Value* that) {
1659 if (IsDeadCheck("v8::Number::Cast()")) return;
1660 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1661 ApiCheck(obj->IsNumber(),
1662 "v8::Number::Cast()",
1663 "Could not convert to number");
1664}
1665
1666
1667void v8::Integer::CheckCast(v8::Value* that) {
1668 if (IsDeadCheck("v8::Integer::Cast()")) return;
1669 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1670 ApiCheck(obj->IsNumber(),
1671 "v8::Integer::Cast()",
1672 "Could not convert to number");
1673}
1674
1675
1676void v8::Array::CheckCast(Value* that) {
1677 if (IsDeadCheck("v8::Array::Cast()")) return;
1678 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1679 ApiCheck(obj->IsJSArray(),
1680 "v8::Array::Cast()",
1681 "Could not convert to array");
1682}
1683
1684
1685void v8::Date::CheckCast(v8::Value* that) {
1686 if (IsDeadCheck("v8::Date::Cast()")) return;
1687 i::Handle<i::Object> obj = Utils::OpenHandle(that);
1688 ApiCheck(obj->HasSpecificClassOf(i::Heap::Date_symbol()),
1689 "v8::Date::Cast()",
1690 "Could not convert to date");
1691}
1692
1693
1694bool Value::BooleanValue() const {
1695 if (IsDeadCheck("v8::Value::BooleanValue()")) return false;
1696 LOG_API("BooleanValue");
1697 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1698 if (obj->IsBoolean()) {
1699 return obj->IsTrue();
1700 } else {
1701 ENTER_V8;
1702 i::Handle<i::Object> value = i::Execution::ToBoolean(obj);
1703 return value->IsTrue();
1704 }
1705}
1706
1707
1708double Value::NumberValue() const {
1709 if (IsDeadCheck("v8::Value::NumberValue()")) return i::OS::nan_value();
1710 LOG_API("NumberValue");
1711 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1712 i::Handle<i::Object> num;
1713 if (obj->IsNumber()) {
1714 num = obj;
1715 } else {
1716 ENTER_V8;
1717 EXCEPTION_PREAMBLE();
1718 num = i::Execution::ToNumber(obj, &has_pending_exception);
1719 EXCEPTION_BAILOUT_CHECK(i::OS::nan_value());
1720 }
1721 return num->Number();
1722}
1723
1724
1725int64_t Value::IntegerValue() const {
1726 if (IsDeadCheck("v8::Value::IntegerValue()")) return 0;
1727 LOG_API("IntegerValue");
1728 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1729 i::Handle<i::Object> num;
1730 if (obj->IsNumber()) {
1731 num = obj;
1732 } else {
1733 ENTER_V8;
1734 EXCEPTION_PREAMBLE();
1735 num = i::Execution::ToInteger(obj, &has_pending_exception);
1736 EXCEPTION_BAILOUT_CHECK(0);
1737 }
1738 if (num->IsSmi()) {
1739 return i::Smi::cast(*num)->value();
1740 } else {
1741 return static_cast<int64_t>(num->Number());
1742 }
1743}
1744
1745
1746Local<Int32> Value::ToInt32() const {
1747 if (IsDeadCheck("v8::Value::ToInt32()")) return Local<Int32>();
1748 LOG_API("ToInt32");
1749 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1750 i::Handle<i::Object> num;
1751 if (obj->IsSmi()) {
1752 num = obj;
1753 } else {
1754 ENTER_V8;
1755 EXCEPTION_PREAMBLE();
1756 num = i::Execution::ToInt32(obj, &has_pending_exception);
1757 EXCEPTION_BAILOUT_CHECK(Local<Int32>());
1758 }
1759 return Local<Int32>(ToApi<Int32>(num));
1760}
1761
1762
1763Local<Uint32> Value::ToUint32() const {
1764 if (IsDeadCheck("v8::Value::ToUint32()")) return Local<Uint32>();
1765 LOG_API("ToUInt32");
1766 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1767 i::Handle<i::Object> num;
1768 if (obj->IsSmi()) {
1769 num = obj;
1770 } else {
1771 ENTER_V8;
1772 EXCEPTION_PREAMBLE();
1773 num = i::Execution::ToUint32(obj, &has_pending_exception);
1774 EXCEPTION_BAILOUT_CHECK(Local<Uint32>());
1775 }
1776 return Local<Uint32>(ToApi<Uint32>(num));
1777}
1778
1779
1780Local<Uint32> Value::ToArrayIndex() const {
1781 if (IsDeadCheck("v8::Value::ToArrayIndex()")) return Local<Uint32>();
1782 LOG_API("ToArrayIndex");
1783 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1784 if (obj->IsSmi()) {
1785 if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
1786 return Local<Uint32>();
1787 }
1788 ENTER_V8;
1789 EXCEPTION_PREAMBLE();
1790 i::Handle<i::Object> string_obj =
1791 i::Execution::ToString(obj, &has_pending_exception);
1792 EXCEPTION_BAILOUT_CHECK(Local<Uint32>());
1793 i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
1794 uint32_t index;
1795 if (str->AsArrayIndex(&index)) {
1796 i::Handle<i::Object> value;
1797 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
1798 value = i::Handle<i::Object>(i::Smi::FromInt(index));
1799 } else {
1800 value = i::Factory::NewNumber(index);
1801 }
1802 return Utils::Uint32ToLocal(value);
1803 }
1804 return Local<Uint32>();
1805}
1806
1807
1808int32_t Value::Int32Value() const {
1809 if (IsDeadCheck("v8::Value::Int32Value()")) return 0;
1810 LOG_API("Int32Value");
1811 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1812 if (obj->IsSmi()) {
1813 return i::Smi::cast(*obj)->value();
1814 } else {
1815 LOG_API("Int32Value (slow)");
1816 ENTER_V8;
1817 EXCEPTION_PREAMBLE();
1818 i::Handle<i::Object> num =
1819 i::Execution::ToInt32(obj, &has_pending_exception);
1820 EXCEPTION_BAILOUT_CHECK(0);
1821 if (num->IsSmi()) {
1822 return i::Smi::cast(*num)->value();
1823 } else {
1824 return static_cast<int32_t>(num->Number());
1825 }
1826 }
1827}
1828
1829
1830bool Value::Equals(Handle<Value> that) const {
1831 if (IsDeadCheck("v8::Value::Equals()")
1832 || EmptyCheck("v8::Value::Equals()", this)
1833 || EmptyCheck("v8::Value::Equals()", that)) {
1834 return false;
1835 }
1836 LOG_API("Equals");
1837 ENTER_V8;
1838 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1839 i::Handle<i::Object> other = Utils::OpenHandle(*that);
1840 i::Object** args[1] = { other.location() };
1841 EXCEPTION_PREAMBLE();
1842 i::Handle<i::Object> result =
1843 CallV8HeapFunction("EQUALS", obj, 1, args, &has_pending_exception);
1844 EXCEPTION_BAILOUT_CHECK(false);
1845 return *result == i::Smi::FromInt(i::EQUAL);
1846}
1847
1848
1849bool Value::StrictEquals(Handle<Value> that) const {
1850 if (IsDeadCheck("v8::Value::StrictEquals()")
1851 || EmptyCheck("v8::Value::StrictEquals()", this)
1852 || EmptyCheck("v8::Value::StrictEquals()", that)) {
1853 return false;
1854 }
1855 LOG_API("StrictEquals");
1856 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1857 i::Handle<i::Object> other = Utils::OpenHandle(*that);
1858 // Must check HeapNumber first, since NaN !== NaN.
1859 if (obj->IsHeapNumber()) {
1860 if (!other->IsNumber()) return false;
1861 double x = obj->Number();
1862 double y = other->Number();
1863 // Must check explicitly for NaN:s on Windows, but -0 works fine.
1864 return x == y && !isnan(x) && !isnan(y);
1865 } else if (*obj == *other) { // Also covers Booleans.
1866 return true;
1867 } else if (obj->IsSmi()) {
1868 return other->IsNumber() && obj->Number() == other->Number();
1869 } else if (obj->IsString()) {
1870 return other->IsString() &&
1871 i::String::cast(*obj)->Equals(i::String::cast(*other));
1872 } else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
1873 return other->IsUndefined() || other->IsUndetectableObject();
1874 } else {
1875 return false;
1876 }
1877}
1878
1879
1880uint32_t Value::Uint32Value() const {
1881 if (IsDeadCheck("v8::Value::Uint32Value()")) return 0;
1882 LOG_API("Uint32Value");
1883 i::Handle<i::Object> obj = Utils::OpenHandle(this);
1884 if (obj->IsSmi()) {
1885 return i::Smi::cast(*obj)->value();
1886 } else {
1887 ENTER_V8;
1888 EXCEPTION_PREAMBLE();
1889 i::Handle<i::Object> num =
1890 i::Execution::ToUint32(obj, &has_pending_exception);
1891 EXCEPTION_BAILOUT_CHECK(0);
1892 if (num->IsSmi()) {
1893 return i::Smi::cast(*num)->value();
1894 } else {
1895 return static_cast<uint32_t>(num->Number());
1896 }
1897 }
1898}
1899
1900
1901bool v8::Object::Set(v8::Handle<Value> key, v8::Handle<Value> value,
1902 v8::PropertyAttribute attribs) {
1903 ON_BAILOUT("v8::Object::Set()", return false);
1904 ENTER_V8;
1905 HandleScope scope;
1906 i::Handle<i::Object> self = Utils::OpenHandle(this);
1907 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
1908 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
1909 EXCEPTION_PREAMBLE();
1910 i::Handle<i::Object> obj = i::SetProperty(
1911 self,
1912 key_obj,
1913 value_obj,
1914 static_cast<PropertyAttributes>(attribs));
1915 has_pending_exception = obj.is_null();
1916 EXCEPTION_BAILOUT_CHECK(false);
1917 return true;
1918}
1919
1920
1921bool v8::Object::ForceSet(v8::Handle<Value> key,
1922 v8::Handle<Value> value,
1923 v8::PropertyAttribute attribs) {
1924 ON_BAILOUT("v8::Object::ForceSet()", return false);
1925 ENTER_V8;
1926 HandleScope scope;
1927 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
1928 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
1929 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
1930 EXCEPTION_PREAMBLE();
1931 i::Handle<i::Object> obj = i::ForceSetProperty(
1932 self,
1933 key_obj,
1934 value_obj,
1935 static_cast<PropertyAttributes>(attribs));
1936 has_pending_exception = obj.is_null();
1937 EXCEPTION_BAILOUT_CHECK(false);
1938 return true;
1939}
1940
1941
1942bool v8::Object::ForceDelete(v8::Handle<Value> key) {
1943 ON_BAILOUT("v8::Object::ForceDelete()", return false);
1944 ENTER_V8;
1945 HandleScope scope;
1946 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
1947 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
1948 EXCEPTION_PREAMBLE();
1949 i::Handle<i::Object> obj = i::ForceDeleteProperty(self, key_obj);
1950 has_pending_exception = obj.is_null();
1951 EXCEPTION_BAILOUT_CHECK(false);
1952 return obj->IsTrue();
1953}
1954
1955
1956Local<Value> v8::Object::Get(v8::Handle<Value> key) {
1957 ON_BAILOUT("v8::Object::Get()", return Local<v8::Value>());
1958 ENTER_V8;
1959 i::Handle<i::Object> self = Utils::OpenHandle(this);
1960 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
1961 EXCEPTION_PREAMBLE();
1962 i::Handle<i::Object> result = i::GetProperty(self, key_obj);
1963 has_pending_exception = result.is_null();
1964 EXCEPTION_BAILOUT_CHECK(Local<Value>());
1965 return Utils::ToLocal(result);
1966}
1967
1968
1969Local<Value> v8::Object::GetPrototype() {
1970 ON_BAILOUT("v8::Object::GetPrototype()", return Local<v8::Value>());
1971 ENTER_V8;
1972 i::Handle<i::Object> self = Utils::OpenHandle(this);
1973 i::Handle<i::Object> result = i::GetPrototype(self);
1974 return Utils::ToLocal(result);
1975}
1976
1977
1978Local<Object> v8::Object::FindInstanceInPrototypeChain(
1979 v8::Handle<FunctionTemplate> tmpl) {
1980 ON_BAILOUT("v8::Object::FindInstanceInPrototypeChain()",
1981 return Local<v8::Object>());
1982 ENTER_V8;
1983 i::JSObject* object = *Utils::OpenHandle(this);
1984 i::FunctionTemplateInfo* tmpl_info = *Utils::OpenHandle(*tmpl);
1985 while (!object->IsInstanceOf(tmpl_info)) {
1986 i::Object* prototype = object->GetPrototype();
1987 if (!prototype->IsJSObject()) return Local<Object>();
1988 object = i::JSObject::cast(prototype);
1989 }
1990 return Utils::ToLocal(i::Handle<i::JSObject>(object));
1991}
1992
1993
1994Local<Array> v8::Object::GetPropertyNames() {
1995 ON_BAILOUT("v8::Object::GetPropertyNames()", return Local<v8::Array>());
1996 ENTER_V8;
1997 v8::HandleScope scope;
1998 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
1999 i::Handle<i::FixedArray> value =
2000 i::GetKeysInFixedArrayFor(self, i::INCLUDE_PROTOS);
2001 // Because we use caching to speed up enumeration it is important
2002 // to never change the result of the basic enumeration function so
2003 // we clone the result.
2004 i::Handle<i::FixedArray> elms = i::Factory::CopyFixedArray(value);
2005 i::Handle<i::JSArray> result = i::Factory::NewJSArrayWithElements(elms);
2006 return scope.Close(Utils::ToLocal(result));
2007}
2008
2009
2010Local<String> v8::Object::ObjectProtoToString() {
2011 ON_BAILOUT("v8::Object::ObjectProtoToString()", return Local<v8::String>());
2012 ENTER_V8;
2013 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2014
2015 i::Handle<i::Object> name(self->class_name());
2016
2017 // Native implementation of Object.prototype.toString (v8natives.js):
2018 // var c = %ClassOf(this);
2019 // if (c === 'Arguments') c = 'Object';
2020 // return "[object " + c + "]";
2021
2022 if (!name->IsString()) {
2023 return v8::String::New("[object ]");
2024
2025 } else {
2026 i::Handle<i::String> class_name = i::Handle<i::String>::cast(name);
2027 if (class_name->IsEqualTo(i::CStrVector("Arguments"))) {
2028 return v8::String::New("[object Object]");
2029
2030 } else {
2031 const char* prefix = "[object ";
2032 Local<String> str = Utils::ToLocal(class_name);
2033 const char* postfix = "]";
2034
2035 size_t prefix_len = strlen(prefix);
2036 size_t str_len = str->Length();
2037 size_t postfix_len = strlen(postfix);
2038
2039 size_t buf_len = prefix_len + str_len + postfix_len;
2040 char* buf = i::NewArray<char>(buf_len);
2041
2042 // Write prefix.
2043 char* ptr = buf;
2044 memcpy(ptr, prefix, prefix_len * v8::internal::kCharSize);
2045 ptr += prefix_len;
2046
2047 // Write real content.
2048 str->WriteAscii(ptr, 0, str_len);
2049 ptr += str_len;
2050
2051 // Write postfix.
2052 memcpy(ptr, postfix, postfix_len * v8::internal::kCharSize);
2053
2054 // Copy the buffer into a heap-allocated string and return it.
2055 Local<String> result = v8::String::New(buf, buf_len);
2056 i::DeleteArray(buf);
2057 return result;
2058 }
2059 }
2060}
2061
2062
2063bool v8::Object::Delete(v8::Handle<String> key) {
2064 ON_BAILOUT("v8::Object::Delete()", return false);
2065 ENTER_V8;
2066 HandleScope scope;
2067 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2068 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
2069 return i::DeleteProperty(self, key_obj)->IsTrue();
2070}
2071
2072
2073bool v8::Object::Has(v8::Handle<String> key) {
2074 ON_BAILOUT("v8::Object::Has()", return false);
2075 ENTER_V8;
2076 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2077 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
2078 return self->HasProperty(*key_obj);
2079}
2080
2081
2082bool v8::Object::Delete(uint32_t index) {
2083 ON_BAILOUT("v8::Object::DeleteProperty()", return false);
2084 ENTER_V8;
2085 HandleScope scope;
2086 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2087 return i::DeleteElement(self, index)->IsTrue();
2088}
2089
2090
2091bool v8::Object::Has(uint32_t index) {
2092 ON_BAILOUT("v8::Object::HasProperty()", return false);
2093 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2094 return self->HasElement(index);
2095}
2096
2097
2098bool v8::Object::HasRealNamedProperty(Handle<String> key) {
2099 ON_BAILOUT("v8::Object::HasRealNamedProperty()", return false);
2100 return Utils::OpenHandle(this)->HasRealNamedProperty(
2101 *Utils::OpenHandle(*key));
2102}
2103
2104
2105bool v8::Object::HasRealIndexedProperty(uint32_t index) {
2106 ON_BAILOUT("v8::Object::HasRealIndexedProperty()", return false);
2107 return Utils::OpenHandle(this)->HasRealElementProperty(index);
2108}
2109
2110
2111bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
2112 ON_BAILOUT("v8::Object::HasRealNamedCallbackProperty()", return false);
2113 ENTER_V8;
2114 return Utils::OpenHandle(this)->HasRealNamedCallbackProperty(
2115 *Utils::OpenHandle(*key));
2116}
2117
2118
2119bool v8::Object::HasNamedLookupInterceptor() {
2120 ON_BAILOUT("v8::Object::HasNamedLookupInterceptor()", return false);
2121 return Utils::OpenHandle(this)->HasNamedInterceptor();
2122}
2123
2124
2125bool v8::Object::HasIndexedLookupInterceptor() {
2126 ON_BAILOUT("v8::Object::HasIndexedLookupInterceptor()", return false);
2127 return Utils::OpenHandle(this)->HasIndexedInterceptor();
2128}
2129
2130
2131Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
2132 Handle<String> key) {
2133 ON_BAILOUT("v8::Object::GetRealNamedPropertyInPrototypeChain()",
2134 return Local<Value>());
2135 ENTER_V8;
2136 i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
2137 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
2138 i::LookupResult lookup;
2139 self_obj->LookupRealNamedPropertyInPrototypes(*key_obj, &lookup);
2140 if (lookup.IsValid()) {
2141 PropertyAttributes attributes;
2142 i::Handle<i::Object> result(self_obj->GetProperty(*self_obj,
2143 &lookup,
2144 *key_obj,
2145 &attributes));
2146 return Utils::ToLocal(result);
2147 }
2148 return Local<Value>(); // No real property was found in prototype chain.
2149}
2150
2151
2152Local<Value> v8::Object::GetRealNamedProperty(Handle<String> key) {
2153 ON_BAILOUT("v8::Object::GetRealNamedProperty()", return Local<Value>());
2154 ENTER_V8;
2155 i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
2156 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
2157 i::LookupResult lookup;
2158 self_obj->LookupRealNamedProperty(*key_obj, &lookup);
2159 if (lookup.IsValid()) {
2160 PropertyAttributes attributes;
2161 i::Handle<i::Object> result(self_obj->GetProperty(*self_obj,
2162 &lookup,
2163 *key_obj,
2164 &attributes));
2165 return Utils::ToLocal(result);
2166 }
2167 return Local<Value>(); // No real property was found in prototype chain.
2168}
2169
2170
2171// Turns on access checks by copying the map and setting the check flag.
2172// Because the object gets a new map, existing inline cache caching
2173// the old map of this object will fail.
2174void v8::Object::TurnOnAccessCheck() {
2175 ON_BAILOUT("v8::Object::TurnOnAccessCheck()", return);
2176 ENTER_V8;
2177 HandleScope scope;
2178 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2179
2180 i::Handle<i::Map> new_map =
2181 i::Factory::CopyMapDropTransitions(i::Handle<i::Map>(obj->map()));
2182 new_map->set_is_access_check_needed(true);
2183 obj->set_map(*new_map);
2184}
2185
2186
2187bool v8::Object::IsDirty() {
2188 return Utils::OpenHandle(this)->IsDirty();
2189}
2190
2191
2192Local<v8::Object> v8::Object::Clone() {
2193 ON_BAILOUT("v8::Object::Clone()", return Local<Object>());
2194 ENTER_V8;
2195 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2196 EXCEPTION_PREAMBLE();
2197 i::Handle<i::JSObject> result = i::Copy(self);
2198 has_pending_exception = result.is_null();
2199 EXCEPTION_BAILOUT_CHECK(Local<Object>());
2200 return Utils::ToLocal(result);
2201}
2202
2203
2204int v8::Object::GetIdentityHash() {
2205 ON_BAILOUT("v8::Object::GetIdentityHash()", return 0);
2206 ENTER_V8;
2207 HandleScope scope;
2208 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2209 i::Handle<i::Object> hidden_props(i::GetHiddenProperties(self, true));
2210 i::Handle<i::Object> hash_symbol = i::Factory::identity_hash_symbol();
2211 i::Handle<i::Object> hash = i::GetProperty(hidden_props, hash_symbol);
2212 int hash_value;
2213 if (hash->IsSmi()) {
2214 hash_value = i::Smi::cast(*hash)->value();
2215 } else {
2216 int attempts = 0;
2217 do {
2218 // Generate a random 32-bit hash value but limit range to fit
2219 // within a smi.
2220 hash_value = i::V8::Random() & i::Smi::kMaxValue;
2221 attempts++;
2222 } while (hash_value == 0 && attempts < 30);
2223 hash_value = hash_value != 0 ? hash_value : 1; // never return 0
2224 i::SetProperty(hidden_props,
2225 hash_symbol,
2226 i::Handle<i::Object>(i::Smi::FromInt(hash_value)),
2227 static_cast<PropertyAttributes>(None));
2228 }
2229 return hash_value;
2230}
2231
2232
2233bool v8::Object::SetHiddenValue(v8::Handle<v8::String> key,
2234 v8::Handle<v8::Value> value) {
2235 ON_BAILOUT("v8::Object::SetHiddenValue()", return false);
2236 ENTER_V8;
2237 HandleScope scope;
2238 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2239 i::Handle<i::Object> hidden_props(i::GetHiddenProperties(self, true));
2240 i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
2241 i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
2242 EXCEPTION_PREAMBLE();
2243 i::Handle<i::Object> obj = i::SetProperty(
2244 hidden_props,
2245 key_obj,
2246 value_obj,
2247 static_cast<PropertyAttributes>(None));
2248 has_pending_exception = obj.is_null();
2249 EXCEPTION_BAILOUT_CHECK(false);
2250 return true;
2251}
2252
2253
2254v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Handle<v8::String> key) {
2255 ON_BAILOUT("v8::Object::GetHiddenValue()", return Local<v8::Value>());
2256 ENTER_V8;
2257 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2258 i::Handle<i::Object> hidden_props(i::GetHiddenProperties(self, false));
2259 if (hidden_props->IsUndefined()) {
2260 return v8::Local<v8::Value>();
2261 }
2262 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
2263 EXCEPTION_PREAMBLE();
2264 i::Handle<i::Object> result = i::GetProperty(hidden_props, key_obj);
2265 has_pending_exception = result.is_null();
2266 EXCEPTION_BAILOUT_CHECK(v8::Local<v8::Value>());
2267 if (result->IsUndefined()) {
2268 return v8::Local<v8::Value>();
2269 }
2270 return Utils::ToLocal(result);
2271}
2272
2273
2274bool v8::Object::DeleteHiddenValue(v8::Handle<v8::String> key) {
2275 ON_BAILOUT("v8::DeleteHiddenValue()", return false);
2276 ENTER_V8;
2277 HandleScope scope;
2278 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2279 i::Handle<i::Object> hidden_props(i::GetHiddenProperties(self, false));
2280 if (hidden_props->IsUndefined()) {
2281 return true;
2282 }
2283 i::Handle<i::JSObject> js_obj(i::JSObject::cast(*hidden_props));
2284 i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
2285 return i::DeleteProperty(js_obj, key_obj)->IsTrue();
2286}
2287
2288
2289void v8::Object::SetIndexedPropertiesToPixelData(uint8_t* data, int length) {
2290 ON_BAILOUT("v8::SetElementsToPixelData()", return);
2291 ENTER_V8;
2292 HandleScope scope;
2293 if (!ApiCheck(i::Smi::IsValid(length),
2294 "v8::Object::SetIndexedPropertiesToPixelData()",
2295 "length exceeds max acceptable value")) {
2296 return;
2297 }
2298 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2299 if (!ApiCheck(!self->IsJSArray(),
2300 "v8::Object::SetIndexedPropertiesToPixelData()",
2301 "JSArray is not supported")) {
2302 return;
2303 }
2304 i::Handle<i::PixelArray> pixels = i::Factory::NewPixelArray(length, data);
2305 self->set_elements(*pixels);
2306}
2307
2308
2309Local<v8::Object> Function::NewInstance() const {
2310 return NewInstance(0, NULL);
2311}
2312
2313
2314Local<v8::Object> Function::NewInstance(int argc,
2315 v8::Handle<v8::Value> argv[]) const {
2316 ON_BAILOUT("v8::Function::NewInstance()", return Local<v8::Object>());
2317 LOG_API("Function::NewInstance");
2318 ENTER_V8;
2319 HandleScope scope;
2320 i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
2321 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
2322 i::Object*** args = reinterpret_cast<i::Object***>(argv);
2323 EXCEPTION_PREAMBLE();
2324 i::Handle<i::Object> returned =
2325 i::Execution::New(function, argc, args, &has_pending_exception);
2326 EXCEPTION_BAILOUT_CHECK(Local<v8::Object>());
2327 return scope.Close(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
2328}
2329
2330
2331Local<v8::Value> Function::Call(v8::Handle<v8::Object> recv, int argc,
2332 v8::Handle<v8::Value> argv[]) {
2333 ON_BAILOUT("v8::Function::Call()", return Local<v8::Value>());
2334 LOG_API("Function::Call");
2335 ENTER_V8;
2336 i::Object* raw_result = NULL;
2337 {
2338 HandleScope scope;
2339 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
2340 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
2341 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
2342 i::Object*** args = reinterpret_cast<i::Object***>(argv);
2343 EXCEPTION_PREAMBLE();
2344 i::Handle<i::Object> returned =
2345 i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
2346 EXCEPTION_BAILOUT_CHECK(Local<Object>());
2347 raw_result = *returned;
2348 }
2349 i::Handle<i::Object> result(raw_result);
2350 return Utils::ToLocal(result);
2351}
2352
2353
2354void Function::SetName(v8::Handle<v8::String> name) {
2355 ENTER_V8;
2356 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
2357 func->shared()->set_name(*Utils::OpenHandle(*name));
2358}
2359
2360
2361Handle<Value> Function::GetName() const {
2362 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
2363 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name()));
2364}
2365
2366
2367int String::Length() const {
2368 if (IsDeadCheck("v8::String::Length()")) return 0;
2369 return Utils::OpenHandle(this)->length();
2370}
2371
2372
2373int String::Utf8Length() const {
2374 if (IsDeadCheck("v8::String::Utf8Length()")) return 0;
2375 return Utils::OpenHandle(this)->Utf8Length();
2376}
2377
2378
2379int String::WriteUtf8(char* buffer, int capacity) const {
2380 if (IsDeadCheck("v8::String::WriteUtf8()")) return 0;
2381 LOG_API("String::WriteUtf8");
2382 ENTER_V8;
2383 i::Handle<i::String> str = Utils::OpenHandle(this);
2384 write_input_buffer.Reset(0, *str);
2385 int len = str->length();
2386 // Encode the first K - 3 bytes directly into the buffer since we
2387 // know there's room for them. If no capacity is given we copy all
2388 // of them here.
2389 int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
2390 int i;
2391 int pos = 0;
2392 for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
2393 i::uc32 c = write_input_buffer.GetNext();
2394 int written = unibrow::Utf8::Encode(buffer + pos, c);
2395 pos += written;
2396 }
2397 if (i < len) {
2398 // For the last characters we need to check the length for each one
2399 // because they may be longer than the remaining space in the
2400 // buffer.
2401 char intermediate[unibrow::Utf8::kMaxEncodedSize];
2402 for (; i < len && pos < capacity; i++) {
2403 i::uc32 c = write_input_buffer.GetNext();
2404 int written = unibrow::Utf8::Encode(intermediate, c);
2405 if (pos + written <= capacity) {
2406 for (int j = 0; j < written; j++)
2407 buffer[pos + j] = intermediate[j];
2408 pos += written;
2409 } else {
2410 // We've reached the end of the buffer
2411 break;
2412 }
2413 }
2414 }
2415 if (i == len && (capacity == -1 || pos < capacity))
2416 buffer[pos++] = '\0';
2417 return pos;
2418}
2419
2420
2421int String::WriteAscii(char* buffer, int start, int length) const {
2422 if (IsDeadCheck("v8::String::WriteAscii()")) return 0;
2423 LOG_API("String::WriteAscii");
2424 ENTER_V8;
2425 ASSERT(start >= 0 && length >= -1);
2426 i::Handle<i::String> str = Utils::OpenHandle(this);
2427 // Flatten the string for efficiency. This applies whether we are
2428 // using StringInputBuffer or Get(i) to access the characters.
2429 str->TryFlattenIfNotFlat();
2430 int end = length;
2431 if ( (length == -1) || (length > str->length() - start) )
2432 end = str->length() - start;
2433 if (end < 0) return 0;
2434 write_input_buffer.Reset(start, *str);
2435 int i;
2436 for (i = 0; i < end; i++) {
2437 char c = static_cast<char>(write_input_buffer.GetNext());
2438 if (c == '\0') c = ' ';
2439 buffer[i] = c;
2440 }
2441 if (length == -1 || i < length)
2442 buffer[i] = '\0';
2443 return i;
2444}
2445
2446
2447int String::Write(uint16_t* buffer, int start, int length) const {
2448 if (IsDeadCheck("v8::String::Write()")) return 0;
2449 LOG_API("String::Write");
2450 ENTER_V8;
2451 ASSERT(start >= 0 && length >= -1);
2452 i::Handle<i::String> str = Utils::OpenHandle(this);
2453 int end = length;
2454 if ( (length == -1) || (length > str->length() - start) )
2455 end = str->length() - start;
2456 if (end < 0) return 0;
2457 i::String::WriteToFlat(*str, buffer, start, end);
2458 if (length == -1 || end < length)
2459 buffer[end] = '\0';
2460 return end;
2461}
2462
2463
2464bool v8::String::IsExternal() const {
2465 EnsureInitialized("v8::String::IsExternal()");
2466 i::Handle<i::String> str = Utils::OpenHandle(this);
2467 return i::StringShape(*str).IsExternalTwoByte();
2468}
2469
2470
2471bool v8::String::IsExternalAscii() const {
2472 EnsureInitialized("v8::String::IsExternalAscii()");
2473 i::Handle<i::String> str = Utils::OpenHandle(this);
2474 return i::StringShape(*str).IsExternalAscii();
2475}
2476
2477
2478void v8::String::VerifyExternalStringResource(
2479 v8::String::ExternalStringResource* value) const {
2480 i::Handle<i::String> str = Utils::OpenHandle(this);
2481 v8::String::ExternalStringResource* expected;
2482 if (i::StringShape(*str).IsExternalTwoByte()) {
2483 void* resource = i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
2484 expected = reinterpret_cast<ExternalStringResource*>(resource);
2485 } else {
2486 expected = NULL;
2487 }
2488 CHECK_EQ(expected, value);
2489}
2490
2491
2492v8::String::ExternalAsciiStringResource*
2493 v8::String::GetExternalAsciiStringResource() const {
2494 EnsureInitialized("v8::String::GetExternalAsciiStringResource()");
2495 i::Handle<i::String> str = Utils::OpenHandle(this);
2496 if (i::StringShape(*str).IsExternalAscii()) {
2497 void* resource = i::Handle<i::ExternalAsciiString>::cast(str)->resource();
2498 return reinterpret_cast<ExternalAsciiStringResource*>(resource);
2499 } else {
2500 return NULL;
2501 }
2502}
2503
2504
2505double Number::Value() const {
2506 if (IsDeadCheck("v8::Number::Value()")) return 0;
2507 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2508 return obj->Number();
2509}
2510
2511
2512bool Boolean::Value() const {
2513 if (IsDeadCheck("v8::Boolean::Value()")) return false;
2514 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2515 return obj->IsTrue();
2516}
2517
2518
2519int64_t Integer::Value() const {
2520 if (IsDeadCheck("v8::Integer::Value()")) return 0;
2521 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2522 if (obj->IsSmi()) {
2523 return i::Smi::cast(*obj)->value();
2524 } else {
2525 return static_cast<int64_t>(obj->Number());
2526 }
2527}
2528
2529
2530int32_t Int32::Value() const {
2531 if (IsDeadCheck("v8::Int32::Value()")) return 0;
2532 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2533 if (obj->IsSmi()) {
2534 return i::Smi::cast(*obj)->value();
2535 } else {
2536 return static_cast<int32_t>(obj->Number());
2537 }
2538}
2539
2540
2541int v8::Object::InternalFieldCount() {
2542 if (IsDeadCheck("v8::Object::InternalFieldCount()")) return 0;
2543 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2544 return obj->GetInternalFieldCount();
2545}
2546
2547
2548Local<Value> v8::Object::CheckedGetInternalField(int index) {
2549 if (IsDeadCheck("v8::Object::GetInternalField()")) return Local<Value>();
2550 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2551 if (!ApiCheck(index < obj->GetInternalFieldCount(),
2552 "v8::Object::GetInternalField()",
2553 "Reading internal field out of bounds")) {
2554 return Local<Value>();
2555 }
2556 i::Handle<i::Object> value(obj->GetInternalField(index));
2557 Local<Value> result = Utils::ToLocal(value);
2558#ifdef DEBUG
2559 Local<Value> unchecked = UncheckedGetInternalField(index);
2560 ASSERT(unchecked.IsEmpty() || (unchecked == result));
2561#endif
2562 return result;
2563}
2564
2565
2566void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
2567 if (IsDeadCheck("v8::Object::SetInternalField()")) return;
2568 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2569 if (!ApiCheck(index < obj->GetInternalFieldCount(),
2570 "v8::Object::SetInternalField()",
2571 "Writing internal field out of bounds")) {
2572 return;
2573 }
2574 ENTER_V8;
2575 i::Handle<i::Object> val = Utils::OpenHandle(*value);
2576 obj->SetInternalField(index, *val);
2577}
2578
2579
2580void v8::Object::SetPointerInInternalField(int index, void* value) {
2581 SetInternalField(index, External::Wrap(value));
2582}
2583
2584
2585// --- E n v i r o n m e n t ---
2586
2587bool v8::V8::Initialize() {
2588 if (i::V8::IsRunning()) return true;
2589 ENTER_V8;
2590 HandleScope scope;
2591 if (i::Snapshot::Initialize()) {
2592 return true;
2593 } else {
2594 return i::V8::Initialize(NULL);
2595 }
2596}
2597
2598
2599bool v8::V8::Dispose() {
2600 i::V8::TearDown();
2601 return true;
2602}
2603
2604
2605bool v8::V8::IdleNotification(bool is_high_priority) {
2606 // Returning true tells the caller that it need not
2607 // continue to call IdleNotification.
2608 if (!i::V8::IsRunning()) return true;
2609 return i::V8::IdleNotification(is_high_priority);
2610}
2611
2612
2613void v8::V8::LowMemoryNotification() {
2614#if defined(ANDROID)
2615 if (!i::V8::IsRunning()) return;
2616 i::Heap::CollectAllGarbage(true);
2617#endif
2618}
2619
2620
2621const char* v8::V8::GetVersion() {
2622 static v8::internal::EmbeddedVector<char, 128> buffer;
2623 v8::internal::Version::GetString(buffer);
2624 return buffer.start();
2625}
2626
2627
2628static i::Handle<i::FunctionTemplateInfo>
2629 EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
2630 if (templ->constructor()->IsUndefined()) {
2631 Local<FunctionTemplate> constructor = FunctionTemplate::New();
2632 Utils::OpenHandle(*constructor)->set_instance_template(*templ);
2633 templ->set_constructor(*Utils::OpenHandle(*constructor));
2634 }
2635 return i::Handle<i::FunctionTemplateInfo>(
2636 i::FunctionTemplateInfo::cast(templ->constructor()));
2637}
2638
2639
2640Persistent<Context> v8::Context::New(
2641 v8::ExtensionConfiguration* extensions,
2642 v8::Handle<ObjectTemplate> global_template,
2643 v8::Handle<Value> global_object) {
2644 EnsureInitialized("v8::Context::New()");
2645 LOG_API("Context::New");
2646 ON_BAILOUT("v8::Context::New()", return Persistent<Context>());
2647
2648 // Enter V8 via an ENTER_V8 scope.
2649 i::Handle<i::Context> env;
2650 {
2651 ENTER_V8;
2652#if defined(ANDROID)
2653 // On mobile device, full GC is expensive, leave it to the system to
2654 // decide when should make a full GC.
2655#else
2656 // Give the heap a chance to cleanup if we've disposed contexts.
2657 i::Heap::CollectAllGarbageIfContextDisposed();
2658#endif
2659 v8::Handle<ObjectTemplate> proxy_template = global_template;
2660 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
2661 i::Handle<i::FunctionTemplateInfo> global_constructor;
2662
2663 if (!global_template.IsEmpty()) {
2664 // Make sure that the global_template has a constructor.
2665 global_constructor =
2666 EnsureConstructor(Utils::OpenHandle(*global_template));
2667
2668 // Create a fresh template for the global proxy object.
2669 proxy_template = ObjectTemplate::New();
2670 proxy_constructor =
2671 EnsureConstructor(Utils::OpenHandle(*proxy_template));
2672
2673 // Set the global template to be the prototype template of
2674 // global proxy template.
2675 proxy_constructor->set_prototype_template(
2676 *Utils::OpenHandle(*global_template));
2677
2678 // Migrate security handlers from global_template to
2679 // proxy_template. Temporarily removing access check
2680 // information from the global template.
2681 if (!global_constructor->access_check_info()->IsUndefined()) {
2682 proxy_constructor->set_access_check_info(
2683 global_constructor->access_check_info());
2684 proxy_constructor->set_needs_access_check(
2685 global_constructor->needs_access_check());
2686 global_constructor->set_needs_access_check(false);
2687 global_constructor->set_access_check_info(i::Heap::undefined_value());
2688 }
2689 }
2690
2691 // Create the environment.
2692 env = i::Bootstrapper::CreateEnvironment(
2693 Utils::OpenHandle(*global_object),
2694 proxy_template,
2695 extensions);
2696
2697 // Restore the access check info on the global template.
2698 if (!global_template.IsEmpty()) {
2699 ASSERT(!global_constructor.is_null());
2700 ASSERT(!proxy_constructor.is_null());
2701 global_constructor->set_access_check_info(
2702 proxy_constructor->access_check_info());
2703 global_constructor->set_needs_access_check(
2704 proxy_constructor->needs_access_check());
2705 }
2706 }
2707 // Leave V8.
2708
2709 if (env.is_null())
2710 return Persistent<Context>();
2711 return Persistent<Context>(Utils::ToLocal(env));
2712}
2713
2714
2715void v8::Context::SetSecurityToken(Handle<Value> token) {
2716 if (IsDeadCheck("v8::Context::SetSecurityToken()")) return;
2717 ENTER_V8;
2718 i::Handle<i::Context> env = Utils::OpenHandle(this);
2719 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
2720 env->set_security_token(*token_handle);
2721}
2722
2723
2724void v8::Context::UseDefaultSecurityToken() {
2725 if (IsDeadCheck("v8::Context::UseDefaultSecurityToken()")) return;
2726 ENTER_V8;
2727 i::Handle<i::Context> env = Utils::OpenHandle(this);
2728 env->set_security_token(env->global());
2729}
2730
2731
2732Handle<Value> v8::Context::GetSecurityToken() {
2733 if (IsDeadCheck("v8::Context::GetSecurityToken()")) return Handle<Value>();
2734 i::Handle<i::Context> env = Utils::OpenHandle(this);
2735 i::Object* security_token = env->security_token();
2736 i::Handle<i::Object> token_handle(security_token);
2737 return Utils::ToLocal(token_handle);
2738}
2739
2740
2741bool Context::HasOutOfMemoryException() {
2742 i::Handle<i::Context> env = Utils::OpenHandle(this);
2743 return env->has_out_of_memory();
2744}
2745
2746
2747bool Context::InContext() {
2748 return i::Top::context() != NULL;
2749}
2750
2751
2752v8::Local<v8::Context> Context::GetEntered() {
2753 if (IsDeadCheck("v8::Context::GetEntered()")) return Local<Context>();
2754 i::Handle<i::Object> last = thread_local.LastEnteredContext();
2755 if (last.is_null()) return Local<Context>();
2756 i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
2757 return Utils::ToLocal(context);
2758}
2759
2760
2761v8::Local<v8::Context> Context::GetCurrent() {
2762 if (IsDeadCheck("v8::Context::GetCurrent()")) return Local<Context>();
2763 i::Handle<i::Context> context(i::Top::global_context());
2764 return Utils::ToLocal(context);
2765}
2766
2767
2768v8::Local<v8::Context> Context::GetCalling() {
2769 if (IsDeadCheck("v8::Context::GetCalling()")) return Local<Context>();
2770 i::Handle<i::Object> calling = i::Top::GetCallingGlobalContext();
2771 if (calling.is_null()) return Local<Context>();
2772 i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
2773 return Utils::ToLocal(context);
2774}
2775
2776
2777v8::Local<v8::Object> Context::Global() {
2778 if (IsDeadCheck("v8::Context::Global()")) return Local<v8::Object>();
2779 i::Object** ctx = reinterpret_cast<i::Object**>(this);
2780 i::Handle<i::Context> context =
2781 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
2782 i::Handle<i::Object> global(context->global_proxy());
2783 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
2784}
2785
2786
2787void Context::DetachGlobal() {
2788 if (IsDeadCheck("v8::Context::DetachGlobal()")) return;
2789 ENTER_V8;
2790 i::Object** ctx = reinterpret_cast<i::Object**>(this);
2791 i::Handle<i::Context> context =
2792 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
2793 i::Bootstrapper::DetachGlobal(context);
2794}
2795
2796
2797Local<v8::Object> ObjectTemplate::NewInstance() {
2798 ON_BAILOUT("v8::ObjectTemplate::NewInstance()", return Local<v8::Object>());
2799 LOG_API("ObjectTemplate::NewInstance");
2800 ENTER_V8;
2801 EXCEPTION_PREAMBLE();
2802 i::Handle<i::Object> obj =
2803 i::Execution::InstantiateObject(Utils::OpenHandle(this),
2804 &has_pending_exception);
2805 EXCEPTION_BAILOUT_CHECK(Local<v8::Object>());
2806 return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
2807}
2808
2809
2810Local<v8::Function> FunctionTemplate::GetFunction() {
2811 ON_BAILOUT("v8::FunctionTemplate::GetFunction()",
2812 return Local<v8::Function>());
2813 LOG_API("FunctionTemplate::GetFunction");
2814 ENTER_V8;
2815 EXCEPTION_PREAMBLE();
2816 i::Handle<i::Object> obj =
2817 i::Execution::InstantiateFunction(Utils::OpenHandle(this),
2818 &has_pending_exception);
2819 EXCEPTION_BAILOUT_CHECK(Local<v8::Function>());
2820 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
2821}
2822
2823
2824bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
2825 ON_BAILOUT("v8::FunctionTemplate::HasInstanceOf()", return false);
2826 i::Object* obj = *Utils::OpenHandle(*value);
2827 return obj->IsInstanceOf(*Utils::OpenHandle(this));
2828}
2829
2830
2831static Local<External> ExternalNewImpl(void* data) {
2832 return Utils::ToLocal(i::Factory::NewProxy(static_cast<i::Address>(data)));
2833}
2834
2835static void* ExternalValueImpl(i::Handle<i::Object> obj) {
2836 return reinterpret_cast<void*>(i::Proxy::cast(*obj)->proxy());
2837}
2838
2839
2840static const intptr_t kAlignedPointerMask = 3;
2841
2842Local<Value> v8::External::Wrap(void* data) {
2843 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
2844 LOG_API("External::Wrap");
2845 EnsureInitialized("v8::External::Wrap()");
2846 ENTER_V8;
2847 if ((reinterpret_cast<intptr_t>(data) & kAlignedPointerMask) == 0) {
2848 uintptr_t data_ptr = reinterpret_cast<uintptr_t>(data);
2849 intptr_t data_value =
2850 static_cast<intptr_t>(data_ptr >> i::Internals::kAlignedPointerShift);
2851 STATIC_ASSERT(sizeof(data_ptr) == sizeof(data_value));
2852 if (i::Smi::IsIntptrValid(data_value)) {
2853 i::Handle<i::Object> obj(i::Smi::FromIntptr(data_value));
2854 return Utils::ToLocal(obj);
2855 }
2856 }
2857 return ExternalNewImpl(data);
2858}
2859
2860
2861void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
2862 if (IsDeadCheck("v8::External::Unwrap()")) return 0;
2863 i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
2864 void* result;
2865 if (obj->IsSmi()) {
2866 // The external value was an aligned pointer.
2867 uintptr_t value = static_cast<uintptr_t>(
2868 i::Smi::cast(*obj)->value()) << i::Internals::kAlignedPointerShift;
2869 result = reinterpret_cast<void*>(value);
2870 } else if (obj->IsProxy()) {
2871 result = ExternalValueImpl(obj);
2872 } else {
2873 result = NULL;
2874 }
2875 ASSERT_EQ(result, QuickUnwrap(wrapper));
2876 return result;
2877}
2878
2879
2880Local<External> v8::External::New(void* data) {
2881 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
2882 LOG_API("External::New");
2883 EnsureInitialized("v8::External::New()");
2884 ENTER_V8;
2885 return ExternalNewImpl(data);
2886}
2887
2888
2889void* External::Value() const {
2890 if (IsDeadCheck("v8::External::Value()")) return 0;
2891 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2892 return ExternalValueImpl(obj);
2893}
2894
2895
2896Local<String> v8::String::Empty() {
2897 EnsureInitialized("v8::String::Empty()");
2898 LOG_API("String::Empty()");
2899 return Utils::ToLocal(i::Factory::empty_symbol());
2900}
2901
2902
2903Local<String> v8::String::New(const char* data, int length) {
2904 EnsureInitialized("v8::String::New()");
2905 LOG_API("String::New(char)");
2906 if (length == 0) return Empty();
2907 ENTER_V8;
2908 if (length == -1) length = strlen(data);
2909 i::Handle<i::String> result =
2910 i::Factory::NewStringFromUtf8(i::Vector<const char>(data, length));
2911 return Utils::ToLocal(result);
2912}
2913
2914
2915Local<String> v8::String::NewUndetectable(const char* data, int length) {
2916 EnsureInitialized("v8::String::NewUndetectable()");
2917 LOG_API("String::NewUndetectable(char)");
2918 ENTER_V8;
2919 if (length == -1) length = strlen(data);
2920 i::Handle<i::String> result =
2921 i::Factory::NewStringFromUtf8(i::Vector<const char>(data, length));
2922 result->MarkAsUndetectable();
2923 return Utils::ToLocal(result);
2924}
2925
2926
2927static int TwoByteStringLength(const uint16_t* data) {
2928 int length = 0;
2929 while (data[length] != '\0') length++;
2930 return length;
2931}
2932
2933
2934Local<String> v8::String::New(const uint16_t* data, int length) {
2935 EnsureInitialized("v8::String::New()");
2936 LOG_API("String::New(uint16_)");
2937 if (length == 0) return Empty();
2938 ENTER_V8;
2939 if (length == -1) length = TwoByteStringLength(data);
2940 i::Handle<i::String> result =
2941 i::Factory::NewStringFromTwoByte(i::Vector<const uint16_t>(data, length));
2942 return Utils::ToLocal(result);
2943}
2944
2945
2946Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
2947 EnsureInitialized("v8::String::NewUndetectable()");
2948 LOG_API("String::NewUndetectable(uint16_)");
2949 ENTER_V8;
2950 if (length == -1) length = TwoByteStringLength(data);
2951 i::Handle<i::String> result =
2952 i::Factory::NewStringFromTwoByte(i::Vector<const uint16_t>(data, length));
2953 result->MarkAsUndetectable();
2954 return Utils::ToLocal(result);
2955}
2956
2957
2958i::Handle<i::String> NewExternalStringHandle(
2959 v8::String::ExternalStringResource* resource) {
2960 i::Handle<i::String> result =
2961 i::Factory::NewExternalStringFromTwoByte(resource);
2962 return result;
2963}
2964
2965
2966i::Handle<i::String> NewExternalAsciiStringHandle(
2967 v8::String::ExternalAsciiStringResource* resource) {
2968 i::Handle<i::String> result =
2969 i::Factory::NewExternalStringFromAscii(resource);
2970 return result;
2971}
2972
2973
2974static void DisposeExternalString(v8::Persistent<v8::Value> obj,
2975 void* parameter) {
2976 ENTER_V8;
2977 i::ExternalTwoByteString* str =
2978 i::ExternalTwoByteString::cast(*Utils::OpenHandle(*obj));
2979
2980 // External symbols are deleted when they are pruned out of the symbol
2981 // table. Generally external symbols are not registered with the weak handle
2982 // callbacks unless they are upgraded to a symbol after being externalized.
2983 if (!str->IsSymbol()) {
2984 v8::String::ExternalStringResource* resource =
2985 reinterpret_cast<v8::String::ExternalStringResource*>(parameter);
2986 if (resource != NULL) {
2987 const size_t total_size = resource->length() * sizeof(*resource->data());
2988 i::Counters::total_external_string_memory.Decrement(total_size);
2989
2990 // The object will continue to live in the JavaScript heap until the
2991 // handle is entirely cleaned out by the next GC. For example the
2992 // destructor for the resource below could bring it back to life again.
2993 // Which is why we make sure to not have a dangling pointer here.
2994 str->set_resource(NULL);
2995 delete resource;
2996 }
2997 }
2998
2999 // In any case we do not need this handle any longer.
3000 obj.Dispose();
3001}
3002
3003
3004static void DisposeExternalAsciiString(v8::Persistent<v8::Value> obj,
3005 void* parameter) {
3006 ENTER_V8;
3007 i::ExternalAsciiString* str =
3008 i::ExternalAsciiString::cast(*Utils::OpenHandle(*obj));
3009
3010 // External symbols are deleted when they are pruned out of the symbol
3011 // table. Generally external symbols are not registered with the weak handle
3012 // callbacks unless they are upgraded to a symbol after being externalized.
3013 if (!str->IsSymbol()) {
3014 v8::String::ExternalAsciiStringResource* resource =
3015 reinterpret_cast<v8::String::ExternalAsciiStringResource*>(parameter);
3016 if (resource != NULL) {
3017 const size_t total_size = resource->length() * sizeof(*resource->data());
3018 i::Counters::total_external_string_memory.Decrement(total_size);
3019
3020 // The object will continue to live in the JavaScript heap until the
3021 // handle is entirely cleaned out by the next GC. For example the
3022 // destructor for the resource below could bring it back to life again.
3023 // Which is why we make sure to not have a dangling pointer here.
3024 str->set_resource(NULL);
3025 delete resource;
3026 }
3027 }
3028
3029 // In any case we do not need this handle any longer.
3030 obj.Dispose();
3031}
3032
3033
3034Local<String> v8::String::NewExternal(
3035 v8::String::ExternalStringResource* resource) {
3036 EnsureInitialized("v8::String::NewExternal()");
3037 LOG_API("String::NewExternal");
3038 ENTER_V8;
3039 const size_t total_size = resource->length() * sizeof(*resource->data());
3040 i::Counters::total_external_string_memory.Increment(total_size);
3041 i::Handle<i::String> result = NewExternalStringHandle(resource);
3042 i::Handle<i::Object> handle = i::GlobalHandles::Create(*result);
3043 i::GlobalHandles::MakeWeak(handle.location(),
3044 resource,
3045 &DisposeExternalString);
3046 return Utils::ToLocal(result);
3047}
3048
3049
3050bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
3051 if (IsDeadCheck("v8::String::MakeExternal()")) return false;
3052 if (this->IsExternal()) return false; // Already an external string.
3053 ENTER_V8;
3054 i::Handle<i::String> obj = Utils::OpenHandle(this);
3055 bool result = obj->MakeExternal(resource);
3056 if (result && !obj->IsSymbol()) {
3057 // Operation was successful and the string is not a symbol. In this case
3058 // we need to make sure that the we call the destructor for the external
3059 // resource when no strong references to the string remain.
3060 i::Handle<i::Object> handle = i::GlobalHandles::Create(*obj);
3061 i::GlobalHandles::MakeWeak(handle.location(),
3062 resource,
3063 &DisposeExternalString);
3064 }
3065 return result;
3066}
3067
3068
3069Local<String> v8::String::NewExternal(
3070 v8::String::ExternalAsciiStringResource* resource) {
3071 EnsureInitialized("v8::String::NewExternal()");
3072 LOG_API("String::NewExternal");
3073 ENTER_V8;
3074 const size_t total_size = resource->length() * sizeof(*resource->data());
3075 i::Counters::total_external_string_memory.Increment(total_size);
3076 i::Handle<i::String> result = NewExternalAsciiStringHandle(resource);
3077 i::Handle<i::Object> handle = i::GlobalHandles::Create(*result);
3078 i::GlobalHandles::MakeWeak(handle.location(),
3079 resource,
3080 &DisposeExternalAsciiString);
3081 return Utils::ToLocal(result);
3082}
3083
3084
3085bool v8::String::MakeExternal(
3086 v8::String::ExternalAsciiStringResource* resource) {
3087 if (IsDeadCheck("v8::String::MakeExternal()")) return false;
3088 if (this->IsExternal()) return false; // Already an external string.
3089 ENTER_V8;
3090 i::Handle<i::String> obj = Utils::OpenHandle(this);
3091 bool result = obj->MakeExternal(resource);
3092 if (result && !obj->IsSymbol()) {
3093 // Operation was successful and the string is not a symbol. In this case
3094 // we need to make sure that the we call the destructor for the external
3095 // resource when no strong references to the string remain.
3096 i::Handle<i::Object> handle = i::GlobalHandles::Create(*obj);
3097 i::GlobalHandles::MakeWeak(handle.location(),
3098 resource,
3099 &DisposeExternalAsciiString);
3100 }
3101 return result;
3102}
3103
3104
3105bool v8::String::CanMakeExternal() {
3106 if (IsDeadCheck("v8::String::CanMakeExternal()")) return false;
3107 i::Handle<i::String> obj = Utils::OpenHandle(this);
3108 int size = obj->Size(); // Byte size of the original string.
3109 if (size < i::ExternalString::kSize)
3110 return false;
3111 i::StringShape shape(*obj);
3112 return !shape.IsExternal();
3113}
3114
3115
3116Local<v8::Object> v8::Object::New() {
3117 EnsureInitialized("v8::Object::New()");
3118 LOG_API("Object::New");
3119 ENTER_V8;
3120 i::Handle<i::JSObject> obj =
3121 i::Factory::NewJSObject(i::Top::object_function());
3122 return Utils::ToLocal(obj);
3123}
3124
3125
3126Local<v8::Value> v8::Date::New(double time) {
3127 EnsureInitialized("v8::Date::New()");
3128 LOG_API("Date::New");
3129 ENTER_V8;
3130 EXCEPTION_PREAMBLE();
3131 i::Handle<i::Object> obj =
3132 i::Execution::NewDate(time, &has_pending_exception);
3133 EXCEPTION_BAILOUT_CHECK(Local<v8::Value>());
3134 return Utils::ToLocal(obj);
3135}
3136
3137
3138double v8::Date::NumberValue() const {
3139 if (IsDeadCheck("v8::Date::NumberValue()")) return 0;
3140 LOG_API("Date::NumberValue");
3141 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3142 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
3143 return jsvalue->value()->Number();
3144}
3145
3146
3147Local<v8::Array> v8::Array::New(int length) {
3148 EnsureInitialized("v8::Array::New()");
3149 LOG_API("Array::New");
3150 ENTER_V8;
3151 i::Handle<i::JSArray> obj = i::Factory::NewJSArray(length);
3152 return Utils::ToLocal(obj);
3153}
3154
3155
3156uint32_t v8::Array::Length() const {
3157 if (IsDeadCheck("v8::Array::Length()")) return 0;
3158 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
3159 i::Object* length = obj->length();
3160 if (length->IsSmi()) {
3161 return i::Smi::cast(length)->value();
3162 } else {
3163 return static_cast<uint32_t>(length->Number());
3164 }
3165}
3166
3167
3168Local<Object> Array::CloneElementAt(uint32_t index) {
3169 ON_BAILOUT("v8::Array::CloneElementAt()", return Local<Object>());
3170 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3171 if (!self->HasFastElements()) {
3172 return Local<Object>();
3173 }
3174 i::FixedArray* elms = i::FixedArray::cast(self->elements());
3175 i::Object* paragon = elms->get(index);
3176 if (!paragon->IsJSObject()) {
3177 return Local<Object>();
3178 }
3179 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
3180 EXCEPTION_PREAMBLE();
3181 i::Handle<i::JSObject> result = i::Copy(paragon_handle);
3182 has_pending_exception = result.is_null();
3183 EXCEPTION_BAILOUT_CHECK(Local<Object>());
3184 return Utils::ToLocal(result);
3185}
3186
3187
3188Local<String> v8::String::NewSymbol(const char* data, int length) {
3189 EnsureInitialized("v8::String::NewSymbol()");
3190 LOG_API("String::NewSymbol(char)");
3191 ENTER_V8;
3192 if (length == -1) length = strlen(data);
3193 i::Handle<i::String> result =
3194 i::Factory::LookupSymbol(i::Vector<const char>(data, length));
3195 return Utils::ToLocal(result);
3196}
3197
3198
3199Local<Number> v8::Number::New(double value) {
3200 EnsureInitialized("v8::Number::New()");
3201 ENTER_V8;
3202 i::Handle<i::Object> result = i::Factory::NewNumber(value);
3203 return Utils::NumberToLocal(result);
3204}
3205
3206
3207Local<Integer> v8::Integer::New(int32_t value) {
3208 EnsureInitialized("v8::Integer::New()");
3209 if (i::Smi::IsValid(value)) {
3210 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value)));
3211 }
3212 ENTER_V8;
3213 i::Handle<i::Object> result = i::Factory::NewNumber(value);
3214 return Utils::IntegerToLocal(result);
3215}
3216
3217
3218void V8::IgnoreOutOfMemoryException() {
3219 thread_local.set_ignore_out_of_memory(true);
3220}
3221
3222
3223bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
3224 EnsureInitialized("v8::V8::AddMessageListener()");
3225 ON_BAILOUT("v8::V8::AddMessageListener()", return false);
3226 ENTER_V8;
3227 HandleScope scope;
3228 NeanderArray listeners(i::Factory::message_listeners());
3229 NeanderObject obj(2);
3230 obj.set(0, *i::Factory::NewProxy(FUNCTION_ADDR(that)));
3231 obj.set(1, data.IsEmpty() ?
3232 i::Heap::undefined_value() :
3233 *Utils::OpenHandle(*data));
3234 listeners.add(obj.value());
3235 return true;
3236}
3237
3238
3239void V8::RemoveMessageListeners(MessageCallback that) {
3240 EnsureInitialized("v8::V8::RemoveMessageListener()");
3241 ON_BAILOUT("v8::V8::RemoveMessageListeners()", return);
3242 ENTER_V8;
3243 HandleScope scope;
3244 NeanderArray listeners(i::Factory::message_listeners());
3245 for (int i = 0; i < listeners.length(); i++) {
3246 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
3247
3248 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
3249 i::Handle<i::Proxy> callback_obj(i::Proxy::cast(listener.get(0)));
3250 if (callback_obj->proxy() == FUNCTION_ADDR(that)) {
3251 listeners.set(i, i::Heap::undefined_value());
3252 }
3253 }
3254}
3255
3256
3257void V8::SetCounterFunction(CounterLookupCallback callback) {
3258 if (IsDeadCheck("v8::V8::SetCounterFunction()")) return;
3259 i::StatsTable::SetCounterFunction(callback);
3260}
3261
3262void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
3263 if (IsDeadCheck("v8::V8::SetCreateHistogramFunction()")) return;
3264 i::StatsTable::SetCreateHistogramFunction(callback);
3265}
3266
3267void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
3268 if (IsDeadCheck("v8::V8::SetAddHistogramSampleFunction()")) return;
3269 i::StatsTable::SetAddHistogramSampleFunction(callback);
3270}
3271
3272void V8::EnableSlidingStateWindow() {
3273 if (IsDeadCheck("v8::V8::EnableSlidingStateWindow()")) return;
3274 i::Logger::EnableSlidingStateWindow();
3275}
3276
3277
3278void V8::SetFailedAccessCheckCallbackFunction(
3279 FailedAccessCheckCallback callback) {
3280 if (IsDeadCheck("v8::V8::SetFailedAccessCheckCallbackFunction()")) return;
3281 i::Top::SetFailedAccessCheckCallback(callback);
3282}
3283
3284
3285void V8::AddObjectGroup(Persistent<Value>* objects, size_t length) {
3286 if (IsDeadCheck("v8::V8::AddObjectGroup()")) return;
3287 STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
3288 i::GlobalHandles::AddGroup(reinterpret_cast<i::Object***>(objects), length);
3289}
3290
3291
3292int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
3293 if (IsDeadCheck("v8::V8::AdjustAmountOfExternalAllocatedMemory()")) return 0;
3294 return i::Heap::AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
3295}
3296
3297
3298void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
3299 if (IsDeadCheck("v8::V8::SetGlobalGCPrologueCallback()")) return;
3300 i::Heap::SetGlobalGCPrologueCallback(callback);
3301}
3302
3303
3304void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
3305 if (IsDeadCheck("v8::V8::SetGlobalGCEpilogueCallback()")) return;
3306 i::Heap::SetGlobalGCEpilogueCallback(callback);
3307}
3308
3309
3310void V8::PauseProfiler() {
3311#ifdef ENABLE_LOGGING_AND_PROFILING
3312 i::Logger::PauseProfiler(PROFILER_MODULE_CPU);
3313#endif
3314}
3315
3316
3317void V8::ResumeProfiler() {
3318#ifdef ENABLE_LOGGING_AND_PROFILING
3319 i::Logger::ResumeProfiler(PROFILER_MODULE_CPU);
3320#endif
3321}
3322
3323
3324bool V8::IsProfilerPaused() {
3325#ifdef ENABLE_LOGGING_AND_PROFILING
3326 return i::Logger::GetActiveProfilerModules() & PROFILER_MODULE_CPU;
3327#else
3328 return true;
3329#endif
3330}
3331
3332
3333void V8::ResumeProfilerEx(int flags) {
3334#ifdef ENABLE_LOGGING_AND_PROFILING
3335 if (flags & PROFILER_MODULE_HEAP_SNAPSHOT) {
3336 // Snapshot mode: resume modules, perform GC, then pause only
3337 // those modules which haven't been started prior to making a
3338 // snapshot.
3339
3340 // Reset snapshot flag and CPU module flags.
3341 flags &= ~(PROFILER_MODULE_HEAP_SNAPSHOT | PROFILER_MODULE_CPU);
3342 const int current_flags = i::Logger::GetActiveProfilerModules();
3343 i::Logger::ResumeProfiler(flags);
3344 i::Heap::CollectAllGarbage(false);
3345 i::Logger::PauseProfiler(~current_flags & flags);
3346 } else {
3347 i::Logger::ResumeProfiler(flags);
3348 }
3349#endif
3350}
3351
3352
3353void V8::PauseProfilerEx(int flags) {
3354#ifdef ENABLE_LOGGING_AND_PROFILING
3355 i::Logger::PauseProfiler(flags);
3356#endif
3357}
3358
3359
3360int V8::GetActiveProfilerModules() {
3361#ifdef ENABLE_LOGGING_AND_PROFILING
3362 return i::Logger::GetActiveProfilerModules();
3363#else
3364 return PROFILER_MODULE_NONE;
3365#endif
3366}
3367
3368
3369int V8::GetLogLines(int from_pos, char* dest_buf, int max_size) {
3370#ifdef ENABLE_LOGGING_AND_PROFILING
3371 return i::Logger::GetLogLines(from_pos, dest_buf, max_size);
3372#endif
3373 return 0;
3374}
3375
3376
3377int V8::GetCurrentThreadId() {
3378 API_ENTRY_CHECK("V8::GetCurrentThreadId()");
3379 EnsureInitialized("V8::GetCurrentThreadId()");
3380 return i::Top::thread_id();
3381}
3382
3383
3384void V8::TerminateExecution(int thread_id) {
3385 if (!i::V8::IsRunning()) return;
3386 API_ENTRY_CHECK("V8::GetCurrentThreadId()");
3387 // If the thread_id identifies the current thread just terminate
3388 // execution right away. Otherwise, ask the thread manager to
3389 // terminate the thread with the given id if any.
3390 if (thread_id == i::Top::thread_id()) {
3391 i::StackGuard::TerminateExecution();
3392 } else {
3393 i::ThreadManager::TerminateExecution(thread_id);
3394 }
3395}
3396
3397
3398void V8::TerminateExecution() {
3399 if (!i::V8::IsRunning()) return;
3400 i::StackGuard::TerminateExecution();
3401}
3402
3403
3404String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj) {
3405 EnsureInitialized("v8::String::Utf8Value::Utf8Value()");
3406 if (obj.IsEmpty()) {
3407 str_ = NULL;
3408 length_ = 0;
3409 return;
3410 }
3411 ENTER_V8;
3412 HandleScope scope;
3413 TryCatch try_catch;
3414 Handle<String> str = obj->ToString();
3415 if (str.IsEmpty()) {
3416 str_ = NULL;
3417 length_ = 0;
3418 } else {
3419 length_ = str->Utf8Length();
3420 str_ = i::NewArray<char>(length_ + 1);
3421 str->WriteUtf8(str_);
3422 }
3423}
3424
3425
3426String::Utf8Value::~Utf8Value() {
3427 i::DeleteArray(str_);
3428}
3429
3430
3431String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj) {
3432 EnsureInitialized("v8::String::AsciiValue::AsciiValue()");
3433 if (obj.IsEmpty()) {
3434 str_ = NULL;
3435 length_ = 0;
3436 return;
3437 }
3438 ENTER_V8;
3439 HandleScope scope;
3440 TryCatch try_catch;
3441 Handle<String> str = obj->ToString();
3442 if (str.IsEmpty()) {
3443 str_ = NULL;
3444 length_ = 0;
3445 } else {
3446 length_ = str->Length();
3447 str_ = i::NewArray<char>(length_ + 1);
3448 str->WriteAscii(str_);
3449 }
3450}
3451
3452
3453String::AsciiValue::~AsciiValue() {
3454 i::DeleteArray(str_);
3455}
3456
3457
3458String::Value::Value(v8::Handle<v8::Value> obj) {
3459 EnsureInitialized("v8::String::Value::Value()");
3460 if (obj.IsEmpty()) {
3461 str_ = NULL;
3462 length_ = 0;
3463 return;
3464 }
3465 ENTER_V8;
3466 HandleScope scope;
3467 TryCatch try_catch;
3468 Handle<String> str = obj->ToString();
3469 if (str.IsEmpty()) {
3470 str_ = NULL;
3471 length_ = 0;
3472 } else {
3473 length_ = str->Length();
3474 str_ = i::NewArray<uint16_t>(length_ + 1);
3475 str->Write(str_);
3476 }
3477}
3478
3479
3480String::Value::~Value() {
3481 i::DeleteArray(str_);
3482}
3483
3484Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
3485 LOG_API("RangeError");
3486 ON_BAILOUT("v8::Exception::RangeError()", return Local<Value>());
3487 ENTER_V8;
3488 i::Object* error;
3489 {
3490 HandleScope scope;
3491 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3492 i::Handle<i::Object> result = i::Factory::NewRangeError(message);
3493 error = *result;
3494 }
3495 i::Handle<i::Object> result(error);
3496 return Utils::ToLocal(result);
3497}
3498
3499Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
3500 LOG_API("ReferenceError");
3501 ON_BAILOUT("v8::Exception::ReferenceError()", return Local<Value>());
3502 ENTER_V8;
3503 i::Object* error;
3504 {
3505 HandleScope scope;
3506 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3507 i::Handle<i::Object> result = i::Factory::NewReferenceError(message);
3508 error = *result;
3509 }
3510 i::Handle<i::Object> result(error);
3511 return Utils::ToLocal(result);
3512}
3513
3514Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
3515 LOG_API("SyntaxError");
3516 ON_BAILOUT("v8::Exception::SyntaxError()", return Local<Value>());
3517 ENTER_V8;
3518 i::Object* error;
3519 {
3520 HandleScope scope;
3521 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3522 i::Handle<i::Object> result = i::Factory::NewSyntaxError(message);
3523 error = *result;
3524 }
3525 i::Handle<i::Object> result(error);
3526 return Utils::ToLocal(result);
3527}
3528
3529Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
3530 LOG_API("TypeError");
3531 ON_BAILOUT("v8::Exception::TypeError()", return Local<Value>());
3532 ENTER_V8;
3533 i::Object* error;
3534 {
3535 HandleScope scope;
3536 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3537 i::Handle<i::Object> result = i::Factory::NewTypeError(message);
3538 error = *result;
3539 }
3540 i::Handle<i::Object> result(error);
3541 return Utils::ToLocal(result);
3542}
3543
3544Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
3545 LOG_API("Error");
3546 ON_BAILOUT("v8::Exception::Error()", return Local<Value>());
3547 ENTER_V8;
3548 i::Object* error;
3549 {
3550 HandleScope scope;
3551 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3552 i::Handle<i::Object> result = i::Factory::NewError(message);
3553 error = *result;
3554 }
3555 i::Handle<i::Object> result(error);
3556 return Utils::ToLocal(result);
3557}
3558
3559
3560// --- D e b u g S u p p o r t ---
3561
3562#ifdef ENABLE_DEBUGGER_SUPPORT
3563bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
3564 EnsureInitialized("v8::Debug::SetDebugEventListener()");
3565 ON_BAILOUT("v8::Debug::SetDebugEventListener()", return false);
3566 ENTER_V8;
3567 HandleScope scope;
3568 i::Handle<i::Object> proxy = i::Factory::undefined_value();
3569 if (that != NULL) {
3570 proxy = i::Factory::NewProxy(FUNCTION_ADDR(that));
3571 }
3572 i::Debugger::SetEventListener(proxy, Utils::OpenHandle(*data));
3573 return true;
3574}
3575
3576
3577bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
3578 Handle<Value> data) {
3579 ON_BAILOUT("v8::Debug::SetDebugEventListener()", return false);
3580 ENTER_V8;
3581 i::Debugger::SetEventListener(Utils::OpenHandle(*that),
3582 Utils::OpenHandle(*data));
3583 return true;
3584}
3585
3586
3587void Debug::DebugBreak() {
3588 if (!i::V8::IsRunning()) return;
3589 i::StackGuard::DebugBreak();
3590}
3591
3592
3593static v8::Debug::MessageHandler message_handler = NULL;
3594
3595static void MessageHandlerWrapper(const v8::Debug::Message& message) {
3596 if (message_handler) {
3597 v8::String::Value json(message.GetJSON());
3598 message_handler(*json, json.length(), message.GetClientData());
3599 }
3600}
3601
3602
3603void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
3604 bool message_handler_thread) {
3605 EnsureInitialized("v8::Debug::SetMessageHandler");
3606 ENTER_V8;
3607 // Message handler thread not supported any more. Parameter temporally left in
3608 // the API for client compatability reasons.
3609 CHECK(!message_handler_thread);
3610
3611 // TODO(sgjesse) support the old message handler API through a simple wrapper.
3612 message_handler = handler;
3613 if (message_handler != NULL) {
3614 i::Debugger::SetMessageHandler(MessageHandlerWrapper);
3615 } else {
3616 i::Debugger::SetMessageHandler(NULL);
3617 }
3618}
3619
3620
3621void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
3622 EnsureInitialized("v8::Debug::SetMessageHandler");
3623 ENTER_V8;
3624 HandleScope scope;
3625 i::Debugger::SetMessageHandler(handler);
3626}
3627
3628
3629void Debug::SendCommand(const uint16_t* command, int length,
3630 ClientData* client_data) {
3631 if (!i::V8::IsRunning()) return;
3632 i::Debugger::ProcessCommand(i::Vector<const uint16_t>(command, length),
3633 client_data);
3634}
3635
3636
3637void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
3638 int period) {
3639 EnsureInitialized("v8::Debug::SetHostDispatchHandler");
3640 ENTER_V8;
3641 i::Debugger::SetHostDispatchHandler(handler, period);
3642}
3643
3644
3645Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
3646 v8::Handle<v8::Value> data) {
3647 if (!i::V8::IsRunning()) return Local<Value>();
3648 ON_BAILOUT("v8::Debug::Call()", return Local<Value>());
3649 ENTER_V8;
3650 i::Handle<i::Object> result;
3651 EXCEPTION_PREAMBLE();
3652 if (data.IsEmpty()) {
3653 result = i::Debugger::Call(Utils::OpenHandle(*fun),
3654 i::Factory::undefined_value(),
3655 &has_pending_exception);
3656 } else {
3657 result = i::Debugger::Call(Utils::OpenHandle(*fun),
3658 Utils::OpenHandle(*data),
3659 &has_pending_exception);
3660 }
3661 EXCEPTION_BAILOUT_CHECK(Local<Value>());
3662 return Utils::ToLocal(result);
3663}
3664
3665
3666Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
3667 if (!i::V8::IsRunning()) return Local<Value>();
3668 ON_BAILOUT("v8::Debug::GetMirror()", return Local<Value>());
3669 ENTER_V8;
3670 v8::HandleScope scope;
3671 i::Debug::Load();
3672 i::Handle<i::JSObject> debug(i::Debug::debug_context()->global());
3673 i::Handle<i::String> name = i::Factory::LookupAsciiSymbol("MakeMirror");
3674 i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
3675 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
3676 v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
3677 const int kArgc = 1;
3678 v8::Handle<v8::Value> argv[kArgc] = { obj };
3679 EXCEPTION_PREAMBLE();
3680 v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
3681 kArgc,
3682 argv);
3683 EXCEPTION_BAILOUT_CHECK(Local<Value>());
3684 return scope.Close(result);
3685}
3686
3687
3688bool Debug::EnableAgent(const char* name, int port) {
3689 return i::Debugger::StartAgent(name, port);
3690}
3691#endif // ENABLE_DEBUGGER_SUPPORT
3692
3693namespace internal {
3694
3695
3696HandleScopeImplementer* HandleScopeImplementer::instance() {
3697 return &thread_local;
3698}
3699
3700
3701void HandleScopeImplementer::FreeThreadResources() {
3702 thread_local.Free();
3703}
3704
3705
3706char* HandleScopeImplementer::ArchiveThread(char* storage) {
3707 return thread_local.ArchiveThreadHelper(storage);
3708}
3709
3710
3711char* HandleScopeImplementer::ArchiveThreadHelper(char* storage) {
3712 v8::ImplementationUtilities::HandleScopeData* current =
3713 v8::ImplementationUtilities::CurrentHandleScope();
3714 handle_scope_data_ = *current;
3715 memcpy(storage, this, sizeof(*this));
3716
3717 ResetAfterArchive();
3718 current->Initialize();
3719
3720 return storage + ArchiveSpacePerThread();
3721}
3722
3723
3724int HandleScopeImplementer::ArchiveSpacePerThread() {
3725 return sizeof(thread_local);
3726}
3727
3728
3729char* HandleScopeImplementer::RestoreThread(char* storage) {
3730 return thread_local.RestoreThreadHelper(storage);
3731}
3732
3733
3734char* HandleScopeImplementer::RestoreThreadHelper(char* storage) {
3735 memcpy(this, storage, sizeof(*this));
3736 *v8::ImplementationUtilities::CurrentHandleScope() = handle_scope_data_;
3737 return storage + ArchiveSpacePerThread();
3738}
3739
3740
3741void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
3742 // Iterate over all handles in the blocks except for the last.
3743 for (int i = blocks()->length() - 2; i >= 0; --i) {
3744 Object** block = blocks()->at(i);
3745 v->VisitPointers(block, &block[kHandleBlockSize]);
3746 }
3747
3748 // Iterate over live handles in the last block (if any).
3749 if (!blocks()->is_empty()) {
3750 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
3751 }
3752
3753 if (!saved_contexts_.is_empty()) {
3754 Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
3755 v->VisitPointers(start, start + saved_contexts_.length());
3756 }
3757}
3758
3759
3760void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
3761 v8::ImplementationUtilities::HandleScopeData* current =
3762 v8::ImplementationUtilities::CurrentHandleScope();
3763 thread_local.handle_scope_data_ = *current;
3764 thread_local.IterateThis(v);
3765}
3766
3767
3768char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
3769 HandleScopeImplementer* thread_local =
3770 reinterpret_cast<HandleScopeImplementer*>(storage);
3771 thread_local->IterateThis(v);
3772 return storage + ArchiveSpacePerThread();
3773}
3774
3775} } // namespace v8::internal