9d2652663aa0353a1ea1c0a742db8366743a45e6
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / execution.cc
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
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 <stdlib.h>
29
30 #include "v8.h"
31
32 #include "api.h"
33 #include "bootstrapper.h"
34 #include "codegen.h"
35 #include "debug.h"
36 #include "isolate-inl.h"
37 #include "runtime-profiler.h"
38 #include "simulator.h"
39 #include "v8threads.h"
40 #include "vm-state-inl.h"
41
42 namespace v8 {
43 namespace internal {
44
45
46 StackGuard::StackGuard()
47     : isolate_(NULL) {
48 }
49
50
51 void StackGuard::set_interrupt_limits(const ExecutionAccess& lock) {
52   ASSERT(isolate_ != NULL);
53   // Ignore attempts to interrupt when interrupts are postponed.
54   if (should_postpone_interrupts(lock)) return;
55   thread_local_.jslimit_ = kInterruptLimit;
56   thread_local_.climit_ = kInterruptLimit;
57   isolate_->heap()->SetStackLimits();
58 }
59
60
61 void StackGuard::reset_limits(const ExecutionAccess& lock) {
62   ASSERT(isolate_ != NULL);
63   thread_local_.jslimit_ = thread_local_.real_jslimit_;
64   thread_local_.climit_ = thread_local_.real_climit_;
65   isolate_->heap()->SetStackLimits();
66 }
67
68
69 static Handle<Object> Invoke(bool is_construct,
70                              Handle<JSFunction> function,
71                              Handle<Object> receiver,
72                              int argc,
73                              Handle<Object> args[],
74                              bool* has_pending_exception,
75                              Handle<Object> qml) {
76   Isolate* isolate = function->GetIsolate();
77
78   // Entering JavaScript.
79   VMState state(isolate, JS);
80
81   // Placeholder for return value.
82   MaybeObject* value = reinterpret_cast<Object*>(kZapValue);
83
84   typedef Object* (*JSEntryFunction)(byte* entry,
85                                      Object* function,
86                                      Object* receiver,
87                                      int argc,
88                                      Object*** args);
89
90   Handle<Code> code = is_construct
91       ? isolate->factory()->js_construct_entry_code()
92       : isolate->factory()->js_entry_code();
93
94   // Convert calls on global objects to be calls on the global
95   // receiver instead to avoid having a 'this' pointer which refers
96   // directly to a global object.
97   if (receiver->IsGlobalObject()) {
98     Handle<GlobalObject> global = Handle<GlobalObject>::cast(receiver);
99     receiver = Handle<JSObject>(global->global_receiver());
100   }
101
102   // Make sure that the global object of the context we're about to
103   // make the current one is indeed a global object.
104   ASSERT(function->context()->global()->IsGlobalObject());
105
106   Handle<JSObject> oldqml;
107   if (!qml.is_null()) {
108     oldqml = Handle<JSObject>(function->context()->qml_global());
109     function->context()->set_qml_global(JSObject::cast(*qml));
110   }
111
112   {
113     // Save and restore context around invocation and block the
114     // allocation of handles without explicit handle scopes.
115     SaveContext save(isolate);
116     NoHandleAllocation na;
117     JSEntryFunction stub_entry = FUNCTION_CAST<JSEntryFunction>(code->entry());
118
119     // Call the function through the right JS entry stub.
120     byte* function_entry = function->code()->entry();
121     JSFunction* func = *function;
122     Object* recv = *receiver;
123     Object*** argv = reinterpret_cast<Object***>(args);
124     value =
125         CALL_GENERATED_CODE(stub_entry, function_entry, func, recv, argc, argv);
126   }
127
128   if (!qml.is_null())
129     function->context()->set_qml_global(*oldqml);
130
131 #ifdef DEBUG
132   value->Verify();
133 #endif
134
135   // Update the pending exception flag and return the value.
136   *has_pending_exception = value->IsException();
137   ASSERT(*has_pending_exception == Isolate::Current()->has_pending_exception());
138   if (*has_pending_exception) {
139     isolate->ReportPendingMessages();
140     if (isolate->pending_exception() == Failure::OutOfMemoryException()) {
141       if (!isolate->ignore_out_of_memory()) {
142         V8::FatalProcessOutOfMemory("JS", true);
143       }
144     }
145     return Handle<Object>();
146   } else {
147     isolate->clear_pending_message();
148   }
149
150   return Handle<Object>(value->ToObjectUnchecked(), isolate);
151 }
152
153
154 Handle<Object> Execution::Call(Handle<Object> callable,
155                                Handle<Object> receiver,
156                                int argc,
157                                Handle<Object> argv[],
158                                bool* pending_exception,
159                                bool convert_receiver)
160 {
161     return Call(callable, receiver, argc, argv, pending_exception, convert_receiver, Handle<Object>());
162 }
163
164 Handle<Object> Execution::Call(Handle<Object> callable,
165                                Handle<Object> receiver,
166                                int argc,
167                                Handle<Object> argv[],
168                                bool* pending_exception,
169                                bool convert_receiver,
170                                Handle<Object> qml) {
171   *pending_exception = false;
172
173   if (!callable->IsJSFunction()) {
174     callable = TryGetFunctionDelegate(callable, pending_exception);
175     if (*pending_exception) return callable;
176   }
177   Handle<JSFunction> func = Handle<JSFunction>::cast(callable);
178
179   // In non-strict mode, convert receiver.
180   if (convert_receiver && !receiver->IsJSReceiver() &&
181       !func->shared()->native() && !func->shared()->strict_mode()) {
182     if (receiver->IsUndefined() || receiver->IsNull()) {
183       Object* global = func->context()->global()->global_receiver();
184       // Under some circumstances, 'global' can be the JSBuiltinsObject
185       // In that case, don't rewrite.
186       // (FWIW, the same holds for GetIsolate()->global()->global_receiver().)
187       if (!global->IsJSBuiltinsObject()) receiver = Handle<Object>(global);
188     } else {
189       receiver = ToObject(receiver, pending_exception);
190     }
191     if (*pending_exception) return callable;
192   }
193
194   return Invoke(false, func, receiver, argc, argv, pending_exception, qml);
195 }
196
197
198 Handle<Object> Execution::New(Handle<JSFunction> func,
199                               int argc,
200                               Handle<Object> argv[],
201                               bool* pending_exception) {
202   return Invoke(true, func, Isolate::Current()->global(), argc, argv,
203                 pending_exception, Handle<Object>());
204 }
205
206
207 Handle<Object> Execution::TryCall(Handle<JSFunction> func,
208                                   Handle<Object> receiver,
209                                   int argc,
210                                   Handle<Object> args[],
211                                   bool* caught_exception) {
212   // Enter a try-block while executing the JavaScript code. To avoid
213   // duplicate error printing it must be non-verbose.  Also, to avoid
214   // creating message objects during stack overflow we shouldn't
215   // capture messages.
216   v8::TryCatch catcher;
217   catcher.SetVerbose(false);
218   catcher.SetCaptureMessage(false);
219   *caught_exception = false;
220
221   Handle<Object> result = Invoke(false, func, receiver, argc, args,
222                                  caught_exception, Handle<Object>());
223
224   if (*caught_exception) {
225     ASSERT(catcher.HasCaught());
226     Isolate* isolate = Isolate::Current();
227     ASSERT(isolate->has_pending_exception());
228     ASSERT(isolate->external_caught_exception());
229     if (isolate->pending_exception() ==
230         isolate->heap()->termination_exception()) {
231       result = isolate->factory()->termination_exception();
232     } else {
233       result = v8::Utils::OpenHandle(*catcher.Exception());
234     }
235     isolate->OptionalRescheduleException(true);
236   }
237
238   ASSERT(!Isolate::Current()->has_pending_exception());
239   ASSERT(!Isolate::Current()->external_caught_exception());
240   return result;
241 }
242
243
244 Handle<Object> Execution::GetFunctionDelegate(Handle<Object> object) {
245   ASSERT(!object->IsJSFunction());
246   Isolate* isolate = Isolate::Current();
247   Factory* factory = isolate->factory();
248
249   // If you return a function from here, it will be called when an
250   // attempt is made to call the given object as a function.
251
252   // If object is a function proxy, get its handler. Iterate if necessary.
253   Object* fun = *object;
254   while (fun->IsJSFunctionProxy()) {
255     fun = JSFunctionProxy::cast(fun)->call_trap();
256   }
257   if (fun->IsJSFunction()) return Handle<Object>(fun);
258
259   // Objects created through the API can have an instance-call handler
260   // that should be used when calling the object as a function.
261   if (fun->IsHeapObject() &&
262       HeapObject::cast(fun)->map()->has_instance_call_handler()) {
263     return Handle<JSFunction>(
264         isolate->global_context()->call_as_function_delegate());
265   }
266
267   return factory->undefined_value();
268 }
269
270
271 Handle<Object> Execution::TryGetFunctionDelegate(Handle<Object> object,
272                                                  bool* has_pending_exception) {
273   ASSERT(!object->IsJSFunction());
274   Isolate* isolate = Isolate::Current();
275
276   // If object is a function proxy, get its handler. Iterate if necessary.
277   Object* fun = *object;
278   while (fun->IsJSFunctionProxy()) {
279     fun = JSFunctionProxy::cast(fun)->call_trap();
280   }
281   if (fun->IsJSFunction()) return Handle<Object>(fun);
282
283   // Objects created through the API can have an instance-call handler
284   // that should be used when calling the object as a function.
285   if (fun->IsHeapObject() &&
286       HeapObject::cast(fun)->map()->has_instance_call_handler()) {
287     return Handle<JSFunction>(
288         isolate->global_context()->call_as_function_delegate());
289   }
290
291   // If the Object doesn't have an instance-call handler we should
292   // throw a non-callable exception.
293   i::Handle<i::Object> error_obj = isolate->factory()->NewTypeError(
294       "called_non_callable", i::HandleVector<i::Object>(&object, 1));
295   isolate->Throw(*error_obj);
296   *has_pending_exception = true;
297
298   return isolate->factory()->undefined_value();
299 }
300
301
302 Handle<Object> Execution::GetConstructorDelegate(Handle<Object> object) {
303   ASSERT(!object->IsJSFunction());
304   Isolate* isolate = Isolate::Current();
305
306   // If you return a function from here, it will be called when an
307   // attempt is made to call the given object as a constructor.
308
309   // If object is a function proxies, get its handler. Iterate if necessary.
310   Object* fun = *object;
311   while (fun->IsJSFunctionProxy()) {
312     fun = JSFunctionProxy::cast(fun)->call_trap();
313   }
314   if (fun->IsJSFunction()) return Handle<Object>(fun);
315
316   // Objects created through the API can have an instance-call handler
317   // that should be used when calling the object as a function.
318   if (fun->IsHeapObject() &&
319       HeapObject::cast(fun)->map()->has_instance_call_handler()) {
320     return Handle<JSFunction>(
321         isolate->global_context()->call_as_constructor_delegate());
322   }
323
324   return isolate->factory()->undefined_value();
325 }
326
327
328 Handle<Object> Execution::TryGetConstructorDelegate(
329     Handle<Object> object,
330     bool* has_pending_exception) {
331   ASSERT(!object->IsJSFunction());
332   Isolate* isolate = Isolate::Current();
333
334   // If you return a function from here, it will be called when an
335   // attempt is made to call the given object as a constructor.
336
337   // If object is a function proxies, get its handler. Iterate if necessary.
338   Object* fun = *object;
339   while (fun->IsJSFunctionProxy()) {
340     fun = JSFunctionProxy::cast(fun)->call_trap();
341   }
342   if (fun->IsJSFunction()) return Handle<Object>(fun);
343
344   // Objects created through the API can have an instance-call handler
345   // that should be used when calling the object as a function.
346   if (fun->IsHeapObject() &&
347       HeapObject::cast(fun)->map()->has_instance_call_handler()) {
348     return Handle<JSFunction>(
349         isolate->global_context()->call_as_constructor_delegate());
350   }
351
352   // If the Object doesn't have an instance-call handler we should
353   // throw a non-callable exception.
354   i::Handle<i::Object> error_obj = isolate->factory()->NewTypeError(
355       "called_non_callable", i::HandleVector<i::Object>(&object, 1));
356   isolate->Throw(*error_obj);
357   *has_pending_exception = true;
358
359   return isolate->factory()->undefined_value();
360 }
361
362
363 bool StackGuard::IsStackOverflow() {
364   ExecutionAccess access(isolate_);
365   return (thread_local_.jslimit_ != kInterruptLimit &&
366           thread_local_.climit_ != kInterruptLimit);
367 }
368
369
370 void StackGuard::EnableInterrupts() {
371   ExecutionAccess access(isolate_);
372   if (has_pending_interrupts(access)) {
373     set_interrupt_limits(access);
374   }
375 }
376
377
378 void StackGuard::SetStackLimit(uintptr_t limit) {
379   ExecutionAccess access(isolate_);
380   // If the current limits are special (eg due to a pending interrupt) then
381   // leave them alone.
382   uintptr_t jslimit = SimulatorStack::JsLimitFromCLimit(isolate_, limit);
383   if (thread_local_.jslimit_ == thread_local_.real_jslimit_) {
384     thread_local_.jslimit_ = jslimit;
385   }
386   if (thread_local_.climit_ == thread_local_.real_climit_) {
387     thread_local_.climit_ = limit;
388   }
389   thread_local_.real_climit_ = limit;
390   thread_local_.real_jslimit_ = jslimit;
391 }
392
393
394 void StackGuard::DisableInterrupts() {
395   ExecutionAccess access(isolate_);
396   reset_limits(access);
397 }
398
399
400 bool StackGuard::IsInterrupted() {
401   ExecutionAccess access(isolate_);
402   return (thread_local_.interrupt_flags_ & INTERRUPT) != 0;
403 }
404
405
406 void StackGuard::Interrupt() {
407   ExecutionAccess access(isolate_);
408   thread_local_.interrupt_flags_ |= INTERRUPT;
409   set_interrupt_limits(access);
410 }
411
412
413 bool StackGuard::IsPreempted() {
414   ExecutionAccess access(isolate_);
415   return thread_local_.interrupt_flags_ & PREEMPT;
416 }
417
418
419 void StackGuard::Preempt() {
420   ExecutionAccess access(isolate_);
421   thread_local_.interrupt_flags_ |= PREEMPT;
422   set_interrupt_limits(access);
423 }
424
425
426 bool StackGuard::IsTerminateExecution() {
427   ExecutionAccess access(isolate_);
428   return (thread_local_.interrupt_flags_ & TERMINATE) != 0;
429 }
430
431
432 void StackGuard::TerminateExecution() {
433   ExecutionAccess access(isolate_);
434   thread_local_.interrupt_flags_ |= TERMINATE;
435   set_interrupt_limits(access);
436 }
437
438
439 bool StackGuard::IsRuntimeProfilerTick() {
440   ExecutionAccess access(isolate_);
441   return (thread_local_.interrupt_flags_ & RUNTIME_PROFILER_TICK) != 0;
442 }
443
444
445 void StackGuard::RequestRuntimeProfilerTick() {
446   // Ignore calls if we're not optimizing or if we can't get the lock.
447   if (FLAG_opt && ExecutionAccess::TryLock(isolate_)) {
448     thread_local_.interrupt_flags_ |= RUNTIME_PROFILER_TICK;
449     if (thread_local_.postpone_interrupts_nesting_ == 0) {
450       thread_local_.jslimit_ = thread_local_.climit_ = kInterruptLimit;
451       isolate_->heap()->SetStackLimits();
452     }
453     ExecutionAccess::Unlock(isolate_);
454   }
455 }
456
457
458 bool StackGuard::IsGCRequest() {
459   ExecutionAccess access(isolate_);
460   return (thread_local_.interrupt_flags_ & GC_REQUEST) != 0;
461 }
462
463
464 void StackGuard::RequestGC() {
465   ExecutionAccess access(isolate_);
466   thread_local_.interrupt_flags_ |= GC_REQUEST;
467   if (thread_local_.postpone_interrupts_nesting_ == 0) {
468     thread_local_.jslimit_ = thread_local_.climit_ = kInterruptLimit;
469     isolate_->heap()->SetStackLimits();
470   }
471 }
472
473
474 #ifdef ENABLE_DEBUGGER_SUPPORT
475 bool StackGuard::IsDebugBreak() {
476   ExecutionAccess access(isolate_);
477   return thread_local_.interrupt_flags_ & DEBUGBREAK;
478 }
479
480
481 void StackGuard::DebugBreak() {
482   ExecutionAccess access(isolate_);
483   thread_local_.interrupt_flags_ |= DEBUGBREAK;
484   set_interrupt_limits(access);
485 }
486
487
488 bool StackGuard::IsDebugCommand() {
489   ExecutionAccess access(isolate_);
490   return thread_local_.interrupt_flags_ & DEBUGCOMMAND;
491 }
492
493
494 void StackGuard::DebugCommand() {
495   if (FLAG_debugger_auto_break) {
496     ExecutionAccess access(isolate_);
497     thread_local_.interrupt_flags_ |= DEBUGCOMMAND;
498     set_interrupt_limits(access);
499   }
500 }
501 #endif
502
503 void StackGuard::Continue(InterruptFlag after_what) {
504   ExecutionAccess access(isolate_);
505   thread_local_.interrupt_flags_ &= ~static_cast<int>(after_what);
506   if (!should_postpone_interrupts(access) && !has_pending_interrupts(access)) {
507     reset_limits(access);
508   }
509 }
510
511
512 char* StackGuard::ArchiveStackGuard(char* to) {
513   ExecutionAccess access(isolate_);
514   memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
515   ThreadLocal blank;
516
517   // Set the stack limits using the old thread_local_.
518   // TODO(isolates): This was the old semantics of constructing a ThreadLocal
519   //                 (as the ctor called SetStackLimits, which looked at the
520   //                 current thread_local_ from StackGuard)-- but is this
521   //                 really what was intended?
522   isolate_->heap()->SetStackLimits();
523   thread_local_ = blank;
524
525   return to + sizeof(ThreadLocal);
526 }
527
528
529 char* StackGuard::RestoreStackGuard(char* from) {
530   ExecutionAccess access(isolate_);
531   memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
532   isolate_->heap()->SetStackLimits();
533   return from + sizeof(ThreadLocal);
534 }
535
536
537 void StackGuard::FreeThreadResources() {
538   Isolate::PerIsolateThreadData* per_thread =
539       isolate_->FindOrAllocatePerThreadDataForThisThread();
540   per_thread->set_stack_limit(thread_local_.real_climit_);
541 }
542
543
544 void StackGuard::ThreadLocal::Clear() {
545   real_jslimit_ = kIllegalLimit;
546   jslimit_ = kIllegalLimit;
547   real_climit_ = kIllegalLimit;
548   climit_ = kIllegalLimit;
549   nesting_ = 0;
550   postpone_interrupts_nesting_ = 0;
551   interrupt_flags_ = 0;
552 }
553
554
555 bool StackGuard::ThreadLocal::Initialize(Isolate* isolate) {
556   bool should_set_stack_limits = false;
557   if (real_climit_ == kIllegalLimit) {
558     // Takes the address of the limit variable in order to find out where
559     // the top of stack is right now.
560     const uintptr_t kLimitSize = FLAG_stack_size * KB;
561     uintptr_t limit = reinterpret_cast<uintptr_t>(&limit) - kLimitSize;
562     ASSERT(reinterpret_cast<uintptr_t>(&limit) > kLimitSize);
563     real_jslimit_ = SimulatorStack::JsLimitFromCLimit(isolate, limit);
564     jslimit_ = SimulatorStack::JsLimitFromCLimit(isolate, limit);
565     real_climit_ = limit;
566     climit_ = limit;
567     should_set_stack_limits = true;
568   }
569   nesting_ = 0;
570   postpone_interrupts_nesting_ = 0;
571   interrupt_flags_ = 0;
572   return should_set_stack_limits;
573 }
574
575
576 void StackGuard::ClearThread(const ExecutionAccess& lock) {
577   thread_local_.Clear();
578   isolate_->heap()->SetStackLimits();
579 }
580
581
582 void StackGuard::InitThread(const ExecutionAccess& lock) {
583   if (thread_local_.Initialize(isolate_)) isolate_->heap()->SetStackLimits();
584   Isolate::PerIsolateThreadData* per_thread =
585       isolate_->FindOrAllocatePerThreadDataForThisThread();
586   uintptr_t stored_limit = per_thread->stack_limit();
587   // You should hold the ExecutionAccess lock when you call this.
588   if (stored_limit != 0) {
589     SetStackLimit(stored_limit);
590   }
591 }
592
593
594 // --- C a l l s   t o   n a t i v e s ---
595
596 #define RETURN_NATIVE_CALL(name, args, has_pending_exception)           \
597   do {                                                                  \
598     Isolate* isolate = Isolate::Current();                              \
599     Handle<Object> argv[] = args;                                       \
600     ASSERT(has_pending_exception != NULL);                              \
601     return Call(isolate->name##_fun(),                                  \
602                 isolate->js_builtins_object(),                          \
603                 ARRAY_SIZE(argv), argv,                                 \
604                 has_pending_exception);                                 \
605   } while (false)
606
607
608 Handle<Object> Execution::ToBoolean(Handle<Object> obj) {
609   // See the similar code in runtime.js:ToBoolean.
610   if (obj->IsBoolean()) return obj;
611   bool result = true;
612   if (obj->IsString()) {
613     result = Handle<String>::cast(obj)->length() != 0;
614   } else if (obj->IsNull() || obj->IsUndefined()) {
615     result = false;
616   } else if (obj->IsNumber()) {
617     double value = obj->Number();
618     result = !((value == 0) || isnan(value));
619   }
620   return Handle<Object>(HEAP->ToBoolean(result));
621 }
622
623
624 Handle<Object> Execution::ToNumber(Handle<Object> obj, bool* exc) {
625   RETURN_NATIVE_CALL(to_number, { obj }, exc);
626 }
627
628
629 Handle<Object> Execution::ToString(Handle<Object> obj, bool* exc) {
630   RETURN_NATIVE_CALL(to_string, { obj }, exc);
631 }
632
633
634 Handle<Object> Execution::ToDetailString(Handle<Object> obj, bool* exc) {
635   RETURN_NATIVE_CALL(to_detail_string, { obj }, exc);
636 }
637
638
639 Handle<Object> Execution::ToObject(Handle<Object> obj, bool* exc) {
640   if (obj->IsSpecObject()) return obj;
641   RETURN_NATIVE_CALL(to_object, { obj }, exc);
642 }
643
644
645 Handle<Object> Execution::ToInteger(Handle<Object> obj, bool* exc) {
646   RETURN_NATIVE_CALL(to_integer, { obj }, exc);
647 }
648
649
650 Handle<Object> Execution::ToUint32(Handle<Object> obj, bool* exc) {
651   RETURN_NATIVE_CALL(to_uint32, { obj }, exc);
652 }
653
654
655 Handle<Object> Execution::ToInt32(Handle<Object> obj, bool* exc) {
656   RETURN_NATIVE_CALL(to_int32, { obj }, exc);
657 }
658
659
660 Handle<Object> Execution::NewDate(double time, bool* exc) {
661   Handle<Object> time_obj = FACTORY->NewNumber(time);
662   RETURN_NATIVE_CALL(create_date, { time_obj }, exc);
663 }
664
665
666 #undef RETURN_NATIVE_CALL
667
668
669 Handle<JSRegExp> Execution::NewJSRegExp(Handle<String> pattern,
670                                         Handle<String> flags,
671                                         bool* exc) {
672   Handle<JSFunction> function = Handle<JSFunction>(
673       pattern->GetIsolate()->global_context()->regexp_function());
674   Handle<Object> re_obj = RegExpImpl::CreateRegExpLiteral(
675       function, pattern, flags, exc);
676   if (*exc) return Handle<JSRegExp>();
677   return Handle<JSRegExp>::cast(re_obj);
678 }
679
680
681 Handle<Object> Execution::CharAt(Handle<String> string, uint32_t index) {
682   Isolate* isolate = string->GetIsolate();
683   Factory* factory = isolate->factory();
684
685   int int_index = static_cast<int>(index);
686   if (int_index < 0 || int_index >= string->length()) {
687     return factory->undefined_value();
688   }
689
690   Handle<Object> char_at =
691       GetProperty(isolate->js_builtins_object(),
692                   factory->char_at_symbol());
693   if (!char_at->IsJSFunction()) {
694     return factory->undefined_value();
695   }
696
697   bool caught_exception;
698   Handle<Object> index_object = factory->NewNumberFromInt(int_index);
699   Handle<Object> index_arg[] = { index_object };
700   Handle<Object> result = TryCall(Handle<JSFunction>::cast(char_at),
701                                   string,
702                                   ARRAY_SIZE(index_arg),
703                                   index_arg,
704                                   &caught_exception);
705   if (caught_exception) {
706     return factory->undefined_value();
707   }
708   return result;
709 }
710
711
712 Handle<JSFunction> Execution::InstantiateFunction(
713     Handle<FunctionTemplateInfo> data,
714     bool* exc) {
715   Isolate* isolate = data->GetIsolate();
716   // Fast case: see if the function has already been instantiated
717   int serial_number = Smi::cast(data->serial_number())->value();
718   Object* elm =
719       isolate->global_context()->function_cache()->
720           GetElementNoExceptionThrown(serial_number);
721   if (elm->IsJSFunction()) return Handle<JSFunction>(JSFunction::cast(elm));
722   // The function has not yet been instantiated in this context; do it.
723   Handle<Object> args[] = { data };
724   Handle<Object> result = Call(isolate->instantiate_fun(),
725                                isolate->js_builtins_object(),
726                                ARRAY_SIZE(args),
727                                args,
728                                exc);
729   if (*exc) return Handle<JSFunction>::null();
730   return Handle<JSFunction>::cast(result);
731 }
732
733
734 Handle<JSObject> Execution::InstantiateObject(Handle<ObjectTemplateInfo> data,
735                                               bool* exc) {
736   Isolate* isolate = data->GetIsolate();
737   if (data->property_list()->IsUndefined() &&
738       !data->constructor()->IsUndefined()) {
739     // Initialization to make gcc happy.
740     Object* result = NULL;
741     {
742       HandleScope scope(isolate);
743       Handle<FunctionTemplateInfo> cons_template =
744           Handle<FunctionTemplateInfo>(
745               FunctionTemplateInfo::cast(data->constructor()));
746       Handle<JSFunction> cons = InstantiateFunction(cons_template, exc);
747       if (*exc) return Handle<JSObject>::null();
748       Handle<Object> value = New(cons, 0, NULL, exc);
749       if (*exc) return Handle<JSObject>::null();
750       result = *value;
751     }
752     ASSERT(!*exc);
753     return Handle<JSObject>(JSObject::cast(result));
754   } else {
755     Handle<Object> args[] = { data };
756     Handle<Object> result = Call(isolate->instantiate_fun(),
757                                  isolate->js_builtins_object(),
758                                  ARRAY_SIZE(args),
759                                  args,
760                                  exc);
761     if (*exc) return Handle<JSObject>::null();
762     return Handle<JSObject>::cast(result);
763   }
764 }
765
766
767 void Execution::ConfigureInstance(Handle<Object> instance,
768                                   Handle<Object> instance_template,
769                                   bool* exc) {
770   Isolate* isolate = Isolate::Current();
771   Handle<Object> args[] = { instance, instance_template };
772   Execution::Call(isolate->configure_instance_fun(),
773                   isolate->js_builtins_object(),
774                   ARRAY_SIZE(args),
775                   args,
776                   exc);
777 }
778
779
780 Handle<String> Execution::GetStackTraceLine(Handle<Object> recv,
781                                             Handle<JSFunction> fun,
782                                             Handle<Object> pos,
783                                             Handle<Object> is_global) {
784   Isolate* isolate = fun->GetIsolate();
785   Handle<Object> args[] = { recv, fun, pos, is_global };
786   bool caught_exception;
787   Handle<Object> result = TryCall(isolate->get_stack_trace_line_fun(),
788                                   isolate->js_builtins_object(),
789                                   ARRAY_SIZE(args),
790                                   args,
791                                   &caught_exception);
792   if (caught_exception || !result->IsString()) {
793       return isolate->factory()->empty_symbol();
794   }
795
796   return Handle<String>::cast(result);
797 }
798
799
800 static Object* RuntimePreempt() {
801   Isolate* isolate = Isolate::Current();
802
803   // Clear the preempt request flag.
804   isolate->stack_guard()->Continue(PREEMPT);
805
806   ContextSwitcher::PreemptionReceived();
807
808 #ifdef ENABLE_DEBUGGER_SUPPORT
809   if (isolate->debug()->InDebugger()) {
810     // If currently in the debugger don't do any actual preemption but record
811     // that preemption occoured while in the debugger.
812     isolate->debug()->PreemptionWhileInDebugger();
813   } else {
814     // Perform preemption.
815     v8::Unlocker unlocker(reinterpret_cast<v8::Isolate*>(isolate));
816     Thread::YieldCPU();
817   }
818 #else
819   { // NOLINT
820     // Perform preemption.
821     v8::Unlocker unlocker(reinterpret_cast<v8::Isolate*>(isolate));
822     Thread::YieldCPU();
823   }
824 #endif
825
826   return isolate->heap()->undefined_value();
827 }
828
829
830 #ifdef ENABLE_DEBUGGER_SUPPORT
831 Object* Execution::DebugBreakHelper() {
832   Isolate* isolate = Isolate::Current();
833
834   // Just continue if breaks are disabled.
835   if (isolate->debug()->disable_break()) {
836     return isolate->heap()->undefined_value();
837   }
838
839   // Ignore debug break during bootstrapping.
840   if (isolate->bootstrapper()->IsActive()) {
841     return isolate->heap()->undefined_value();
842   }
843
844   {
845     JavaScriptFrameIterator it(isolate);
846     ASSERT(!it.done());
847     Object* fun = it.frame()->function();
848     if (fun && fun->IsJSFunction()) {
849       // Don't stop in builtin functions.
850       if (JSFunction::cast(fun)->IsBuiltin()) {
851         return isolate->heap()->undefined_value();
852       }
853       GlobalObject* global = JSFunction::cast(fun)->context()->global();
854       // Don't stop in debugger functions.
855       if (isolate->debug()->IsDebugGlobal(global)) {
856         return isolate->heap()->undefined_value();
857       }
858     }
859   }
860
861   // Collect the break state before clearing the flags.
862   bool debug_command_only =
863       isolate->stack_guard()->IsDebugCommand() &&
864       !isolate->stack_guard()->IsDebugBreak();
865
866   // Clear the debug break request flag.
867   isolate->stack_guard()->Continue(DEBUGBREAK);
868
869   ProcessDebugMesssages(debug_command_only);
870
871   // Return to continue execution.
872   return isolate->heap()->undefined_value();
873 }
874
875 void Execution::ProcessDebugMesssages(bool debug_command_only) {
876   Isolate* isolate = Isolate::Current();
877   // Clear the debug command request flag.
878   isolate->stack_guard()->Continue(DEBUGCOMMAND);
879
880   HandleScope scope(isolate);
881   // Enter the debugger. Just continue if we fail to enter the debugger.
882   EnterDebugger debugger;
883   if (debugger.FailedToEnter()) {
884     return;
885   }
886
887   // Notify the debug event listeners. Indicate auto continue if the break was
888   // a debug command break.
889   isolate->debugger()->OnDebugBreak(isolate->factory()->undefined_value(),
890                                     debug_command_only);
891 }
892
893
894 #endif
895
896 MaybeObject* Execution::HandleStackGuardInterrupt() {
897   Isolate* isolate = Isolate::Current();
898   StackGuard* stack_guard = isolate->stack_guard();
899
900   if (stack_guard->IsGCRequest()) {
901     isolate->heap()->CollectAllGarbage(false);
902     stack_guard->Continue(GC_REQUEST);
903   }
904
905   isolate->counters()->stack_interrupts()->Increment();
906   if (stack_guard->IsRuntimeProfilerTick()) {
907     isolate->counters()->runtime_profiler_ticks()->Increment();
908     stack_guard->Continue(RUNTIME_PROFILER_TICK);
909     isolate->runtime_profiler()->OptimizeNow();
910   }
911 #ifdef ENABLE_DEBUGGER_SUPPORT
912   if (stack_guard->IsDebugBreak() || stack_guard->IsDebugCommand()) {
913     DebugBreakHelper();
914   }
915 #endif
916   if (stack_guard->IsPreempted()) RuntimePreempt();
917   if (stack_guard->IsTerminateExecution()) {
918     stack_guard->Continue(TERMINATE);
919     return isolate->TerminateExecution();
920   }
921   if (stack_guard->IsInterrupted()) {
922     stack_guard->Continue(INTERRUPT);
923     return isolate->StackOverflow();
924   }
925   return isolate->heap()->undefined_value();
926 }
927
928 } }  // namespace v8::internal