execution.cc 16.4 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/execution.h"
6

7 8
#include "src/bootstrapper.h"
#include "src/codegen.h"
9
#include "src/compiler-dispatcher/optimizing-compile-dispatcher.h"
10
#include "src/debug/debug.h"
11
#include "src/isolate-inl.h"
12
#include "src/messages.h"
13
#include "src/runtime-profiler.h"
14
#include "src/vm-state-inl.h"
15

16 17
namespace v8 {
namespace internal {
18

19 20 21 22 23 24
StackGuard::StackGuard()
    : isolate_(NULL) {
}


void StackGuard::set_interrupt_limits(const ExecutionAccess& lock) {
25
  DCHECK(isolate_ != NULL);
26 27
  thread_local_.set_jslimit(kInterruptLimit);
  thread_local_.set_climit(kInterruptLimit);
28 29 30 31 32
  isolate_->heap()->SetStackLimits();
}


void StackGuard::reset_limits(const ExecutionAccess& lock) {
33
  DCHECK(isolate_ != NULL);
34 35
  thread_local_.set_jslimit(thread_local_.real_jslimit_);
  thread_local_.set_climit(thread_local_.real_climit_);
36 37 38 39
  isolate_->heap()->SetStackLimits();
}


40
static void PrintDeserializedCodeInfo(Handle<JSFunction> function) {
41 42
  if (function->code() == function->shared()->code() &&
      function->shared()->deserialized()) {
43
    PrintF("[Running deserialized script");
44
    Object* script = function->shared()->script();
45 46 47 48 49 50 51
    if (script->IsScript()) {
      Object* name = Script::cast(script)->name();
      if (name->IsString()) {
        PrintF(": %s", String::cast(name)->ToCString().get());
      }
    }
    PrintF("]\n");
52 53 54 55
  }
}


56 57
namespace {

58 59 60 61
MUST_USE_RESULT MaybeHandle<Object> Invoke(
    Isolate* isolate, bool is_construct, Handle<Object> target,
    Handle<Object> receiver, int argc, Handle<Object> args[],
    Handle<Object> new_target, Execution::MessageHandling message_handling) {
62
  DCHECK(!receiver->IsJSGlobalObject());
63

64 65 66 67 68 69 70 71
#ifdef USE_SIMULATOR
  // Simulators use separate stacks for C++ and JS. JS stack overflow checks
  // are performed whenever a JS function is called. However, it can be the case
  // that the C++ stack grows faster than the JS stack, resulting in an overflow
  // there. Add a check here to make that less likely.
  StackLimitCheck check(isolate);
  if (check.HasOverflowed()) {
    isolate->StackOverflow();
72 73 74
    if (message_handling == Execution::MessageHandling::kReport) {
      isolate->ReportPendingMessages();
    }
75 76 77 78
    return MaybeHandle<Object>();
  }
#endif

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  // api callbacks can be called directly.
  if (target->IsJSFunction()) {
    Handle<JSFunction> function = Handle<JSFunction>::cast(target);
    if ((!is_construct || function->IsConstructor()) &&
        function->shared()->IsApiFunction()) {
      SaveContext save(isolate);
      isolate->set_context(function->context());
      DCHECK(function->context()->global_object()->IsJSGlobalObject());
      if (is_construct) receiver = isolate->factory()->the_hole_value();
      auto value = Builtins::InvokeApiFunction(
          isolate, is_construct, function, receiver, argc, args,
          Handle<HeapObject>::cast(new_target));
      bool has_exception = value.is_null();
      DCHECK(has_exception == isolate->has_pending_exception());
      if (has_exception) {
94 95 96
        if (message_handling == Execution::MessageHandling::kReport) {
          isolate->ReportPendingMessages();
        }
97 98 99 100 101 102 103 104
        return MaybeHandle<Object>();
      } else {
        isolate->clear_pending_message();
      }
      return value;
    }
  }

105
  // Entering JavaScript.
106
  VMState<JS> state(isolate);
107
  CHECK(AllowJavascriptExecution::IsAllowed(isolate));
108 109
  if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) {
    isolate->ThrowIllegalOperation();
110 111 112
    if (message_handling == Execution::MessageHandling::kReport) {
      isolate->ReportPendingMessages();
    }
113
    return MaybeHandle<Object>();
114
  }
115 116

  // Placeholder for return value.
117
  Object* value = NULL;
118

119
  typedef Object* (*JSEntryFunction)(Object* new_target, Object* target,
120
                                     Object* receiver, int argc,
121
                                     Object*** args);
122

123 124 125
  Handle<Code> code = is_construct
      ? isolate->factory()->js_construct_entry_code()
      : isolate->factory()->js_entry_code();
126

127 128
  {
    // Save and restore context around invocation and block the
129
    // allocation of handles without explicit handle scopes.
130
    SaveContext save(isolate);
131
    SealHandleScope shs(isolate);
132
    JSEntryFunction stub_entry = FUNCTION_CAST<JSEntryFunction>(code->entry());
133

134 135
    if (FLAG_clear_exceptions_on_js_entry) isolate->clear_pending_exception();

136
    // Call the function through the right JS entry stub.
137
    Object* orig_func = *new_target;
138
    Object* func = *target;
139 140
    Object* recv = *receiver;
    Object*** argv = reinterpret_cast<Object***>(args);
141 142 143
    if (FLAG_profile_deserialization && target->IsJSFunction()) {
      PrintDeserializedCodeInfo(Handle<JSFunction>::cast(target));
    }
144
    RuntimeCallTimerScope timer(isolate, &RuntimeCallStats::JS_Execution);
145 146
    value = CALL_GENERATED_CODE(isolate, stub_entry, orig_func, func, recv,
                                argc, argv);
147 148
  }

149
#ifdef VERIFY_HEAP
150 151 152
  if (FLAG_verify_heap) {
    value->ObjectVerify();
  }
153 154
#endif

155
  // Update the pending exception flag and return the value.
156
  bool has_exception = value->IsException(isolate);
157
  DCHECK(has_exception == isolate->has_pending_exception());
158
  if (has_exception) {
159 160 161
    if (message_handling == Execution::MessageHandling::kReport) {
      isolate->ReportPendingMessages();
    }
162
    return MaybeHandle<Object>();
163
  } else {
164
    isolate->clear_pending_message();
165 166
  }

167
  return Handle<Object>(value, isolate);
168 169
}

170 171 172 173
MaybeHandle<Object> CallInternal(Isolate* isolate, Handle<Object> callable,
                                 Handle<Object> receiver, int argc,
                                 Handle<Object> argv[],
                                 Execution::MessageHandling message_handling) {
174 175 176
  // Convert calls on global objects to be calls on the global
  // receiver instead to avoid having a 'this' pointer which refers
  // directly to a global object.
177
  if (receiver->IsJSGlobalObject()) {
178
    receiver =
179
        handle(Handle<JSGlobalObject>::cast(receiver)->global_proxy(), isolate);
180 181
  }
  return Invoke(isolate, false, callable, receiver, argc, argv,
182 183 184 185 186 187 188 189 190 191 192
                isolate->factory()->undefined_value(), message_handling);
}

}  // namespace

// static
MaybeHandle<Object> Execution::Call(Isolate* isolate, Handle<Object> callable,
                                    Handle<Object> receiver, int argc,
                                    Handle<Object> argv[]) {
  return CallInternal(isolate, callable, receiver, argc, argv,
                      MessageHandling::kReport);
193 194
}

195

196
// static
197 198
MaybeHandle<Object> Execution::New(Handle<JSFunction> constructor, int argc,
                                   Handle<Object> argv[]) {
199
  return New(constructor->GetIsolate(), constructor, constructor, argc, argv);
200 201 202
}


203 204 205
// static
MaybeHandle<Object> Execution::New(Isolate* isolate, Handle<Object> constructor,
                                   Handle<Object> new_target, int argc,
206
                                   Handle<Object> argv[]) {
207
  return Invoke(isolate, true, constructor,
208 209
                isolate->factory()->undefined_value(), argc, argv, new_target,
                MessageHandling::kReport);
210 211
}

212 213
MaybeHandle<Object> Execution::TryCall(Isolate* isolate,
                                       Handle<Object> callable,
214
                                       Handle<Object> receiver, int argc,
215
                                       Handle<Object> args[],
216
                                       MessageHandling message_handling,
217 218 219 220
                                       MaybeHandle<Object>* exception_out) {
  bool is_termination = false;
  MaybeHandle<Object> maybe_result;
  if (exception_out != NULL) *exception_out = MaybeHandle<Object>();
221 222
  DCHECK_IMPLIES(message_handling == MessageHandling::kKeepPending,
                 exception_out == nullptr);
223
  // Enter a try-block while executing the JavaScript code. To avoid
224 225 226
  // duplicate error printing it must be non-verbose.  Also, to avoid
  // creating message objects during stack overflow we shouldn't
  // capture messages.
227
  {
228
    v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate));
229 230 231
    catcher.SetVerbose(false);
    catcher.SetCaptureMessage(false);

232 233
    maybe_result =
        CallInternal(isolate, callable, receiver, argc, args, message_handling);
234 235 236

    if (maybe_result.is_null()) {
      DCHECK(isolate->has_pending_exception());
237 238 239 240
      if (isolate->pending_exception() ==
          isolate->heap()->termination_exception()) {
        is_termination = true;
      } else {
241 242 243
        if (exception_out != nullptr) {
          DCHECK(catcher.HasCaught());
          DCHECK(isolate->external_caught_exception());
244 245
          *exception_out = v8::Utils::OpenHandle(*catcher.Exception());
        }
246
      }
247 248 249
      if (message_handling == MessageHandling::kReport) {
        isolate->OptionalRescheduleException(true);
      }
250
    }
251
  }
252 253 254 255

  // Re-request terminate execution interrupt to trigger later.
  if (is_termination) isolate->stack_guard()->RequestTerminateExecution();

256
  return maybe_result;
257 258 259 260
}


void StackGuard::SetStackLimit(uintptr_t limit) {
261
  ExecutionAccess access(isolate_);
262
  // If the current limits are special (e.g. due to a pending interrupt) then
263
  // leave them alone.
264
  uintptr_t jslimit = SimulatorStack::JsLimitFromCLimit(isolate_, limit);
265 266
  if (thread_local_.jslimit() == thread_local_.real_jslimit_) {
    thread_local_.set_jslimit(jslimit);
267
  }
268 269
  if (thread_local_.climit() == thread_local_.real_climit_) {
    thread_local_.set_climit(limit);
270
  }
271 272
  thread_local_.real_climit_ = limit;
  thread_local_.real_jslimit_ = jslimit;
273 274 275
}


276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
void StackGuard::AdjustStackLimitForSimulator() {
  ExecutionAccess access(isolate_);
  uintptr_t climit = thread_local_.real_climit_;
  // If the current limits are special (e.g. due to a pending interrupt) then
  // leave them alone.
  uintptr_t jslimit = SimulatorStack::JsLimitFromCLimit(isolate_, climit);
  if (thread_local_.jslimit() == thread_local_.real_jslimit_) {
    thread_local_.set_jslimit(jslimit);
    isolate_->heap()->SetStackLimits();
  }
}


void StackGuard::EnableInterrupts() {
  ExecutionAccess access(isolate_);
  if (has_pending_interrupts(access)) {
    set_interrupt_limits(access);
  }
}


297
void StackGuard::DisableInterrupts() {
298
  ExecutionAccess access(isolate_);
299 300 301 302
  reset_limits(access);
}


303
void StackGuard::PushPostponeInterruptsScope(PostponeInterruptsScope* scope) {
304
  ExecutionAccess access(isolate_);
305 306 307 308 309 310 311 312
  // Intercept already requested interrupts.
  int intercepted = thread_local_.interrupt_flags_ & scope->intercept_mask_;
  scope->intercepted_flags_ = intercepted;
  thread_local_.interrupt_flags_ &= ~intercepted;
  if (!has_pending_interrupts(access)) reset_limits(access);
  // Add scope to the chain.
  scope->prev_ = thread_local_.postpone_interrupts_;
  thread_local_.postpone_interrupts_ = scope;
313 314 315
}


316
void StackGuard::PopPostponeInterruptsScope() {
317
  ExecutionAccess access(isolate_);
318 319
  PostponeInterruptsScope* top = thread_local_.postpone_interrupts_;
  // Make intercepted interrupts active.
320
  DCHECK((thread_local_.interrupt_flags_ & top->intercept_mask_) == 0);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
  thread_local_.interrupt_flags_ |= top->intercepted_flags_;
  if (has_pending_interrupts(access)) set_interrupt_limits(access);
  // Remove scope from chain.
  thread_local_.postpone_interrupts_ = top->prev_;
}


bool StackGuard::CheckInterrupt(InterruptFlag flag) {
  ExecutionAccess access(isolate_);
  return thread_local_.interrupt_flags_ & flag;
}


void StackGuard::RequestInterrupt(InterruptFlag flag) {
  ExecutionAccess access(isolate_);
  // Check the chain of PostponeInterruptsScopes for interception.
  if (thread_local_.postpone_interrupts_ &&
      thread_local_.postpone_interrupts_->Intercept(flag)) {
    return;
  }

  // Not intercepted.  Set as active interrupt flag.
  thread_local_.interrupt_flags_ |= flag;
344
  set_interrupt_limits(access);
345 346 347

  // If this isolate is waiting in a futex, notify it to wake up.
  isolate_->futex_wait_list_node()->NotifyWake();
348 349 350
}


351
void StackGuard::ClearInterrupt(InterruptFlag flag) {
352
  ExecutionAccess access(isolate_);
353 354 355 356 357
  // Clear the interrupt flag from the chain of PostponeInterruptsScopes.
  for (PostponeInterruptsScope* current = thread_local_.postpone_interrupts_;
       current != NULL;
       current = current->prev_) {
    current->intercepted_flags_ &= ~flag;
358
  }
359 360 361 362

  // Clear the interrupt flag from the active interrupt flags.
  thread_local_.interrupt_flags_ &= ~flag;
  if (!has_pending_interrupts(access)) reset_limits(access);
363 364 365
}


366 367
bool StackGuard::CheckAndClearInterrupt(InterruptFlag flag) {
  ExecutionAccess access(isolate_);
368 369 370
  bool result = (thread_local_.interrupt_flags_ & flag);
  thread_local_.interrupt_flags_ &= ~flag;
  if (!has_pending_interrupts(access)) reset_limits(access);
371 372 373 374
  return result;
}


375
char* StackGuard::ArchiveStackGuard(char* to) {
376
  ExecutionAccess access(isolate_);
377
  MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
378
  ThreadLocal blank;
379 380 381 382 383 384 385

  // Set the stack limits using the old thread_local_.
  // TODO(isolates): This was the old semantics of constructing a ThreadLocal
  //                 (as the ctor called SetStackLimits, which looked at the
  //                 current thread_local_ from StackGuard)-- but is this
  //                 really what was intended?
  isolate_->heap()->SetStackLimits();
386
  thread_local_ = blank;
387

388 389 390 391 392
  return to + sizeof(ThreadLocal);
}


char* StackGuard::RestoreStackGuard(char* from) {
393
  ExecutionAccess access(isolate_);
394
  MemCopy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
395
  isolate_->heap()->SetStackLimits();
396 397 398 399
  return from + sizeof(ThreadLocal);
}


400
void StackGuard::FreeThreadResources() {
401 402 403
  Isolate::PerIsolateThreadData* per_thread =
      isolate_->FindOrAllocatePerThreadDataForThisThread();
  per_thread->set_stack_limit(thread_local_.real_climit_);
404 405 406 407
}


void StackGuard::ThreadLocal::Clear() {
408
  real_jslimit_ = kIllegalLimit;
409
  set_jslimit(kIllegalLimit);
410
  real_climit_ = kIllegalLimit;
411
  set_climit(kIllegalLimit);
412
  postpone_interrupts_ = NULL;
413 414 415 416
  interrupt_flags_ = 0;
}


417
bool StackGuard::ThreadLocal::Initialize(Isolate* isolate) {
418
  bool should_set_stack_limits = false;
419
  if (real_climit_ == kIllegalLimit) {
420
    const uintptr_t kLimitSize = FLAG_stack_size * KB;
421
    DCHECK(GetCurrentStackPosition() > kLimitSize);
422
    uintptr_t limit = GetCurrentStackPosition() - kLimitSize;
423
    real_jslimit_ = SimulatorStack::JsLimitFromCLimit(isolate, limit);
424
    set_jslimit(SimulatorStack::JsLimitFromCLimit(isolate, limit));
425
    real_climit_ = limit;
426
    set_climit(limit);
427
    should_set_stack_limits = true;
428
  }
429
  postpone_interrupts_ = NULL;
430
  interrupt_flags_ = 0;
431
  return should_set_stack_limits;
432 433 434 435 436
}


void StackGuard::ClearThread(const ExecutionAccess& lock) {
  thread_local_.Clear();
437
  isolate_->heap()->SetStackLimits();
438 439 440 441
}


void StackGuard::InitThread(const ExecutionAccess& lock) {
442 443 444 445
  if (thread_local_.Initialize(isolate_)) isolate_->heap()->SetStackLimits();
  Isolate::PerIsolateThreadData* per_thread =
      isolate_->FindOrAllocatePerThreadDataForThisThread();
  uintptr_t stored_limit = per_thread->stack_limit();
446
  // You should hold the ExecutionAccess lock when you call this.
447
  if (stored_limit != 0) {
448
    SetStackLimit(stored_limit);
449
  }
450 451 452
}


453 454 455
// --- C a l l s   t o   n a t i v e s ---


456
void StackGuard::HandleGCInterrupt() {
457 458 459 460 461 462
  if (CheckAndClearInterrupt(GC_REQUEST)) {
    isolate_->heap()->HandleGCRequest();
  }
}


463
Object* StackGuard::HandleInterrupts() {
464 465 466 467 468
  if (FLAG_verify_predictable) {
    // Advance synthetic time by making a time request.
    isolate_->heap()->MonotonicallyIncreasingTimeInMs();
  }

469
  if (CheckAndClearInterrupt(GC_REQUEST)) {
470
    isolate_->heap()->HandleGCRequest();
471
  }
472

473
  if (CheckDebugBreak()) {
474
    isolate_->debug()->HandleDebugBreak(kIgnoreIfTopFrameBlackboxed);
475
  }
476

477 478 479
  if (CheckAndClearInterrupt(TERMINATE_EXECUTION)) {
    return isolate_->TerminateExecution();
  }
480

481 482 483
  if (CheckAndClearInterrupt(DEOPT_MARKED_ALLOCATION_SITES)) {
    isolate_->heap()->DeoptMarkedAllocationSites();
  }
484

485
  if (CheckAndClearInterrupt(INSTALL_CODE)) {
486
    DCHECK(isolate_->concurrent_recompilation_enabled());
487
    isolate_->optimizing_compile_dispatcher()->InstallOptimizedFunctions();
488
  }
489

490
  if (CheckAndClearInterrupt(API_INTERRUPT)) {
491 492
    // Callbacks must be invoked outside of ExecusionAccess lock.
    isolate_->InvokeApiInterruptCallbacks();
493
  }
494

495 496
  isolate_->counters()->stack_interrupts()->Increment();
  isolate_->counters()->runtime_profiler_ticks()->Increment();
497
  isolate_->runtime_profiler()->MarkCandidatesForOptimization();
498

499
  return isolate_->heap()->undefined_value();
500 501
}

502 503
}  // namespace internal
}  // namespace v8