blob: b457aad0a052df47eae0176598c0364fa7ddfdd9 [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) {
Steve Block3ce2e202009-11-05 08:53:23 +0000345 int young_space_size = constraints->max_young_space_size();
Steve Blocka7e24c12009-10-30 11:49:00 +0000346 int old_gen_size = constraints->max_old_space_size();
Steve Block3ce2e202009-11-05 08:53:23 +0000347 if (young_space_size != 0 || old_gen_size != 0) {
348 bool result = i::Heap::ConfigureHeap(young_space_size / 2, old_gen_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000349 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;
Steve Block3ce2e202009-11-05 08:53:23 +00002293 if (!ApiCheck(length <= i::PixelArray::kMaxLength,
Steve Blocka7e24c12009-10-30 11:49:00 +00002294 "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
Steve Block3ce2e202009-11-05 08:53:23 +00002309void v8::Object::SetIndexedPropertiesToExternalArrayData(
2310 void* data,
2311 ExternalArrayType array_type,
2312 int length) {
2313 ON_BAILOUT("v8::SetIndexedPropertiesToExternalArrayData()", return);
2314 ENTER_V8;
2315 HandleScope scope;
2316 if (!ApiCheck(length <= i::ExternalArray::kMaxLength,
2317 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
2318 "length exceeds max acceptable value")) {
2319 return;
2320 }
2321 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
2322 if (!ApiCheck(!self->IsJSArray(),
2323 "v8::Object::SetIndexedPropertiesToExternalArrayData()",
2324 "JSArray is not supported")) {
2325 return;
2326 }
2327 i::Handle<i::ExternalArray> array =
2328 i::Factory::NewExternalArray(length, array_type, data);
2329 self->set_elements(*array);
2330}
2331
2332
Steve Blocka7e24c12009-10-30 11:49:00 +00002333Local<v8::Object> Function::NewInstance() const {
2334 return NewInstance(0, NULL);
2335}
2336
2337
2338Local<v8::Object> Function::NewInstance(int argc,
2339 v8::Handle<v8::Value> argv[]) const {
2340 ON_BAILOUT("v8::Function::NewInstance()", return Local<v8::Object>());
2341 LOG_API("Function::NewInstance");
2342 ENTER_V8;
2343 HandleScope scope;
2344 i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
2345 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
2346 i::Object*** args = reinterpret_cast<i::Object***>(argv);
2347 EXCEPTION_PREAMBLE();
2348 i::Handle<i::Object> returned =
2349 i::Execution::New(function, argc, args, &has_pending_exception);
2350 EXCEPTION_BAILOUT_CHECK(Local<v8::Object>());
2351 return scope.Close(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
2352}
2353
2354
2355Local<v8::Value> Function::Call(v8::Handle<v8::Object> recv, int argc,
2356 v8::Handle<v8::Value> argv[]) {
2357 ON_BAILOUT("v8::Function::Call()", return Local<v8::Value>());
2358 LOG_API("Function::Call");
2359 ENTER_V8;
2360 i::Object* raw_result = NULL;
2361 {
2362 HandleScope scope;
2363 i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
2364 i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
2365 STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
2366 i::Object*** args = reinterpret_cast<i::Object***>(argv);
2367 EXCEPTION_PREAMBLE();
2368 i::Handle<i::Object> returned =
2369 i::Execution::Call(fun, recv_obj, argc, args, &has_pending_exception);
2370 EXCEPTION_BAILOUT_CHECK(Local<Object>());
2371 raw_result = *returned;
2372 }
2373 i::Handle<i::Object> result(raw_result);
2374 return Utils::ToLocal(result);
2375}
2376
2377
2378void Function::SetName(v8::Handle<v8::String> name) {
2379 ENTER_V8;
2380 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
2381 func->shared()->set_name(*Utils::OpenHandle(*name));
2382}
2383
2384
2385Handle<Value> Function::GetName() const {
2386 i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
2387 return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name()));
2388}
2389
2390
2391int String::Length() const {
2392 if (IsDeadCheck("v8::String::Length()")) return 0;
2393 return Utils::OpenHandle(this)->length();
2394}
2395
2396
2397int String::Utf8Length() const {
2398 if (IsDeadCheck("v8::String::Utf8Length()")) return 0;
2399 return Utils::OpenHandle(this)->Utf8Length();
2400}
2401
2402
2403int String::WriteUtf8(char* buffer, int capacity) const {
2404 if (IsDeadCheck("v8::String::WriteUtf8()")) return 0;
2405 LOG_API("String::WriteUtf8");
2406 ENTER_V8;
2407 i::Handle<i::String> str = Utils::OpenHandle(this);
2408 write_input_buffer.Reset(0, *str);
2409 int len = str->length();
2410 // Encode the first K - 3 bytes directly into the buffer since we
2411 // know there's room for them. If no capacity is given we copy all
2412 // of them here.
2413 int fast_end = capacity - (unibrow::Utf8::kMaxEncodedSize - 1);
2414 int i;
2415 int pos = 0;
2416 for (i = 0; i < len && (capacity == -1 || pos < fast_end); i++) {
2417 i::uc32 c = write_input_buffer.GetNext();
2418 int written = unibrow::Utf8::Encode(buffer + pos, c);
2419 pos += written;
2420 }
2421 if (i < len) {
2422 // For the last characters we need to check the length for each one
2423 // because they may be longer than the remaining space in the
2424 // buffer.
2425 char intermediate[unibrow::Utf8::kMaxEncodedSize];
2426 for (; i < len && pos < capacity; i++) {
2427 i::uc32 c = write_input_buffer.GetNext();
2428 int written = unibrow::Utf8::Encode(intermediate, c);
2429 if (pos + written <= capacity) {
2430 for (int j = 0; j < written; j++)
2431 buffer[pos + j] = intermediate[j];
2432 pos += written;
2433 } else {
2434 // We've reached the end of the buffer
2435 break;
2436 }
2437 }
2438 }
2439 if (i == len && (capacity == -1 || pos < capacity))
2440 buffer[pos++] = '\0';
2441 return pos;
2442}
2443
2444
2445int String::WriteAscii(char* buffer, int start, int length) const {
2446 if (IsDeadCheck("v8::String::WriteAscii()")) return 0;
2447 LOG_API("String::WriteAscii");
2448 ENTER_V8;
2449 ASSERT(start >= 0 && length >= -1);
2450 i::Handle<i::String> str = Utils::OpenHandle(this);
2451 // Flatten the string for efficiency. This applies whether we are
2452 // using StringInputBuffer or Get(i) to access the characters.
2453 str->TryFlattenIfNotFlat();
2454 int end = length;
2455 if ( (length == -1) || (length > str->length() - start) )
2456 end = str->length() - start;
2457 if (end < 0) return 0;
2458 write_input_buffer.Reset(start, *str);
2459 int i;
2460 for (i = 0; i < end; i++) {
2461 char c = static_cast<char>(write_input_buffer.GetNext());
2462 if (c == '\0') c = ' ';
2463 buffer[i] = c;
2464 }
2465 if (length == -1 || i < length)
2466 buffer[i] = '\0';
2467 return i;
2468}
2469
2470
2471int String::Write(uint16_t* buffer, int start, int length) const {
2472 if (IsDeadCheck("v8::String::Write()")) return 0;
2473 LOG_API("String::Write");
2474 ENTER_V8;
2475 ASSERT(start >= 0 && length >= -1);
2476 i::Handle<i::String> str = Utils::OpenHandle(this);
2477 int end = length;
2478 if ( (length == -1) || (length > str->length() - start) )
2479 end = str->length() - start;
2480 if (end < 0) return 0;
2481 i::String::WriteToFlat(*str, buffer, start, end);
2482 if (length == -1 || end < length)
2483 buffer[end] = '\0';
2484 return end;
2485}
2486
2487
2488bool v8::String::IsExternal() const {
2489 EnsureInitialized("v8::String::IsExternal()");
2490 i::Handle<i::String> str = Utils::OpenHandle(this);
2491 return i::StringShape(*str).IsExternalTwoByte();
2492}
2493
2494
2495bool v8::String::IsExternalAscii() const {
2496 EnsureInitialized("v8::String::IsExternalAscii()");
2497 i::Handle<i::String> str = Utils::OpenHandle(this);
2498 return i::StringShape(*str).IsExternalAscii();
2499}
2500
2501
2502void v8::String::VerifyExternalStringResource(
2503 v8::String::ExternalStringResource* value) const {
2504 i::Handle<i::String> str = Utils::OpenHandle(this);
2505 v8::String::ExternalStringResource* expected;
2506 if (i::StringShape(*str).IsExternalTwoByte()) {
2507 void* resource = i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
2508 expected = reinterpret_cast<ExternalStringResource*>(resource);
2509 } else {
2510 expected = NULL;
2511 }
2512 CHECK_EQ(expected, value);
2513}
2514
2515
2516v8::String::ExternalAsciiStringResource*
2517 v8::String::GetExternalAsciiStringResource() const {
2518 EnsureInitialized("v8::String::GetExternalAsciiStringResource()");
2519 i::Handle<i::String> str = Utils::OpenHandle(this);
2520 if (i::StringShape(*str).IsExternalAscii()) {
2521 void* resource = i::Handle<i::ExternalAsciiString>::cast(str)->resource();
2522 return reinterpret_cast<ExternalAsciiStringResource*>(resource);
2523 } else {
2524 return NULL;
2525 }
2526}
2527
2528
2529double Number::Value() const {
2530 if (IsDeadCheck("v8::Number::Value()")) return 0;
2531 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2532 return obj->Number();
2533}
2534
2535
2536bool Boolean::Value() const {
2537 if (IsDeadCheck("v8::Boolean::Value()")) return false;
2538 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2539 return obj->IsTrue();
2540}
2541
2542
2543int64_t Integer::Value() const {
2544 if (IsDeadCheck("v8::Integer::Value()")) return 0;
2545 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2546 if (obj->IsSmi()) {
2547 return i::Smi::cast(*obj)->value();
2548 } else {
2549 return static_cast<int64_t>(obj->Number());
2550 }
2551}
2552
2553
2554int32_t Int32::Value() const {
2555 if (IsDeadCheck("v8::Int32::Value()")) return 0;
2556 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2557 if (obj->IsSmi()) {
2558 return i::Smi::cast(*obj)->value();
2559 } else {
2560 return static_cast<int32_t>(obj->Number());
2561 }
2562}
2563
2564
2565int v8::Object::InternalFieldCount() {
2566 if (IsDeadCheck("v8::Object::InternalFieldCount()")) return 0;
2567 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2568 return obj->GetInternalFieldCount();
2569}
2570
2571
2572Local<Value> v8::Object::CheckedGetInternalField(int index) {
2573 if (IsDeadCheck("v8::Object::GetInternalField()")) return Local<Value>();
2574 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2575 if (!ApiCheck(index < obj->GetInternalFieldCount(),
2576 "v8::Object::GetInternalField()",
2577 "Reading internal field out of bounds")) {
2578 return Local<Value>();
2579 }
2580 i::Handle<i::Object> value(obj->GetInternalField(index));
2581 Local<Value> result = Utils::ToLocal(value);
2582#ifdef DEBUG
2583 Local<Value> unchecked = UncheckedGetInternalField(index);
2584 ASSERT(unchecked.IsEmpty() || (unchecked == result));
2585#endif
2586 return result;
2587}
2588
2589
2590void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
2591 if (IsDeadCheck("v8::Object::SetInternalField()")) return;
2592 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2593 if (!ApiCheck(index < obj->GetInternalFieldCount(),
2594 "v8::Object::SetInternalField()",
2595 "Writing internal field out of bounds")) {
2596 return;
2597 }
2598 ENTER_V8;
2599 i::Handle<i::Object> val = Utils::OpenHandle(*value);
2600 obj->SetInternalField(index, *val);
2601}
2602
2603
2604void v8::Object::SetPointerInInternalField(int index, void* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00002605 i::Object* as_object = reinterpret_cast<i::Object*>(value);
2606 if (as_object->IsSmi()) {
2607 Utils::OpenHandle(this)->SetInternalField(index, as_object);
2608 return;
2609 }
2610 HandleScope scope;
2611 i::Handle<i::Proxy> proxy =
2612 i::Factory::NewProxy(reinterpret_cast<i::Address>(value), i::TENURED);
2613 if (!proxy.is_null())
2614 Utils::OpenHandle(this)->SetInternalField(index, *proxy);
Steve Blocka7e24c12009-10-30 11:49:00 +00002615}
2616
2617
2618// --- E n v i r o n m e n t ---
2619
2620bool v8::V8::Initialize() {
2621 if (i::V8::IsRunning()) return true;
2622 ENTER_V8;
2623 HandleScope scope;
2624 if (i::Snapshot::Initialize()) {
2625 return true;
2626 } else {
2627 return i::V8::Initialize(NULL);
2628 }
2629}
2630
2631
2632bool v8::V8::Dispose() {
2633 i::V8::TearDown();
2634 return true;
2635}
2636
2637
Steve Block3ce2e202009-11-05 08:53:23 +00002638HeapStatistics::HeapStatistics(): total_heap_size_(0), used_heap_size_(0) { }
2639
2640
2641void v8::V8::GetHeapStatistics(HeapStatistics* heap_statistics) {
2642 heap_statistics->set_total_heap_size(i::Heap::CommittedMemory());
2643 heap_statistics->set_used_heap_size(i::Heap::SizeOfObjects());
2644}
2645
2646
2647bool v8::V8::IdleNotification() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002648 // Returning true tells the caller that it need not
2649 // continue to call IdleNotification.
2650 if (!i::V8::IsRunning()) return true;
Steve Block3ce2e202009-11-05 08:53:23 +00002651 return i::V8::IdleNotification();
Steve Blocka7e24c12009-10-30 11:49:00 +00002652}
2653
2654
2655void v8::V8::LowMemoryNotification() {
2656#if defined(ANDROID)
2657 if (!i::V8::IsRunning()) return;
2658 i::Heap::CollectAllGarbage(true);
2659#endif
2660}
2661
2662
2663const char* v8::V8::GetVersion() {
2664 static v8::internal::EmbeddedVector<char, 128> buffer;
2665 v8::internal::Version::GetString(buffer);
2666 return buffer.start();
2667}
2668
2669
2670static i::Handle<i::FunctionTemplateInfo>
2671 EnsureConstructor(i::Handle<i::ObjectTemplateInfo> templ) {
2672 if (templ->constructor()->IsUndefined()) {
2673 Local<FunctionTemplate> constructor = FunctionTemplate::New();
2674 Utils::OpenHandle(*constructor)->set_instance_template(*templ);
2675 templ->set_constructor(*Utils::OpenHandle(*constructor));
2676 }
2677 return i::Handle<i::FunctionTemplateInfo>(
2678 i::FunctionTemplateInfo::cast(templ->constructor()));
2679}
2680
2681
2682Persistent<Context> v8::Context::New(
2683 v8::ExtensionConfiguration* extensions,
2684 v8::Handle<ObjectTemplate> global_template,
2685 v8::Handle<Value> global_object) {
2686 EnsureInitialized("v8::Context::New()");
2687 LOG_API("Context::New");
2688 ON_BAILOUT("v8::Context::New()", return Persistent<Context>());
2689
2690 // Enter V8 via an ENTER_V8 scope.
2691 i::Handle<i::Context> env;
2692 {
2693 ENTER_V8;
2694#if defined(ANDROID)
2695 // On mobile device, full GC is expensive, leave it to the system to
2696 // decide when should make a full GC.
2697#else
2698 // Give the heap a chance to cleanup if we've disposed contexts.
2699 i::Heap::CollectAllGarbageIfContextDisposed();
2700#endif
2701 v8::Handle<ObjectTemplate> proxy_template = global_template;
2702 i::Handle<i::FunctionTemplateInfo> proxy_constructor;
2703 i::Handle<i::FunctionTemplateInfo> global_constructor;
2704
2705 if (!global_template.IsEmpty()) {
2706 // Make sure that the global_template has a constructor.
2707 global_constructor =
2708 EnsureConstructor(Utils::OpenHandle(*global_template));
2709
2710 // Create a fresh template for the global proxy object.
2711 proxy_template = ObjectTemplate::New();
2712 proxy_constructor =
2713 EnsureConstructor(Utils::OpenHandle(*proxy_template));
2714
2715 // Set the global template to be the prototype template of
2716 // global proxy template.
2717 proxy_constructor->set_prototype_template(
2718 *Utils::OpenHandle(*global_template));
2719
2720 // Migrate security handlers from global_template to
2721 // proxy_template. Temporarily removing access check
2722 // information from the global template.
2723 if (!global_constructor->access_check_info()->IsUndefined()) {
2724 proxy_constructor->set_access_check_info(
2725 global_constructor->access_check_info());
2726 proxy_constructor->set_needs_access_check(
2727 global_constructor->needs_access_check());
2728 global_constructor->set_needs_access_check(false);
2729 global_constructor->set_access_check_info(i::Heap::undefined_value());
2730 }
2731 }
2732
2733 // Create the environment.
2734 env = i::Bootstrapper::CreateEnvironment(
2735 Utils::OpenHandle(*global_object),
2736 proxy_template,
2737 extensions);
2738
2739 // Restore the access check info on the global template.
2740 if (!global_template.IsEmpty()) {
2741 ASSERT(!global_constructor.is_null());
2742 ASSERT(!proxy_constructor.is_null());
2743 global_constructor->set_access_check_info(
2744 proxy_constructor->access_check_info());
2745 global_constructor->set_needs_access_check(
2746 proxy_constructor->needs_access_check());
2747 }
2748 }
2749 // Leave V8.
2750
2751 if (env.is_null())
2752 return Persistent<Context>();
2753 return Persistent<Context>(Utils::ToLocal(env));
2754}
2755
2756
2757void v8::Context::SetSecurityToken(Handle<Value> token) {
2758 if (IsDeadCheck("v8::Context::SetSecurityToken()")) return;
2759 ENTER_V8;
2760 i::Handle<i::Context> env = Utils::OpenHandle(this);
2761 i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
2762 env->set_security_token(*token_handle);
2763}
2764
2765
2766void v8::Context::UseDefaultSecurityToken() {
2767 if (IsDeadCheck("v8::Context::UseDefaultSecurityToken()")) return;
2768 ENTER_V8;
2769 i::Handle<i::Context> env = Utils::OpenHandle(this);
2770 env->set_security_token(env->global());
2771}
2772
2773
2774Handle<Value> v8::Context::GetSecurityToken() {
2775 if (IsDeadCheck("v8::Context::GetSecurityToken()")) return Handle<Value>();
2776 i::Handle<i::Context> env = Utils::OpenHandle(this);
2777 i::Object* security_token = env->security_token();
2778 i::Handle<i::Object> token_handle(security_token);
2779 return Utils::ToLocal(token_handle);
2780}
2781
2782
2783bool Context::HasOutOfMemoryException() {
2784 i::Handle<i::Context> env = Utils::OpenHandle(this);
2785 return env->has_out_of_memory();
2786}
2787
2788
2789bool Context::InContext() {
2790 return i::Top::context() != NULL;
2791}
2792
2793
2794v8::Local<v8::Context> Context::GetEntered() {
2795 if (IsDeadCheck("v8::Context::GetEntered()")) return Local<Context>();
2796 i::Handle<i::Object> last = thread_local.LastEnteredContext();
2797 if (last.is_null()) return Local<Context>();
2798 i::Handle<i::Context> context = i::Handle<i::Context>::cast(last);
2799 return Utils::ToLocal(context);
2800}
2801
2802
2803v8::Local<v8::Context> Context::GetCurrent() {
2804 if (IsDeadCheck("v8::Context::GetCurrent()")) return Local<Context>();
Steve Block3ce2e202009-11-05 08:53:23 +00002805 i::Handle<i::Object> current = i::Top::global_context();
2806 if (current.is_null()) return Local<Context>();
2807 i::Handle<i::Context> context = i::Handle<i::Context>::cast(current);
Steve Blocka7e24c12009-10-30 11:49:00 +00002808 return Utils::ToLocal(context);
2809}
2810
2811
2812v8::Local<v8::Context> Context::GetCalling() {
2813 if (IsDeadCheck("v8::Context::GetCalling()")) return Local<Context>();
2814 i::Handle<i::Object> calling = i::Top::GetCallingGlobalContext();
2815 if (calling.is_null()) return Local<Context>();
2816 i::Handle<i::Context> context = i::Handle<i::Context>::cast(calling);
2817 return Utils::ToLocal(context);
2818}
2819
2820
2821v8::Local<v8::Object> Context::Global() {
2822 if (IsDeadCheck("v8::Context::Global()")) return Local<v8::Object>();
2823 i::Object** ctx = reinterpret_cast<i::Object**>(this);
2824 i::Handle<i::Context> context =
2825 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
2826 i::Handle<i::Object> global(context->global_proxy());
2827 return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
2828}
2829
2830
2831void Context::DetachGlobal() {
2832 if (IsDeadCheck("v8::Context::DetachGlobal()")) return;
2833 ENTER_V8;
2834 i::Object** ctx = reinterpret_cast<i::Object**>(this);
2835 i::Handle<i::Context> context =
2836 i::Handle<i::Context>::cast(i::Handle<i::Object>(ctx));
2837 i::Bootstrapper::DetachGlobal(context);
2838}
2839
2840
2841Local<v8::Object> ObjectTemplate::NewInstance() {
2842 ON_BAILOUT("v8::ObjectTemplate::NewInstance()", return Local<v8::Object>());
2843 LOG_API("ObjectTemplate::NewInstance");
2844 ENTER_V8;
2845 EXCEPTION_PREAMBLE();
2846 i::Handle<i::Object> obj =
2847 i::Execution::InstantiateObject(Utils::OpenHandle(this),
2848 &has_pending_exception);
2849 EXCEPTION_BAILOUT_CHECK(Local<v8::Object>());
2850 return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
2851}
2852
2853
2854Local<v8::Function> FunctionTemplate::GetFunction() {
2855 ON_BAILOUT("v8::FunctionTemplate::GetFunction()",
2856 return Local<v8::Function>());
2857 LOG_API("FunctionTemplate::GetFunction");
2858 ENTER_V8;
2859 EXCEPTION_PREAMBLE();
2860 i::Handle<i::Object> obj =
2861 i::Execution::InstantiateFunction(Utils::OpenHandle(this),
2862 &has_pending_exception);
2863 EXCEPTION_BAILOUT_CHECK(Local<v8::Function>());
2864 return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
2865}
2866
2867
2868bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
2869 ON_BAILOUT("v8::FunctionTemplate::HasInstanceOf()", return false);
2870 i::Object* obj = *Utils::OpenHandle(*value);
2871 return obj->IsInstanceOf(*Utils::OpenHandle(this));
2872}
2873
2874
2875static Local<External> ExternalNewImpl(void* data) {
2876 return Utils::ToLocal(i::Factory::NewProxy(static_cast<i::Address>(data)));
2877}
2878
2879static void* ExternalValueImpl(i::Handle<i::Object> obj) {
2880 return reinterpret_cast<void*>(i::Proxy::cast(*obj)->proxy());
2881}
2882
2883
Steve Blocka7e24c12009-10-30 11:49:00 +00002884Local<Value> v8::External::Wrap(void* data) {
2885 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
2886 LOG_API("External::Wrap");
2887 EnsureInitialized("v8::External::Wrap()");
2888 ENTER_V8;
Steve Block3ce2e202009-11-05 08:53:23 +00002889 i::Object* as_object = reinterpret_cast<i::Object*>(data);
2890 if (as_object->IsSmi()) {
2891 return Utils::ToLocal(i::Handle<i::Object>(as_object));
Steve Blocka7e24c12009-10-30 11:49:00 +00002892 }
2893 return ExternalNewImpl(data);
2894}
2895
2896
Steve Block3ce2e202009-11-05 08:53:23 +00002897void* v8::Object::SlowGetPointerFromInternalField(int index) {
2898 i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
2899 i::Object* value = obj->GetInternalField(index);
2900 if (value->IsSmi()) {
2901 return value;
2902 } else if (value->IsProxy()) {
2903 return reinterpret_cast<void*>(i::Proxy::cast(value)->proxy());
2904 } else {
2905 return NULL;
2906 }
2907}
2908
2909
Steve Blocka7e24c12009-10-30 11:49:00 +00002910void* v8::External::FullUnwrap(v8::Handle<v8::Value> wrapper) {
2911 if (IsDeadCheck("v8::External::Unwrap()")) return 0;
2912 i::Handle<i::Object> obj = Utils::OpenHandle(*wrapper);
2913 void* result;
2914 if (obj->IsSmi()) {
2915 // The external value was an aligned pointer.
Steve Block3ce2e202009-11-05 08:53:23 +00002916 result = *obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00002917 } else if (obj->IsProxy()) {
2918 result = ExternalValueImpl(obj);
2919 } else {
2920 result = NULL;
2921 }
2922 ASSERT_EQ(result, QuickUnwrap(wrapper));
2923 return result;
2924}
2925
2926
2927Local<External> v8::External::New(void* data) {
2928 STATIC_ASSERT(sizeof(data) == sizeof(i::Address));
2929 LOG_API("External::New");
2930 EnsureInitialized("v8::External::New()");
2931 ENTER_V8;
2932 return ExternalNewImpl(data);
2933}
2934
2935
2936void* External::Value() const {
2937 if (IsDeadCheck("v8::External::Value()")) return 0;
2938 i::Handle<i::Object> obj = Utils::OpenHandle(this);
2939 return ExternalValueImpl(obj);
2940}
2941
2942
2943Local<String> v8::String::Empty() {
2944 EnsureInitialized("v8::String::Empty()");
2945 LOG_API("String::Empty()");
2946 return Utils::ToLocal(i::Factory::empty_symbol());
2947}
2948
2949
2950Local<String> v8::String::New(const char* data, int length) {
2951 EnsureInitialized("v8::String::New()");
2952 LOG_API("String::New(char)");
2953 if (length == 0) return Empty();
2954 ENTER_V8;
2955 if (length == -1) length = strlen(data);
2956 i::Handle<i::String> result =
2957 i::Factory::NewStringFromUtf8(i::Vector<const char>(data, length));
2958 return Utils::ToLocal(result);
2959}
2960
2961
Steve Block3ce2e202009-11-05 08:53:23 +00002962Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
2963 EnsureInitialized("v8::String::New()");
2964 LOG_API("String::New(char)");
2965 ENTER_V8;
2966 i::Handle<i::String> left_string = Utils::OpenHandle(*left);
2967 i::Handle<i::String> right_string = Utils::OpenHandle(*right);
2968 i::Handle<i::String> result = i::Factory::NewConsString(left_string,
2969 right_string);
2970 return Utils::ToLocal(result);
2971}
2972
2973
Steve Blocka7e24c12009-10-30 11:49:00 +00002974Local<String> v8::String::NewUndetectable(const char* data, int length) {
2975 EnsureInitialized("v8::String::NewUndetectable()");
2976 LOG_API("String::NewUndetectable(char)");
2977 ENTER_V8;
2978 if (length == -1) length = strlen(data);
2979 i::Handle<i::String> result =
2980 i::Factory::NewStringFromUtf8(i::Vector<const char>(data, length));
2981 result->MarkAsUndetectable();
2982 return Utils::ToLocal(result);
2983}
2984
2985
2986static int TwoByteStringLength(const uint16_t* data) {
2987 int length = 0;
2988 while (data[length] != '\0') length++;
2989 return length;
2990}
2991
2992
2993Local<String> v8::String::New(const uint16_t* data, int length) {
2994 EnsureInitialized("v8::String::New()");
2995 LOG_API("String::New(uint16_)");
2996 if (length == 0) return Empty();
2997 ENTER_V8;
2998 if (length == -1) length = TwoByteStringLength(data);
2999 i::Handle<i::String> result =
3000 i::Factory::NewStringFromTwoByte(i::Vector<const uint16_t>(data, length));
3001 return Utils::ToLocal(result);
3002}
3003
3004
3005Local<String> v8::String::NewUndetectable(const uint16_t* data, int length) {
3006 EnsureInitialized("v8::String::NewUndetectable()");
3007 LOG_API("String::NewUndetectable(uint16_)");
3008 ENTER_V8;
3009 if (length == -1) length = TwoByteStringLength(data);
3010 i::Handle<i::String> result =
3011 i::Factory::NewStringFromTwoByte(i::Vector<const uint16_t>(data, length));
3012 result->MarkAsUndetectable();
3013 return Utils::ToLocal(result);
3014}
3015
3016
3017i::Handle<i::String> NewExternalStringHandle(
3018 v8::String::ExternalStringResource* resource) {
3019 i::Handle<i::String> result =
3020 i::Factory::NewExternalStringFromTwoByte(resource);
3021 return result;
3022}
3023
3024
3025i::Handle<i::String> NewExternalAsciiStringHandle(
3026 v8::String::ExternalAsciiStringResource* resource) {
3027 i::Handle<i::String> result =
3028 i::Factory::NewExternalStringFromAscii(resource);
3029 return result;
3030}
3031
3032
3033static void DisposeExternalString(v8::Persistent<v8::Value> obj,
3034 void* parameter) {
3035 ENTER_V8;
3036 i::ExternalTwoByteString* str =
3037 i::ExternalTwoByteString::cast(*Utils::OpenHandle(*obj));
3038
3039 // External symbols are deleted when they are pruned out of the symbol
3040 // table. Generally external symbols are not registered with the weak handle
3041 // callbacks unless they are upgraded to a symbol after being externalized.
3042 if (!str->IsSymbol()) {
3043 v8::String::ExternalStringResource* resource =
3044 reinterpret_cast<v8::String::ExternalStringResource*>(parameter);
3045 if (resource != NULL) {
3046 const size_t total_size = resource->length() * sizeof(*resource->data());
3047 i::Counters::total_external_string_memory.Decrement(total_size);
3048
3049 // The object will continue to live in the JavaScript heap until the
3050 // handle is entirely cleaned out by the next GC. For example the
3051 // destructor for the resource below could bring it back to life again.
3052 // Which is why we make sure to not have a dangling pointer here.
3053 str->set_resource(NULL);
3054 delete resource;
3055 }
3056 }
3057
3058 // In any case we do not need this handle any longer.
3059 obj.Dispose();
3060}
3061
3062
3063static void DisposeExternalAsciiString(v8::Persistent<v8::Value> obj,
3064 void* parameter) {
3065 ENTER_V8;
3066 i::ExternalAsciiString* str =
3067 i::ExternalAsciiString::cast(*Utils::OpenHandle(*obj));
3068
3069 // External symbols are deleted when they are pruned out of the symbol
3070 // table. Generally external symbols are not registered with the weak handle
3071 // callbacks unless they are upgraded to a symbol after being externalized.
3072 if (!str->IsSymbol()) {
3073 v8::String::ExternalAsciiStringResource* resource =
3074 reinterpret_cast<v8::String::ExternalAsciiStringResource*>(parameter);
3075 if (resource != NULL) {
3076 const size_t total_size = resource->length() * sizeof(*resource->data());
3077 i::Counters::total_external_string_memory.Decrement(total_size);
3078
3079 // The object will continue to live in the JavaScript heap until the
3080 // handle is entirely cleaned out by the next GC. For example the
3081 // destructor for the resource below could bring it back to life again.
3082 // Which is why we make sure to not have a dangling pointer here.
3083 str->set_resource(NULL);
3084 delete resource;
3085 }
3086 }
3087
3088 // In any case we do not need this handle any longer.
3089 obj.Dispose();
3090}
3091
3092
3093Local<String> v8::String::NewExternal(
3094 v8::String::ExternalStringResource* resource) {
3095 EnsureInitialized("v8::String::NewExternal()");
3096 LOG_API("String::NewExternal");
3097 ENTER_V8;
3098 const size_t total_size = resource->length() * sizeof(*resource->data());
3099 i::Counters::total_external_string_memory.Increment(total_size);
3100 i::Handle<i::String> result = NewExternalStringHandle(resource);
3101 i::Handle<i::Object> handle = i::GlobalHandles::Create(*result);
3102 i::GlobalHandles::MakeWeak(handle.location(),
3103 resource,
3104 &DisposeExternalString);
3105 return Utils::ToLocal(result);
3106}
3107
3108
3109bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
3110 if (IsDeadCheck("v8::String::MakeExternal()")) return false;
3111 if (this->IsExternal()) return false; // Already an external string.
3112 ENTER_V8;
3113 i::Handle<i::String> obj = Utils::OpenHandle(this);
3114 bool result = obj->MakeExternal(resource);
3115 if (result && !obj->IsSymbol()) {
3116 // Operation was successful and the string is not a symbol. In this case
3117 // we need to make sure that the we call the destructor for the external
3118 // resource when no strong references to the string remain.
3119 i::Handle<i::Object> handle = i::GlobalHandles::Create(*obj);
3120 i::GlobalHandles::MakeWeak(handle.location(),
3121 resource,
3122 &DisposeExternalString);
3123 }
3124 return result;
3125}
3126
3127
3128Local<String> v8::String::NewExternal(
3129 v8::String::ExternalAsciiStringResource* resource) {
3130 EnsureInitialized("v8::String::NewExternal()");
3131 LOG_API("String::NewExternal");
3132 ENTER_V8;
3133 const size_t total_size = resource->length() * sizeof(*resource->data());
3134 i::Counters::total_external_string_memory.Increment(total_size);
3135 i::Handle<i::String> result = NewExternalAsciiStringHandle(resource);
3136 i::Handle<i::Object> handle = i::GlobalHandles::Create(*result);
3137 i::GlobalHandles::MakeWeak(handle.location(),
3138 resource,
3139 &DisposeExternalAsciiString);
3140 return Utils::ToLocal(result);
3141}
3142
3143
3144bool v8::String::MakeExternal(
3145 v8::String::ExternalAsciiStringResource* resource) {
3146 if (IsDeadCheck("v8::String::MakeExternal()")) return false;
3147 if (this->IsExternal()) return false; // Already an external string.
3148 ENTER_V8;
3149 i::Handle<i::String> obj = Utils::OpenHandle(this);
3150 bool result = obj->MakeExternal(resource);
3151 if (result && !obj->IsSymbol()) {
3152 // Operation was successful and the string is not a symbol. In this case
3153 // we need to make sure that the we call the destructor for the external
3154 // resource when no strong references to the string remain.
3155 i::Handle<i::Object> handle = i::GlobalHandles::Create(*obj);
3156 i::GlobalHandles::MakeWeak(handle.location(),
3157 resource,
3158 &DisposeExternalAsciiString);
3159 }
3160 return result;
3161}
3162
3163
3164bool v8::String::CanMakeExternal() {
3165 if (IsDeadCheck("v8::String::CanMakeExternal()")) return false;
3166 i::Handle<i::String> obj = Utils::OpenHandle(this);
3167 int size = obj->Size(); // Byte size of the original string.
3168 if (size < i::ExternalString::kSize)
3169 return false;
3170 i::StringShape shape(*obj);
3171 return !shape.IsExternal();
3172}
3173
3174
3175Local<v8::Object> v8::Object::New() {
3176 EnsureInitialized("v8::Object::New()");
3177 LOG_API("Object::New");
3178 ENTER_V8;
3179 i::Handle<i::JSObject> obj =
3180 i::Factory::NewJSObject(i::Top::object_function());
3181 return Utils::ToLocal(obj);
3182}
3183
3184
3185Local<v8::Value> v8::Date::New(double time) {
3186 EnsureInitialized("v8::Date::New()");
3187 LOG_API("Date::New");
3188 ENTER_V8;
3189 EXCEPTION_PREAMBLE();
3190 i::Handle<i::Object> obj =
3191 i::Execution::NewDate(time, &has_pending_exception);
3192 EXCEPTION_BAILOUT_CHECK(Local<v8::Value>());
3193 return Utils::ToLocal(obj);
3194}
3195
3196
3197double v8::Date::NumberValue() const {
3198 if (IsDeadCheck("v8::Date::NumberValue()")) return 0;
3199 LOG_API("Date::NumberValue");
3200 i::Handle<i::Object> obj = Utils::OpenHandle(this);
3201 i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
3202 return jsvalue->value()->Number();
3203}
3204
3205
3206Local<v8::Array> v8::Array::New(int length) {
3207 EnsureInitialized("v8::Array::New()");
3208 LOG_API("Array::New");
3209 ENTER_V8;
3210 i::Handle<i::JSArray> obj = i::Factory::NewJSArray(length);
3211 return Utils::ToLocal(obj);
3212}
3213
3214
3215uint32_t v8::Array::Length() const {
3216 if (IsDeadCheck("v8::Array::Length()")) return 0;
3217 i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
3218 i::Object* length = obj->length();
3219 if (length->IsSmi()) {
3220 return i::Smi::cast(length)->value();
3221 } else {
3222 return static_cast<uint32_t>(length->Number());
3223 }
3224}
3225
3226
3227Local<Object> Array::CloneElementAt(uint32_t index) {
3228 ON_BAILOUT("v8::Array::CloneElementAt()", return Local<Object>());
3229 i::Handle<i::JSObject> self = Utils::OpenHandle(this);
3230 if (!self->HasFastElements()) {
3231 return Local<Object>();
3232 }
3233 i::FixedArray* elms = i::FixedArray::cast(self->elements());
3234 i::Object* paragon = elms->get(index);
3235 if (!paragon->IsJSObject()) {
3236 return Local<Object>();
3237 }
3238 i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
3239 EXCEPTION_PREAMBLE();
3240 i::Handle<i::JSObject> result = i::Copy(paragon_handle);
3241 has_pending_exception = result.is_null();
3242 EXCEPTION_BAILOUT_CHECK(Local<Object>());
3243 return Utils::ToLocal(result);
3244}
3245
3246
3247Local<String> v8::String::NewSymbol(const char* data, int length) {
3248 EnsureInitialized("v8::String::NewSymbol()");
3249 LOG_API("String::NewSymbol(char)");
3250 ENTER_V8;
3251 if (length == -1) length = strlen(data);
3252 i::Handle<i::String> result =
3253 i::Factory::LookupSymbol(i::Vector<const char>(data, length));
3254 return Utils::ToLocal(result);
3255}
3256
3257
3258Local<Number> v8::Number::New(double value) {
3259 EnsureInitialized("v8::Number::New()");
3260 ENTER_V8;
3261 i::Handle<i::Object> result = i::Factory::NewNumber(value);
3262 return Utils::NumberToLocal(result);
3263}
3264
3265
3266Local<Integer> v8::Integer::New(int32_t value) {
3267 EnsureInitialized("v8::Integer::New()");
3268 if (i::Smi::IsValid(value)) {
3269 return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value)));
3270 }
3271 ENTER_V8;
3272 i::Handle<i::Object> result = i::Factory::NewNumber(value);
3273 return Utils::IntegerToLocal(result);
3274}
3275
3276
Steve Block3ce2e202009-11-05 08:53:23 +00003277Local<Integer> Integer::NewFromUnsigned(uint32_t value) {
3278 bool fits_into_int32_t = (value & (1 << 31)) == 0;
3279 if (fits_into_int32_t) {
3280 return Integer::New(static_cast<int32_t>(value));
3281 }
3282 ENTER_V8;
3283 i::Handle<i::Object> result = i::Factory::NewNumber(value);
3284 return Utils::IntegerToLocal(result);
3285}
3286
3287
Steve Blocka7e24c12009-10-30 11:49:00 +00003288void V8::IgnoreOutOfMemoryException() {
3289 thread_local.set_ignore_out_of_memory(true);
3290}
3291
3292
3293bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
3294 EnsureInitialized("v8::V8::AddMessageListener()");
3295 ON_BAILOUT("v8::V8::AddMessageListener()", return false);
3296 ENTER_V8;
3297 HandleScope scope;
3298 NeanderArray listeners(i::Factory::message_listeners());
3299 NeanderObject obj(2);
3300 obj.set(0, *i::Factory::NewProxy(FUNCTION_ADDR(that)));
3301 obj.set(1, data.IsEmpty() ?
3302 i::Heap::undefined_value() :
3303 *Utils::OpenHandle(*data));
3304 listeners.add(obj.value());
3305 return true;
3306}
3307
3308
3309void V8::RemoveMessageListeners(MessageCallback that) {
3310 EnsureInitialized("v8::V8::RemoveMessageListener()");
3311 ON_BAILOUT("v8::V8::RemoveMessageListeners()", return);
3312 ENTER_V8;
3313 HandleScope scope;
3314 NeanderArray listeners(i::Factory::message_listeners());
3315 for (int i = 0; i < listeners.length(); i++) {
3316 if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
3317
3318 NeanderObject listener(i::JSObject::cast(listeners.get(i)));
3319 i::Handle<i::Proxy> callback_obj(i::Proxy::cast(listener.get(0)));
3320 if (callback_obj->proxy() == FUNCTION_ADDR(that)) {
3321 listeners.set(i, i::Heap::undefined_value());
3322 }
3323 }
3324}
3325
3326
3327void V8::SetCounterFunction(CounterLookupCallback callback) {
3328 if (IsDeadCheck("v8::V8::SetCounterFunction()")) return;
3329 i::StatsTable::SetCounterFunction(callback);
3330}
3331
3332void V8::SetCreateHistogramFunction(CreateHistogramCallback callback) {
3333 if (IsDeadCheck("v8::V8::SetCreateHistogramFunction()")) return;
3334 i::StatsTable::SetCreateHistogramFunction(callback);
3335}
3336
3337void V8::SetAddHistogramSampleFunction(AddHistogramSampleCallback callback) {
3338 if (IsDeadCheck("v8::V8::SetAddHistogramSampleFunction()")) return;
3339 i::StatsTable::SetAddHistogramSampleFunction(callback);
3340}
3341
3342void V8::EnableSlidingStateWindow() {
3343 if (IsDeadCheck("v8::V8::EnableSlidingStateWindow()")) return;
3344 i::Logger::EnableSlidingStateWindow();
3345}
3346
3347
3348void V8::SetFailedAccessCheckCallbackFunction(
3349 FailedAccessCheckCallback callback) {
3350 if (IsDeadCheck("v8::V8::SetFailedAccessCheckCallbackFunction()")) return;
3351 i::Top::SetFailedAccessCheckCallback(callback);
3352}
3353
3354
3355void V8::AddObjectGroup(Persistent<Value>* objects, size_t length) {
3356 if (IsDeadCheck("v8::V8::AddObjectGroup()")) return;
3357 STATIC_ASSERT(sizeof(Persistent<Value>) == sizeof(i::Object**));
3358 i::GlobalHandles::AddGroup(reinterpret_cast<i::Object***>(objects), length);
3359}
3360
3361
3362int V8::AdjustAmountOfExternalAllocatedMemory(int change_in_bytes) {
3363 if (IsDeadCheck("v8::V8::AdjustAmountOfExternalAllocatedMemory()")) return 0;
3364 return i::Heap::AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
3365}
3366
3367
3368void V8::SetGlobalGCPrologueCallback(GCCallback callback) {
3369 if (IsDeadCheck("v8::V8::SetGlobalGCPrologueCallback()")) return;
3370 i::Heap::SetGlobalGCPrologueCallback(callback);
3371}
3372
3373
3374void V8::SetGlobalGCEpilogueCallback(GCCallback callback) {
3375 if (IsDeadCheck("v8::V8::SetGlobalGCEpilogueCallback()")) return;
3376 i::Heap::SetGlobalGCEpilogueCallback(callback);
3377}
3378
3379
3380void V8::PauseProfiler() {
3381#ifdef ENABLE_LOGGING_AND_PROFILING
3382 i::Logger::PauseProfiler(PROFILER_MODULE_CPU);
3383#endif
3384}
3385
3386
3387void V8::ResumeProfiler() {
3388#ifdef ENABLE_LOGGING_AND_PROFILING
3389 i::Logger::ResumeProfiler(PROFILER_MODULE_CPU);
3390#endif
3391}
3392
3393
3394bool V8::IsProfilerPaused() {
3395#ifdef ENABLE_LOGGING_AND_PROFILING
3396 return i::Logger::GetActiveProfilerModules() & PROFILER_MODULE_CPU;
3397#else
3398 return true;
3399#endif
3400}
3401
3402
3403void V8::ResumeProfilerEx(int flags) {
3404#ifdef ENABLE_LOGGING_AND_PROFILING
3405 if (flags & PROFILER_MODULE_HEAP_SNAPSHOT) {
3406 // Snapshot mode: resume modules, perform GC, then pause only
3407 // those modules which haven't been started prior to making a
3408 // snapshot.
3409
3410 // Reset snapshot flag and CPU module flags.
3411 flags &= ~(PROFILER_MODULE_HEAP_SNAPSHOT | PROFILER_MODULE_CPU);
3412 const int current_flags = i::Logger::GetActiveProfilerModules();
3413 i::Logger::ResumeProfiler(flags);
3414 i::Heap::CollectAllGarbage(false);
3415 i::Logger::PauseProfiler(~current_flags & flags);
3416 } else {
3417 i::Logger::ResumeProfiler(flags);
3418 }
3419#endif
3420}
3421
3422
3423void V8::PauseProfilerEx(int flags) {
3424#ifdef ENABLE_LOGGING_AND_PROFILING
3425 i::Logger::PauseProfiler(flags);
3426#endif
3427}
3428
3429
3430int V8::GetActiveProfilerModules() {
3431#ifdef ENABLE_LOGGING_AND_PROFILING
3432 return i::Logger::GetActiveProfilerModules();
3433#else
3434 return PROFILER_MODULE_NONE;
3435#endif
3436}
3437
3438
3439int V8::GetLogLines(int from_pos, char* dest_buf, int max_size) {
3440#ifdef ENABLE_LOGGING_AND_PROFILING
3441 return i::Logger::GetLogLines(from_pos, dest_buf, max_size);
3442#endif
3443 return 0;
3444}
3445
3446
3447int V8::GetCurrentThreadId() {
3448 API_ENTRY_CHECK("V8::GetCurrentThreadId()");
3449 EnsureInitialized("V8::GetCurrentThreadId()");
3450 return i::Top::thread_id();
3451}
3452
3453
3454void V8::TerminateExecution(int thread_id) {
3455 if (!i::V8::IsRunning()) return;
3456 API_ENTRY_CHECK("V8::GetCurrentThreadId()");
3457 // If the thread_id identifies the current thread just terminate
3458 // execution right away. Otherwise, ask the thread manager to
3459 // terminate the thread with the given id if any.
3460 if (thread_id == i::Top::thread_id()) {
3461 i::StackGuard::TerminateExecution();
3462 } else {
3463 i::ThreadManager::TerminateExecution(thread_id);
3464 }
3465}
3466
3467
3468void V8::TerminateExecution() {
3469 if (!i::V8::IsRunning()) return;
3470 i::StackGuard::TerminateExecution();
3471}
3472
3473
3474String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj) {
3475 EnsureInitialized("v8::String::Utf8Value::Utf8Value()");
3476 if (obj.IsEmpty()) {
3477 str_ = NULL;
3478 length_ = 0;
3479 return;
3480 }
3481 ENTER_V8;
3482 HandleScope scope;
3483 TryCatch try_catch;
3484 Handle<String> str = obj->ToString();
3485 if (str.IsEmpty()) {
3486 str_ = NULL;
3487 length_ = 0;
3488 } else {
3489 length_ = str->Utf8Length();
3490 str_ = i::NewArray<char>(length_ + 1);
3491 str->WriteUtf8(str_);
3492 }
3493}
3494
3495
3496String::Utf8Value::~Utf8Value() {
3497 i::DeleteArray(str_);
3498}
3499
3500
3501String::AsciiValue::AsciiValue(v8::Handle<v8::Value> obj) {
3502 EnsureInitialized("v8::String::AsciiValue::AsciiValue()");
3503 if (obj.IsEmpty()) {
3504 str_ = NULL;
3505 length_ = 0;
3506 return;
3507 }
3508 ENTER_V8;
3509 HandleScope scope;
3510 TryCatch try_catch;
3511 Handle<String> str = obj->ToString();
3512 if (str.IsEmpty()) {
3513 str_ = NULL;
3514 length_ = 0;
3515 } else {
3516 length_ = str->Length();
3517 str_ = i::NewArray<char>(length_ + 1);
3518 str->WriteAscii(str_);
3519 }
3520}
3521
3522
3523String::AsciiValue::~AsciiValue() {
3524 i::DeleteArray(str_);
3525}
3526
3527
3528String::Value::Value(v8::Handle<v8::Value> obj) {
3529 EnsureInitialized("v8::String::Value::Value()");
3530 if (obj.IsEmpty()) {
3531 str_ = NULL;
3532 length_ = 0;
3533 return;
3534 }
3535 ENTER_V8;
3536 HandleScope scope;
3537 TryCatch try_catch;
3538 Handle<String> str = obj->ToString();
3539 if (str.IsEmpty()) {
3540 str_ = NULL;
3541 length_ = 0;
3542 } else {
3543 length_ = str->Length();
3544 str_ = i::NewArray<uint16_t>(length_ + 1);
3545 str->Write(str_);
3546 }
3547}
3548
3549
3550String::Value::~Value() {
3551 i::DeleteArray(str_);
3552}
3553
3554Local<Value> Exception::RangeError(v8::Handle<v8::String> raw_message) {
3555 LOG_API("RangeError");
3556 ON_BAILOUT("v8::Exception::RangeError()", return Local<Value>());
3557 ENTER_V8;
3558 i::Object* error;
3559 {
3560 HandleScope scope;
3561 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3562 i::Handle<i::Object> result = i::Factory::NewRangeError(message);
3563 error = *result;
3564 }
3565 i::Handle<i::Object> result(error);
3566 return Utils::ToLocal(result);
3567}
3568
3569Local<Value> Exception::ReferenceError(v8::Handle<v8::String> raw_message) {
3570 LOG_API("ReferenceError");
3571 ON_BAILOUT("v8::Exception::ReferenceError()", return Local<Value>());
3572 ENTER_V8;
3573 i::Object* error;
3574 {
3575 HandleScope scope;
3576 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3577 i::Handle<i::Object> result = i::Factory::NewReferenceError(message);
3578 error = *result;
3579 }
3580 i::Handle<i::Object> result(error);
3581 return Utils::ToLocal(result);
3582}
3583
3584Local<Value> Exception::SyntaxError(v8::Handle<v8::String> raw_message) {
3585 LOG_API("SyntaxError");
3586 ON_BAILOUT("v8::Exception::SyntaxError()", return Local<Value>());
3587 ENTER_V8;
3588 i::Object* error;
3589 {
3590 HandleScope scope;
3591 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3592 i::Handle<i::Object> result = i::Factory::NewSyntaxError(message);
3593 error = *result;
3594 }
3595 i::Handle<i::Object> result(error);
3596 return Utils::ToLocal(result);
3597}
3598
3599Local<Value> Exception::TypeError(v8::Handle<v8::String> raw_message) {
3600 LOG_API("TypeError");
3601 ON_BAILOUT("v8::Exception::TypeError()", return Local<Value>());
3602 ENTER_V8;
3603 i::Object* error;
3604 {
3605 HandleScope scope;
3606 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3607 i::Handle<i::Object> result = i::Factory::NewTypeError(message);
3608 error = *result;
3609 }
3610 i::Handle<i::Object> result(error);
3611 return Utils::ToLocal(result);
3612}
3613
3614Local<Value> Exception::Error(v8::Handle<v8::String> raw_message) {
3615 LOG_API("Error");
3616 ON_BAILOUT("v8::Exception::Error()", return Local<Value>());
3617 ENTER_V8;
3618 i::Object* error;
3619 {
3620 HandleScope scope;
3621 i::Handle<i::String> message = Utils::OpenHandle(*raw_message);
3622 i::Handle<i::Object> result = i::Factory::NewError(message);
3623 error = *result;
3624 }
3625 i::Handle<i::Object> result(error);
3626 return Utils::ToLocal(result);
3627}
3628
3629
3630// --- D e b u g S u p p o r t ---
3631
3632#ifdef ENABLE_DEBUGGER_SUPPORT
3633bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
3634 EnsureInitialized("v8::Debug::SetDebugEventListener()");
3635 ON_BAILOUT("v8::Debug::SetDebugEventListener()", return false);
3636 ENTER_V8;
3637 HandleScope scope;
3638 i::Handle<i::Object> proxy = i::Factory::undefined_value();
3639 if (that != NULL) {
3640 proxy = i::Factory::NewProxy(FUNCTION_ADDR(that));
3641 }
3642 i::Debugger::SetEventListener(proxy, Utils::OpenHandle(*data));
3643 return true;
3644}
3645
3646
3647bool Debug::SetDebugEventListener(v8::Handle<v8::Object> that,
3648 Handle<Value> data) {
3649 ON_BAILOUT("v8::Debug::SetDebugEventListener()", return false);
3650 ENTER_V8;
3651 i::Debugger::SetEventListener(Utils::OpenHandle(*that),
3652 Utils::OpenHandle(*data));
3653 return true;
3654}
3655
3656
3657void Debug::DebugBreak() {
3658 if (!i::V8::IsRunning()) return;
3659 i::StackGuard::DebugBreak();
3660}
3661
3662
3663static v8::Debug::MessageHandler message_handler = NULL;
3664
3665static void MessageHandlerWrapper(const v8::Debug::Message& message) {
3666 if (message_handler) {
3667 v8::String::Value json(message.GetJSON());
3668 message_handler(*json, json.length(), message.GetClientData());
3669 }
3670}
3671
3672
3673void Debug::SetMessageHandler(v8::Debug::MessageHandler handler,
3674 bool message_handler_thread) {
3675 EnsureInitialized("v8::Debug::SetMessageHandler");
3676 ENTER_V8;
3677 // Message handler thread not supported any more. Parameter temporally left in
3678 // the API for client compatability reasons.
3679 CHECK(!message_handler_thread);
3680
3681 // TODO(sgjesse) support the old message handler API through a simple wrapper.
3682 message_handler = handler;
3683 if (message_handler != NULL) {
3684 i::Debugger::SetMessageHandler(MessageHandlerWrapper);
3685 } else {
3686 i::Debugger::SetMessageHandler(NULL);
3687 }
3688}
3689
3690
3691void Debug::SetMessageHandler2(v8::Debug::MessageHandler2 handler) {
3692 EnsureInitialized("v8::Debug::SetMessageHandler");
3693 ENTER_V8;
3694 HandleScope scope;
3695 i::Debugger::SetMessageHandler(handler);
3696}
3697
3698
3699void Debug::SendCommand(const uint16_t* command, int length,
3700 ClientData* client_data) {
3701 if (!i::V8::IsRunning()) return;
3702 i::Debugger::ProcessCommand(i::Vector<const uint16_t>(command, length),
3703 client_data);
3704}
3705
3706
3707void Debug::SetHostDispatchHandler(HostDispatchHandler handler,
3708 int period) {
3709 EnsureInitialized("v8::Debug::SetHostDispatchHandler");
3710 ENTER_V8;
3711 i::Debugger::SetHostDispatchHandler(handler, period);
3712}
3713
3714
3715Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
3716 v8::Handle<v8::Value> data) {
3717 if (!i::V8::IsRunning()) return Local<Value>();
3718 ON_BAILOUT("v8::Debug::Call()", return Local<Value>());
3719 ENTER_V8;
3720 i::Handle<i::Object> result;
3721 EXCEPTION_PREAMBLE();
3722 if (data.IsEmpty()) {
3723 result = i::Debugger::Call(Utils::OpenHandle(*fun),
3724 i::Factory::undefined_value(),
3725 &has_pending_exception);
3726 } else {
3727 result = i::Debugger::Call(Utils::OpenHandle(*fun),
3728 Utils::OpenHandle(*data),
3729 &has_pending_exception);
3730 }
3731 EXCEPTION_BAILOUT_CHECK(Local<Value>());
3732 return Utils::ToLocal(result);
3733}
3734
3735
3736Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
3737 if (!i::V8::IsRunning()) return Local<Value>();
3738 ON_BAILOUT("v8::Debug::GetMirror()", return Local<Value>());
3739 ENTER_V8;
3740 v8::HandleScope scope;
3741 i::Debug::Load();
3742 i::Handle<i::JSObject> debug(i::Debug::debug_context()->global());
3743 i::Handle<i::String> name = i::Factory::LookupAsciiSymbol("MakeMirror");
3744 i::Handle<i::Object> fun_obj = i::GetProperty(debug, name);
3745 i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
3746 v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
3747 const int kArgc = 1;
3748 v8::Handle<v8::Value> argv[kArgc] = { obj };
3749 EXCEPTION_PREAMBLE();
3750 v8::Handle<v8::Value> result = v8_fun->Call(Utils::ToLocal(debug),
3751 kArgc,
3752 argv);
3753 EXCEPTION_BAILOUT_CHECK(Local<Value>());
3754 return scope.Close(result);
3755}
3756
3757
3758bool Debug::EnableAgent(const char* name, int port) {
3759 return i::Debugger::StartAgent(name, port);
3760}
3761#endif // ENABLE_DEBUGGER_SUPPORT
3762
3763namespace internal {
3764
3765
3766HandleScopeImplementer* HandleScopeImplementer::instance() {
3767 return &thread_local;
3768}
3769
3770
3771void HandleScopeImplementer::FreeThreadResources() {
3772 thread_local.Free();
3773}
3774
3775
3776char* HandleScopeImplementer::ArchiveThread(char* storage) {
3777 return thread_local.ArchiveThreadHelper(storage);
3778}
3779
3780
3781char* HandleScopeImplementer::ArchiveThreadHelper(char* storage) {
3782 v8::ImplementationUtilities::HandleScopeData* current =
3783 v8::ImplementationUtilities::CurrentHandleScope();
3784 handle_scope_data_ = *current;
3785 memcpy(storage, this, sizeof(*this));
3786
3787 ResetAfterArchive();
3788 current->Initialize();
3789
3790 return storage + ArchiveSpacePerThread();
3791}
3792
3793
3794int HandleScopeImplementer::ArchiveSpacePerThread() {
3795 return sizeof(thread_local);
3796}
3797
3798
3799char* HandleScopeImplementer::RestoreThread(char* storage) {
3800 return thread_local.RestoreThreadHelper(storage);
3801}
3802
3803
3804char* HandleScopeImplementer::RestoreThreadHelper(char* storage) {
3805 memcpy(this, storage, sizeof(*this));
3806 *v8::ImplementationUtilities::CurrentHandleScope() = handle_scope_data_;
3807 return storage + ArchiveSpacePerThread();
3808}
3809
3810
3811void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
3812 // Iterate over all handles in the blocks except for the last.
3813 for (int i = blocks()->length() - 2; i >= 0; --i) {
3814 Object** block = blocks()->at(i);
3815 v->VisitPointers(block, &block[kHandleBlockSize]);
3816 }
3817
3818 // Iterate over live handles in the last block (if any).
3819 if (!blocks()->is_empty()) {
3820 v->VisitPointers(blocks()->last(), handle_scope_data_.next);
3821 }
3822
3823 if (!saved_contexts_.is_empty()) {
3824 Object** start = reinterpret_cast<Object**>(&saved_contexts_.first());
3825 v->VisitPointers(start, start + saved_contexts_.length());
3826 }
3827}
3828
3829
3830void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
3831 v8::ImplementationUtilities::HandleScopeData* current =
3832 v8::ImplementationUtilities::CurrentHandleScope();
3833 thread_local.handle_scope_data_ = *current;
3834 thread_local.IterateThis(v);
3835}
3836
3837
3838char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
3839 HandleScopeImplementer* thread_local =
3840 reinterpret_cast<HandleScopeImplementer*>(storage);
3841 thread_local->IterateThis(v);
3842 return storage + ArchiveSpacePerThread();
3843}
3844
3845} } // namespace v8::internal