[V8] Introduce a QML compilation mode
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / execution.cc
1 // Copyright 2012 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()->is_classic_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 (e.g. 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::ShouldPostponeInterrupts() {
401   ExecutionAccess access(isolate_);
402   return should_postpone_interrupts(access);
403 }
404
405
406 bool StackGuard::IsInterrupted() {
407   ExecutionAccess access(isolate_);
408   return (thread_local_.interrupt_flags_ & INTERRUPT) != 0;
409 }
410
411
412 void StackGuard::Interrupt() {
413   ExecutionAccess access(isolate_);
414   thread_local_.interrupt_flags_ |= INTERRUPT;
415   set_interrupt_limits(access);
416 }
417
418
419 bool StackGuard::IsPreempted() {
420   ExecutionAccess access(isolate_);
421   return thread_local_.interrupt_flags_ & PREEMPT;
422 }
423
424
425 void StackGuard::Preempt() {
426   ExecutionAccess access(isolate_);
427   thread_local_.interrupt_flags_ |= PREEMPT;
428   set_interrupt_limits(access);
429 }
430
431
432 bool StackGuard::IsTerminateExecution() {
433   ExecutionAccess access(isolate_);
434   return (thread_local_.interrupt_flags_ & TERMINATE) != 0;
435 }
436
437
438 void StackGuard::TerminateExecution() {
439   ExecutionAccess access(isolate_);
440   thread_local_.interrupt_flags_ |= TERMINATE;
441   set_interrupt_limits(access);
442 }
443
444
445 bool StackGuard::IsRuntimeProfilerTick() {
446   ExecutionAccess access(isolate_);
447   return (thread_local_.interrupt_flags_ & RUNTIME_PROFILER_TICK) != 0;
448 }
449
450
451 void StackGuard::RequestRuntimeProfilerTick() {
452   // Ignore calls if we're not optimizing or if we can't get the lock.
453   if (FLAG_opt && ExecutionAccess::TryLock(isolate_)) {
454     thread_local_.interrupt_flags_ |= RUNTIME_PROFILER_TICK;
455     if (thread_local_.postpone_interrupts_nesting_ == 0) {
456       thread_local_.jslimit_ = thread_local_.climit_ = kInterruptLimit;
457       isolate_->heap()->SetStackLimits();
458     }
459     ExecutionAccess::Unlock(isolate_);
460   }
461 }
462
463
464 bool StackGuard::IsGCRequest() {
465   ExecutionAccess access(isolate_);
466   return (thread_local_.interrupt_flags_ & GC_REQUEST) != 0;
467 }
468
469
470 void StackGuard::RequestGC() {
471   ExecutionAccess access(isolate_);
472   thread_local_.interrupt_flags_ |= GC_REQUEST;
473   if (thread_local_.postpone_interrupts_nesting_ == 0) {
474     thread_local_.jslimit_ = thread_local_.climit_ = kInterruptLimit;
475     isolate_->heap()->SetStackLimits();
476   }
477 }
478
479
480 #ifdef ENABLE_DEBUGGER_SUPPORT
481 bool StackGuard::IsDebugBreak() {
482   ExecutionAccess access(isolate_);
483   return thread_local_.interrupt_flags_ & DEBUGBREAK;
484 }
485
486
487 void StackGuard::DebugBreak() {
488   ExecutionAccess access(isolate_);
489   thread_local_.interrupt_flags_ |= DEBUGBREAK;
490   set_interrupt_limits(access);
491 }
492
493
494 bool StackGuard::IsDebugCommand() {
495   ExecutionAccess access(isolate_);
496   return thread_local_.interrupt_flags_ & DEBUGCOMMAND;
497 }
498
499
500 void StackGuard::DebugCommand() {
501   if (FLAG_debugger_auto_break) {
502     ExecutionAccess access(isolate_);
503     thread_local_.interrupt_flags_ |= DEBUGCOMMAND;
504     set_interrupt_limits(access);
505   }
506 }
507 #endif
508
509 void StackGuard::Continue(InterruptFlag after_what) {
510   ExecutionAccess access(isolate_);
511   thread_local_.interrupt_flags_ &= ~static_cast<int>(after_what);
512   if (!should_postpone_interrupts(access) && !has_pending_interrupts(access)) {
513     reset_limits(access);
514   }
515 }
516
517
518 char* StackGuard::ArchiveStackGuard(char* to) {
519   ExecutionAccess access(isolate_);
520   memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
521   ThreadLocal blank;
522
523   // Set the stack limits using the old thread_local_.
524   // TODO(isolates): This was the old semantics of constructing a ThreadLocal
525   //                 (as the ctor called SetStackLimits, which looked at the
526   //                 current thread_local_ from StackGuard)-- but is this
527   //                 really what was intended?
528   isolate_->heap()->SetStackLimits();
529   thread_local_ = blank;
530
531   return to + sizeof(ThreadLocal);
532 }
533
534
535 char* StackGuard::RestoreStackGuard(char* from) {
536   ExecutionAccess access(isolate_);
537   memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
538   isolate_->heap()->SetStackLimits();
539   return from + sizeof(ThreadLocal);
540 }
541
542
543 void StackGuard::FreeThreadResources() {
544   Isolate::PerIsolateThreadData* per_thread =
545       isolate_->FindOrAllocatePerThreadDataForThisThread();
546   per_thread->set_stack_limit(thread_local_.real_climit_);
547 }
548
549
550 void StackGuard::ThreadLocal::Clear() {
551   real_jslimit_ = kIllegalLimit;
552   jslimit_ = kIllegalLimit;
553   real_climit_ = kIllegalLimit;
554   climit_ = kIllegalLimit;
555   nesting_ = 0;
556   postpone_interrupts_nesting_ = 0;
557   interrupt_flags_ = 0;
558 }
559
560
561 bool StackGuard::ThreadLocal::Initialize(Isolate* isolate) {
562   bool should_set_stack_limits = false;
563   if (real_climit_ == kIllegalLimit) {
564     // Takes the address of the limit variable in order to find out where
565     // the top of stack is right now.
566     const uintptr_t kLimitSize = FLAG_stack_size * KB;
567     uintptr_t limit = reinterpret_cast<uintptr_t>(&limit) - kLimitSize;
568     ASSERT(reinterpret_cast<uintptr_t>(&limit) > kLimitSize);
569     real_jslimit_ = SimulatorStack::JsLimitFromCLimit(isolate, limit);
570     jslimit_ = SimulatorStack::JsLimitFromCLimit(isolate, limit);
571     real_climit_ = limit;
572     climit_ = limit;
573     should_set_stack_limits = true;
574   }
575   nesting_ = 0;
576   postpone_interrupts_nesting_ = 0;
577   interrupt_flags_ = 0;
578   return should_set_stack_limits;
579 }
580
581
582 void StackGuard::ClearThread(const ExecutionAccess& lock) {
583   thread_local_.Clear();
584   isolate_->heap()->SetStackLimits();
585 }
586
587
588 void StackGuard::InitThread(const ExecutionAccess& lock) {
589   if (thread_local_.Initialize(isolate_)) isolate_->heap()->SetStackLimits();
590   Isolate::PerIsolateThreadData* per_thread =
591       isolate_->FindOrAllocatePerThreadDataForThisThread();
592   uintptr_t stored_limit = per_thread->stack_limit();
593   // You should hold the ExecutionAccess lock when you call this.
594   if (stored_limit != 0) {
595     SetStackLimit(stored_limit);
596   }
597 }
598
599
600 // --- C a l l s   t o   n a t i v e s ---
601
602 #define RETURN_NATIVE_CALL(name, args, has_pending_exception)           \
603   do {                                                                  \
604     Isolate* isolate = Isolate::Current();                              \
605     Handle<Object> argv[] = args;                                       \
606     ASSERT(has_pending_exception != NULL);                              \
607     return Call(isolate->name##_fun(),                                  \
608                 isolate->js_builtins_object(),                          \
609                 ARRAY_SIZE(argv), argv,                                 \
610                 has_pending_exception);                                 \
611   } while (false)
612
613
614 Handle<Object> Execution::ToBoolean(Handle<Object> obj) {
615   // See the similar code in runtime.js:ToBoolean.
616   if (obj->IsBoolean()) return obj;
617   bool result = true;
618   if (obj->IsString()) {
619     result = Handle<String>::cast(obj)->length() != 0;
620   } else if (obj->IsNull() || obj->IsUndefined()) {
621     result = false;
622   } else if (obj->IsNumber()) {
623     double value = obj->Number();
624     result = !((value == 0) || isnan(value));
625   }
626   return Handle<Object>(HEAP->ToBoolean(result));
627 }
628
629
630 Handle<Object> Execution::ToNumber(Handle<Object> obj, bool* exc) {
631   RETURN_NATIVE_CALL(to_number, { obj }, exc);
632 }
633
634
635 Handle<Object> Execution::ToString(Handle<Object> obj, bool* exc) {
636   RETURN_NATIVE_CALL(to_string, { obj }, exc);
637 }
638
639
640 Handle<Object> Execution::ToDetailString(Handle<Object> obj, bool* exc) {
641   RETURN_NATIVE_CALL(to_detail_string, { obj }, exc);
642 }
643
644
645 Handle<Object> Execution::ToObject(Handle<Object> obj, bool* exc) {
646   if (obj->IsSpecObject()) return obj;
647   RETURN_NATIVE_CALL(to_object, { obj }, exc);
648 }
649
650
651 Handle<Object> Execution::ToInteger(Handle<Object> obj, bool* exc) {
652   RETURN_NATIVE_CALL(to_integer, { obj }, exc);
653 }
654
655
656 Handle<Object> Execution::ToUint32(Handle<Object> obj, bool* exc) {
657   RETURN_NATIVE_CALL(to_uint32, { obj }, exc);
658 }
659
660
661 Handle<Object> Execution::ToInt32(Handle<Object> obj, bool* exc) {
662   RETURN_NATIVE_CALL(to_int32, { obj }, exc);
663 }
664
665
666 Handle<Object> Execution::NewDate(double time, bool* exc) {
667   Handle<Object> time_obj = FACTORY->NewNumber(time);
668   RETURN_NATIVE_CALL(create_date, { time_obj }, exc);
669 }
670
671
672 #undef RETURN_NATIVE_CALL
673
674
675 Handle<JSRegExp> Execution::NewJSRegExp(Handle<String> pattern,
676                                         Handle<String> flags,
677                                         bool* exc) {
678   Handle<JSFunction> function = Handle<JSFunction>(
679       pattern->GetIsolate()->global_context()->regexp_function());
680   Handle<Object> re_obj = RegExpImpl::CreateRegExpLiteral(
681       function, pattern, flags, exc);
682   if (*exc) return Handle<JSRegExp>();
683   return Handle<JSRegExp>::cast(re_obj);
684 }
685
686
687 Handle<Object> Execution::CharAt(Handle<String> string, uint32_t index) {
688   Isolate* isolate = string->GetIsolate();
689   Factory* factory = isolate->factory();
690
691   int int_index = static_cast<int>(index);
692   if (int_index < 0 || int_index >= string->length()) {
693     return factory->undefined_value();
694   }
695
696   Handle<Object> char_at =
697       GetProperty(isolate->js_builtins_object(),
698                   factory->char_at_symbol());
699   if (!char_at->IsJSFunction()) {
700     return factory->undefined_value();
701   }
702
703   bool caught_exception;
704   Handle<Object> index_object = factory->NewNumberFromInt(int_index);
705   Handle<Object> index_arg[] = { index_object };
706   Handle<Object> result = TryCall(Handle<JSFunction>::cast(char_at),
707                                   string,
708                                   ARRAY_SIZE(index_arg),
709                                   index_arg,
710                                   &caught_exception);
711   if (caught_exception) {
712     return factory->undefined_value();
713   }
714   return result;
715 }
716
717
718 Handle<JSFunction> Execution::InstantiateFunction(
719     Handle<FunctionTemplateInfo> data,
720     bool* exc) {
721   Isolate* isolate = data->GetIsolate();
722   // Fast case: see if the function has already been instantiated
723   int serial_number = Smi::cast(data->serial_number())->value();
724   Object* elm =
725       isolate->global_context()->function_cache()->
726           GetElementNoExceptionThrown(serial_number);
727   if (elm->IsJSFunction()) return Handle<JSFunction>(JSFunction::cast(elm));
728   // The function has not yet been instantiated in this context; do it.
729   Handle<Object> args[] = { data };
730   Handle<Object> result = Call(isolate->instantiate_fun(),
731                                isolate->js_builtins_object(),
732                                ARRAY_SIZE(args),
733                                args,
734                                exc);
735   if (*exc) return Handle<JSFunction>::null();
736   return Handle<JSFunction>::cast(result);
737 }
738
739
740 Handle<JSObject> Execution::InstantiateObject(Handle<ObjectTemplateInfo> data,
741                                               bool* exc) {
742   Isolate* isolate = data->GetIsolate();
743   if (data->property_list()->IsUndefined() &&
744       !data->constructor()->IsUndefined()) {
745     // Initialization to make gcc happy.
746     Object* result = NULL;
747     {
748       HandleScope scope(isolate);
749       Handle<FunctionTemplateInfo> cons_template =
750           Handle<FunctionTemplateInfo>(
751               FunctionTemplateInfo::cast(data->constructor()));
752       Handle<JSFunction> cons = InstantiateFunction(cons_template, exc);
753       if (*exc) return Handle<JSObject>::null();
754       Handle<Object> value = New(cons, 0, NULL, exc);
755       if (*exc) return Handle<JSObject>::null();
756       result = *value;
757     }
758     ASSERT(!*exc);
759     return Handle<JSObject>(JSObject::cast(result));
760   } else {
761     Handle<Object> args[] = { data };
762     Handle<Object> result = Call(isolate->instantiate_fun(),
763                                  isolate->js_builtins_object(),
764                                  ARRAY_SIZE(args),
765                                  args,
766                                  exc);
767     if (*exc) return Handle<JSObject>::null();
768     return Handle<JSObject>::cast(result);
769   }
770 }
771
772
773 void Execution::ConfigureInstance(Handle<Object> instance,
774                                   Handle<Object> instance_template,
775                                   bool* exc) {
776   Isolate* isolate = Isolate::Current();
777   Handle<Object> args[] = { instance, instance_template };
778   Execution::Call(isolate->configure_instance_fun(),
779                   isolate->js_builtins_object(),
780                   ARRAY_SIZE(args),
781                   args,
782                   exc);
783 }
784
785
786 Handle<String> Execution::GetStackTraceLine(Handle<Object> recv,
787                                             Handle<JSFunction> fun,
788                                             Handle<Object> pos,
789                                             Handle<Object> is_global) {
790   Isolate* isolate = fun->GetIsolate();
791   Handle<Object> args[] = { recv, fun, pos, is_global };
792   bool caught_exception;
793   Handle<Object> result = TryCall(isolate->get_stack_trace_line_fun(),
794                                   isolate->js_builtins_object(),
795                                   ARRAY_SIZE(args),
796                                   args,
797                                   &caught_exception);
798   if (caught_exception || !result->IsString()) {
799       return isolate->factory()->empty_symbol();
800   }
801
802   return Handle<String>::cast(result);
803 }
804
805
806 static Object* RuntimePreempt() {
807   Isolate* isolate = Isolate::Current();
808
809   // Clear the preempt request flag.
810   isolate->stack_guard()->Continue(PREEMPT);
811
812   ContextSwitcher::PreemptionReceived();
813
814 #ifdef ENABLE_DEBUGGER_SUPPORT
815   if (isolate->debug()->InDebugger()) {
816     // If currently in the debugger don't do any actual preemption but record
817     // that preemption occoured while in the debugger.
818     isolate->debug()->PreemptionWhileInDebugger();
819   } else {
820     // Perform preemption.
821     v8::Unlocker unlocker(reinterpret_cast<v8::Isolate*>(isolate));
822     Thread::YieldCPU();
823   }
824 #else
825   { // NOLINT
826     // Perform preemption.
827     v8::Unlocker unlocker(reinterpret_cast<v8::Isolate*>(isolate));
828     Thread::YieldCPU();
829   }
830 #endif
831
832   return isolate->heap()->undefined_value();
833 }
834
835
836 #ifdef ENABLE_DEBUGGER_SUPPORT
837 Object* Execution::DebugBreakHelper() {
838   Isolate* isolate = Isolate::Current();
839
840   // Just continue if breaks are disabled.
841   if (isolate->debug()->disable_break()) {
842     return isolate->heap()->undefined_value();
843   }
844
845   // Ignore debug break during bootstrapping.
846   if (isolate->bootstrapper()->IsActive()) {
847     return isolate->heap()->undefined_value();
848   }
849
850   StackLimitCheck check(isolate);
851   if (check.HasOverflowed()) {
852     return isolate->heap()->undefined_value();
853   }
854
855   {
856     JavaScriptFrameIterator it(isolate);
857     ASSERT(!it.done());
858     Object* fun = it.frame()->function();
859     if (fun && fun->IsJSFunction()) {
860       // Don't stop in builtin functions.
861       if (JSFunction::cast(fun)->IsBuiltin()) {
862         return isolate->heap()->undefined_value();
863       }
864       GlobalObject* global = JSFunction::cast(fun)->context()->global();
865       // Don't stop in debugger functions.
866       if (isolate->debug()->IsDebugGlobal(global)) {
867         return isolate->heap()->undefined_value();
868       }
869     }
870   }
871
872   // Collect the break state before clearing the flags.
873   bool debug_command_only =
874       isolate->stack_guard()->IsDebugCommand() &&
875       !isolate->stack_guard()->IsDebugBreak();
876
877   // Clear the debug break request flag.
878   isolate->stack_guard()->Continue(DEBUGBREAK);
879
880   ProcessDebugMessages(debug_command_only);
881
882   // Return to continue execution.
883   return isolate->heap()->undefined_value();
884 }
885
886 void Execution::ProcessDebugMessages(bool debug_command_only) {
887   Isolate* isolate = Isolate::Current();
888   // Clear the debug command request flag.
889   isolate->stack_guard()->Continue(DEBUGCOMMAND);
890
891   StackLimitCheck check(isolate);
892   if (check.HasOverflowed()) {
893     return;
894   }
895
896   HandleScope scope(isolate);
897   // Enter the debugger. Just continue if we fail to enter the debugger.
898   EnterDebugger debugger;
899   if (debugger.FailedToEnter()) {
900     return;
901   }
902
903   // Notify the debug event listeners. Indicate auto continue if the break was
904   // a debug command break.
905   isolate->debugger()->OnDebugBreak(isolate->factory()->undefined_value(),
906                                     debug_command_only);
907 }
908
909
910 #endif
911
912 MaybeObject* Execution::HandleStackGuardInterrupt(Isolate* isolate) {
913   StackGuard* stack_guard = isolate->stack_guard();
914   if (stack_guard->ShouldPostponeInterrupts()) {
915     return isolate->heap()->undefined_value();
916   }
917
918   if (stack_guard->IsGCRequest()) {
919     isolate->heap()->CollectAllGarbage(Heap::kNoGCFlags,
920                                        "StackGuard GC request");
921     stack_guard->Continue(GC_REQUEST);
922   }
923
924   isolate->counters()->stack_interrupts()->Increment();
925   // If FLAG_count_based_interrupts, every interrupt is a profiler interrupt.
926   if (FLAG_count_based_interrupts ||
927       stack_guard->IsRuntimeProfilerTick()) {
928     isolate->counters()->runtime_profiler_ticks()->Increment();
929     stack_guard->Continue(RUNTIME_PROFILER_TICK);
930     isolate->runtime_profiler()->OptimizeNow();
931   }
932 #ifdef ENABLE_DEBUGGER_SUPPORT
933   if (stack_guard->IsDebugBreak() || stack_guard->IsDebugCommand()) {
934     DebugBreakHelper();
935   }
936 #endif
937   if (stack_guard->IsPreempted()) RuntimePreempt();
938   if (stack_guard->IsTerminateExecution()) {
939     stack_guard->Continue(TERMINATE);
940     return isolate->TerminateExecution();
941   }
942   if (stack_guard->IsInterrupted()) {
943     stack_guard->Continue(INTERRUPT);
944     return isolate->StackOverflow();
945   }
946   return isolate->heap()->undefined_value();
947 }
948
949
950 } }  // namespace v8::internal