blob: 996c58c917565cf3898a23cb6e75eeb94c696484 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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 "codegen-inl.h"
34
ager@chromium.orga74f0da2008-12-03 16:05:52 +000035#ifdef ARM
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036#include "simulator-arm.h"
37#else // ia32
38#include "simulator-ia32.h"
39#endif
40
41namespace v8 { namespace internal {
42
43
44static Handle<Object> Invoke(bool construct,
45 Handle<JSFunction> func,
46 Handle<Object> receiver,
47 int argc,
48 Object*** args,
49 bool* has_pending_exception) {
50 // Make sure we have a real function, not a boilerplate function.
51 ASSERT(!func->IsBoilerplate());
52
53 // Entering JavaScript.
54 VMState state(JS);
55
56 // Guard the stack against too much recursion.
57 StackGuard guard;
58
59 // Placeholder for return value.
60 Object* value = reinterpret_cast<Object*>(kZapValue);
61
62 typedef Object* (*JSEntryFunction)(
63 byte* entry,
64 Object* function,
65 Object* receiver,
66 int argc,
67 Object*** args);
68
69 Handle<Code> code;
70 if (construct) {
71 JSConstructEntryStub stub;
72 code = stub.GetCode();
73 } else {
74 JSEntryStub stub;
75 code = stub.GetCode();
76 }
77
kasper.lund44510672008-07-25 07:37:58 +000078 {
79 // Save and restore context around invocation and block the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000080 // allocation of handles without explicit handle scopes.
81 SaveContext save;
82 NoHandleAllocation na;
83 JSEntryFunction entry = FUNCTION_CAST<JSEntryFunction>(code->entry());
84
85 // Call the function through the right JS entry stub.
86 value = CALL_GENERATED_CODE(entry, func->code()->entry(), *func,
87 *receiver, argc, args);
88 }
89
90#ifdef DEBUG
91 value->Verify();
92#endif
93
94 // Update the pending exception flag and return the value.
95 *has_pending_exception = value->IsException();
96 ASSERT(*has_pending_exception == Top::has_pending_exception());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000097 if (*has_pending_exception) {
98 Top::setup_external_caught();
ager@chromium.org3bf7b912008-11-17 09:09:45 +000099 // If the pending exception is OutOfMemoryException set out_of_memory in
100 // the global context. Note: We have to mark the global context here
101 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
102 // set it.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000103 if (Top::pending_exception() == Failure::OutOfMemoryException()) {
104 Top::context()->mark_out_of_memory();
105 }
ager@chromium.org3bf7b912008-11-17 09:09:45 +0000106 return Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000107 }
108
109 return Handle<Object>(value);
110}
111
112
113Handle<Object> Execution::Call(Handle<JSFunction> func,
114 Handle<Object> receiver,
115 int argc,
116 Object*** args,
117 bool* pending_exception) {
118 return Invoke(false, func, receiver, argc, args, pending_exception);
119}
120
121
122Handle<Object> Execution::New(Handle<JSFunction> func, int argc,
123 Object*** args, bool* pending_exception) {
124 return Invoke(true, func, Top::global(), argc, args, pending_exception);
125}
126
127
128Handle<Object> Execution::TryCall(Handle<JSFunction> func,
129 Handle<Object> receiver,
130 int argc,
131 Object*** args,
132 bool* caught_exception) {
133 // Enter a try-block while executing the JavaScript code. To avoid
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000134 // duplicate error printing it must be non-verbose. Also, to avoid
135 // creating message objects during stack overflow we shouldn't
136 // capture messages.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000137 v8::TryCatch catcher;
138 catcher.SetVerbose(false);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000139 catcher.SetCaptureMessage(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000140
141 Handle<Object> result = Invoke(false, func, receiver, argc, args,
142 caught_exception);
143
144 if (*caught_exception) {
145 ASSERT(catcher.HasCaught());
146 ASSERT(Top::has_pending_exception());
147 ASSERT(Top::external_caught_exception());
148 Top::optional_reschedule_exception(true);
149 result = v8::Utils::OpenHandle(*catcher.Exception());
150 }
151
152 ASSERT(!Top::has_pending_exception());
153 ASSERT(!Top::external_caught_exception());
154 return result;
155}
156
157
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000158Handle<Object> Execution::GetFunctionDelegate(Handle<Object> object) {
159 ASSERT(!object->IsJSFunction());
160
161 // If you return a function from here, it will be called when an
162 // attempt is made to call the given object as a function.
163
164 // The regular expression code here is really meant more as an
165 // example than anything else. KJS does not support calling regular
166 // expressions as functions, but SpiderMonkey does.
167 if (FLAG_call_regexp) {
168 bool is_regexp =
169 object->IsHeapObject() &&
170 (HeapObject::cast(*object)->map()->constructor() ==
171 *Top::regexp_function());
172
173 if (is_regexp) {
174 Handle<String> exec = Factory::exec_symbol();
175 return Handle<Object>(object->GetProperty(*exec));
176 }
177 }
178
179 // Objects created through the API can have an instance-call handler
180 // that should be used when calling the object as a function.
181 if (object->IsHeapObject() &&
182 HeapObject::cast(*object)->map()->has_instance_call_handler()) {
183 return Handle<JSFunction>(
184 Top::global_context()->call_as_function_delegate());
185 }
186
187 return Factory::undefined_value();
188}
189
190
191// Static state for stack guards.
192StackGuard::ThreadLocal StackGuard::thread_local_;
193
194
195StackGuard::StackGuard() {
196 ExecutionAccess access;
197 if (thread_local_.nesting_++ == 0 &&
198 thread_local_.jslimit_ != kInterruptLimit) {
199 // NOTE: We assume that the stack grows towards lower addresses.
200 ASSERT(thread_local_.jslimit_ == kIllegalLimit);
201 ASSERT(thread_local_.climit_ == kIllegalLimit);
202
203 thread_local_.initial_jslimit_ = thread_local_.jslimit_ =
kasper.lund7276f142008-07-30 08:49:36 +0000204 GENERATED_CODE_STACK_LIMIT(kLimitSize);
v8.team.kasperl727e9952008-09-02 14:56:44 +0000205 // NOTE: The check for overflow is not safe as there is no guarantee that
kasper.lund7276f142008-07-30 08:49:36 +0000206 // the running thread has its stack in all memory up to address 0x00000000.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000207 thread_local_.initial_climit_ = thread_local_.climit_ =
kasper.lund7276f142008-07-30 08:49:36 +0000208 reinterpret_cast<uintptr_t>(this) >= kLimitSize ?
209 reinterpret_cast<uintptr_t>(this) - kLimitSize : 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000210
211 if (thread_local_.interrupt_flags_ != 0) {
212 set_limits(kInterruptLimit, access);
213 }
214 }
215 // make sure we have proper limits setup
216 ASSERT(thread_local_.jslimit_ != kIllegalLimit &&
217 thread_local_.climit_ != kIllegalLimit);
218}
219
220
221StackGuard::~StackGuard() {
222 ExecutionAccess access;
223 if (--thread_local_.nesting_ == 0) {
224 set_limits(kIllegalLimit, access);
225 }
226}
227
228
229bool StackGuard::IsStackOverflow() {
230 ExecutionAccess access;
231 return (thread_local_.jslimit_ != kInterruptLimit &&
232 thread_local_.climit_ != kInterruptLimit);
233}
234
235
236void StackGuard::EnableInterrupts() {
237 ExecutionAccess access;
238 if (IsSet(access)) {
239 set_limits(kInterruptLimit, access);
240 }
241}
242
243
244void StackGuard::SetStackLimit(uintptr_t limit) {
245 ExecutionAccess access;
246 // If the current limits are special (eg due to a pending interrupt) then
247 // leave them alone.
248 if (thread_local_.jslimit_ == thread_local_.initial_jslimit_) {
249 thread_local_.jslimit_ = limit;
250 }
251 if (thread_local_.climit_ == thread_local_.initial_climit_) {
252 thread_local_.climit_ = limit;
253 }
254 thread_local_.initial_climit_ = limit;
255 thread_local_.initial_jslimit_ = limit;
256}
257
258
259void StackGuard::DisableInterrupts() {
260 ExecutionAccess access;
261 reset_limits(access);
262}
263
264
265bool StackGuard::IsSet(const ExecutionAccess& lock) {
266 return thread_local_.interrupt_flags_ != 0;
267}
268
269
270bool StackGuard::IsInterrupted() {
271 ExecutionAccess access;
272 return thread_local_.interrupt_flags_ & INTERRUPT;
273}
274
275
276void StackGuard::Interrupt() {
277 ExecutionAccess access;
278 thread_local_.interrupt_flags_ |= INTERRUPT;
kasper.lund7276f142008-07-30 08:49:36 +0000279 set_limits(kInterruptLimit, access);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000280}
281
282
283bool StackGuard::IsPreempted() {
284 ExecutionAccess access;
285 return thread_local_.interrupt_flags_ & PREEMPT;
286}
287
288
289void StackGuard::Preempt() {
290 ExecutionAccess access;
291 thread_local_.interrupt_flags_ |= PREEMPT;
kasper.lund7276f142008-07-30 08:49:36 +0000292 set_limits(kInterruptLimit, access);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000293}
294
295
296bool StackGuard::IsDebugBreak() {
297 ExecutionAccess access;
298 return thread_local_.interrupt_flags_ & DEBUGBREAK;
299}
300
kasper.lund44510672008-07-25 07:37:58 +0000301
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000302void StackGuard::DebugBreak() {
303 ExecutionAccess access;
kasper.lund7276f142008-07-30 08:49:36 +0000304 thread_local_.interrupt_flags_ |= DEBUGBREAK;
305 set_limits(kInterruptLimit, access);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000306}
307
308
309void StackGuard::Continue(InterruptFlag after_what) {
310 ExecutionAccess access;
311 thread_local_.interrupt_flags_ &= ~static_cast<int>(after_what);
312 if (thread_local_.interrupt_flags_ == 0) {
313 reset_limits(access);
314 }
315}
316
317
318int StackGuard::ArchiveSpacePerThread() {
319 return sizeof(ThreadLocal);
320}
321
322
323char* StackGuard::ArchiveStackGuard(char* to) {
324 ExecutionAccess access;
325 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
326 ThreadLocal blank;
327 thread_local_ = blank;
328 return to + sizeof(ThreadLocal);
329}
330
331
332char* StackGuard::RestoreStackGuard(char* from) {
333 ExecutionAccess access;
334 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
335 return from + sizeof(ThreadLocal);
336}
337
338
339// --- C a l l s t o n a t i v e s ---
340
341#define RETURN_NATIVE_CALL(name, argc, argv, has_pending_exception) \
342 do { \
343 Object** args[argc] = argv; \
344 ASSERT(has_pending_exception != NULL); \
345 return Call(Top::name##_fun(), Top::builtins(), argc, args, \
346 has_pending_exception); \
347 } while (false)
348
349
350Handle<Object> Execution::ToBoolean(Handle<Object> obj) {
351 // See the similar code in runtime.js:ToBoolean.
352 if (obj->IsBoolean()) return obj;
353 bool result = true;
354 if (obj->IsString()) {
355 result = Handle<String>::cast(obj)->length() != 0;
356 } else if (obj->IsNull() || obj->IsUndefined()) {
357 result = false;
358 } else if (obj->IsNumber()) {
359 double value = obj->Number();
360 result = !((value == 0) || isnan(value));
361 }
362 return Handle<Object>(Heap::ToBoolean(result));
363}
364
365
366Handle<Object> Execution::ToNumber(Handle<Object> obj, bool* exc) {
367 RETURN_NATIVE_CALL(to_number, 1, { obj.location() }, exc);
368}
369
370
371Handle<Object> Execution::ToString(Handle<Object> obj, bool* exc) {
372 RETURN_NATIVE_CALL(to_string, 1, { obj.location() }, exc);
373}
374
375
376Handle<Object> Execution::ToDetailString(Handle<Object> obj, bool* exc) {
377 RETURN_NATIVE_CALL(to_detail_string, 1, { obj.location() }, exc);
378}
379
380
381Handle<Object> Execution::ToObject(Handle<Object> obj, bool* exc) {
382 if (obj->IsJSObject()) return obj;
383 RETURN_NATIVE_CALL(to_object, 1, { obj.location() }, exc);
384}
385
386
387Handle<Object> Execution::ToInteger(Handle<Object> obj, bool* exc) {
388 RETURN_NATIVE_CALL(to_integer, 1, { obj.location() }, exc);
389}
390
391
392Handle<Object> Execution::ToUint32(Handle<Object> obj, bool* exc) {
393 RETURN_NATIVE_CALL(to_uint32, 1, { obj.location() }, exc);
394}
395
396
397Handle<Object> Execution::ToInt32(Handle<Object> obj, bool* exc) {
398 RETURN_NATIVE_CALL(to_int32, 1, { obj.location() }, exc);
399}
400
401
402Handle<Object> Execution::NewDate(double time, bool* exc) {
403 Handle<Object> time_obj = Factory::NewNumber(time);
404 RETURN_NATIVE_CALL(create_date, 1, { time_obj.location() }, exc);
405}
406
407
408#undef RETURN_NATIVE_CALL
409
410
411Handle<Object> Execution::CharAt(Handle<String> string, uint32_t index) {
412 int int_index = static_cast<int>(index);
413 if (int_index < 0 || int_index >= string->length()) {
414 return Factory::undefined_value();
415 }
416
417 Handle<Object> char_at =
418 GetProperty(Top::builtins(), Factory::char_at_symbol());
419 if (!char_at->IsJSFunction()) {
420 return Factory::undefined_value();
421 }
422
423 bool caught_exception;
424 Handle<Object> index_object = Factory::NewNumberFromInt(int_index);
425 Object** index_arg[] = { index_object.location() };
426 Handle<Object> result = TryCall(Handle<JSFunction>::cast(char_at),
427 string,
428 ARRAY_SIZE(index_arg),
429 index_arg,
430 &caught_exception);
431 if (caught_exception) {
432 return Factory::undefined_value();
433 }
434 return result;
435}
436
437
438Handle<JSFunction> Execution::InstantiateFunction(
439 Handle<FunctionTemplateInfo> data, bool* exc) {
440 // Fast case: see if the function has already been instantiated
441 int serial_number = Smi::cast(data->serial_number())->value();
442 Object* elm =
443 Top::global_context()->function_cache()->GetElement(serial_number);
444 if (!elm->IsUndefined()) return Handle<JSFunction>(JSFunction::cast(elm));
445 // The function has not yet been instantiated in this context; do it.
446 Object** args[1] = { Handle<Object>::cast(data).location() };
447 Handle<Object> result =
448 Call(Top::instantiate_fun(), Top::builtins(), 1, args, exc);
449 if (*exc) return Handle<JSFunction>::null();
450 return Handle<JSFunction>::cast(result);
451}
452
453
454Handle<JSObject> Execution::InstantiateObject(Handle<ObjectTemplateInfo> data,
455 bool* exc) {
456 if (data->property_list()->IsUndefined() &&
457 !data->constructor()->IsUndefined()) {
458 Object* result;
459 {
460 HandleScope scope;
461 Handle<FunctionTemplateInfo> cons_template =
462 Handle<FunctionTemplateInfo>(
463 FunctionTemplateInfo::cast(data->constructor()));
464 Handle<JSFunction> cons = InstantiateFunction(cons_template, exc);
465 if (*exc) return Handle<JSObject>::null();
466 Handle<Object> value = New(cons, 0, NULL, exc);
467 if (*exc) return Handle<JSObject>::null();
468 result = *value;
469 }
470 ASSERT(!*exc);
471 return Handle<JSObject>(JSObject::cast(result));
472 } else {
473 Object** args[1] = { Handle<Object>::cast(data).location() };
474 Handle<Object> result =
475 Call(Top::instantiate_fun(), Top::builtins(), 1, args, exc);
476 if (*exc) return Handle<JSObject>::null();
477 return Handle<JSObject>::cast(result);
478 }
479}
480
481
482void Execution::ConfigureInstance(Handle<Object> instance,
483 Handle<Object> instance_template,
484 bool* exc) {
485 Object** args[2] = { instance.location(), instance_template.location() };
486 Execution::Call(Top::configure_instance_fun(), Top::builtins(), 2, args, exc);
487}
488
489
490Handle<String> Execution::GetStackTraceLine(Handle<Object> recv,
491 Handle<JSFunction> fun,
492 Handle<Object> pos,
493 Handle<Object> is_global) {
494 const int argc = 4;
495 Object** args[argc] = { recv.location(),
496 Handle<Object>::cast(fun).location(),
497 pos.location(),
498 is_global.location() };
499 bool caught_exception = false;
500 Handle<Object> result = TryCall(Top::get_stack_trace_line_fun(),
501 Top::builtins(), argc, args,
502 &caught_exception);
503 if (caught_exception || !result->IsString()) return Factory::empty_symbol();
504 return Handle<String>::cast(result);
505}
506
507
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000508// --- G C E x t e n s i o n ---
509
510const char* GCExtension::kSource = "native function gc();";
511
512
513v8::Handle<v8::FunctionTemplate> GCExtension::GetNativeFunction(
514 v8::Handle<v8::String> str) {
515 return v8::FunctionTemplate::New(GCExtension::GC);
516}
517
518
519v8::Handle<v8::Value> GCExtension::GC(const v8::Arguments& args) {
520 // All allocation spaces other than NEW_SPACE have the same effect.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000521 Heap::CollectGarbage(0, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000522 return v8::Undefined();
523}
524
525
526static GCExtension kGCExtension;
527v8::DeclareExtension kGCExtensionDeclaration(&kGCExtension);
528
529} } // namespace v8::internal