runtime-test.cc 27.6 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/runtime/runtime-utils.h"
6

7 8
#include <memory>

9
#include "src/arguments.h"
10
#include "src/compiler-dispatcher/optimizing-compile-dispatcher.h"
11
#include "src/compiler.h"
12
#include "src/deoptimizer.h"
13
#include "src/frames-inl.h"
14
#include "src/full-codegen/full-codegen.h"
15
#include "src/isolate-inl.h"
16
#include "src/runtime-profiler.h"
17
#include "src/snapshot/code-serializer.h"
18
#include "src/snapshot/natives.h"
19
#include "src/wasm/wasm-module.h"
20
#include "src/wasm/wasm-objects.h"
21 22 23 24

namespace v8 {
namespace internal {

25 26
RUNTIME_FUNCTION(Runtime_ConstructDouble) {
  HandleScope scope(isolate);
27
  DCHECK_EQ(2, args.length());
28 29 30 31 32 33
  CONVERT_NUMBER_CHECKED(uint32_t, hi, Uint32, args[0]);
  CONVERT_NUMBER_CHECKED(uint32_t, lo, Uint32, args[1]);
  uint64_t result = (static_cast<uint64_t>(hi) << 32) | lo;
  return *isolate->factory()->NewNumber(uint64_to_double(result));
}

34 35
RUNTIME_FUNCTION(Runtime_DeoptimizeFunction) {
  HandleScope scope(isolate);
36
  DCHECK_EQ(1, args.length());
37 38 39 40 41 42 43 44 45

  // This function is used by fuzzers to get coverage in compiler.
  // Ignore calls on non-function objects to avoid runtime errors.
  CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
  if (!function_object->IsJSFunction()) {
    return isolate->heap()->undefined_value();
  }
  Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);

46
  // If the function is not optimized, just return.
47 48 49
  if (!function->IsOptimized()) return isolate->heap()->undefined_value();

  // TODO(turbofan): Deoptimization is not supported yet.
50
  if (function->code()->is_turbofanned() &&
51
      function->shared()->asm_function()) {
52 53 54 55 56 57 58 59 60
    return isolate->heap()->undefined_value();
  }

  Deoptimizer::DeoptimizeFunction(*function);

  return isolate->heap()->undefined_value();
}


61 62
RUNTIME_FUNCTION(Runtime_DeoptimizeNow) {
  HandleScope scope(isolate);
63
  DCHECK_EQ(0, args.length());
64 65 66

  Handle<JSFunction> function;

67
  // Find the JavaScript function on the top of the stack.
68
  JavaScriptFrameIterator it(isolate);
69
  if (!it.done()) function = Handle<JSFunction>(it.frame()->function());
70 71
  if (function.is_null()) return isolate->heap()->undefined_value();

72
  // If the function is not optimized, just return.
73 74 75
  if (!function->IsOptimized()) return isolate->heap()->undefined_value();

  // TODO(turbofan): Deoptimization is not supported yet.
76
  if (function->code()->is_turbofanned() &&
77
      function->shared()->asm_function()) {
78 79 80 81 82 83 84 85 86
    return isolate->heap()->undefined_value();
  }

  Deoptimizer::DeoptimizeFunction(*function);

  return isolate->heap()->undefined_value();
}


87 88
RUNTIME_FUNCTION(Runtime_RunningInSimulator) {
  SealHandleScope shs(isolate);
89
  DCHECK_EQ(0, args.length());
90 91 92 93 94 95 96 97 98 99
#if defined(USE_SIMULATOR)
  return isolate->heap()->true_value();
#else
  return isolate->heap()->false_value();
#endif
}


RUNTIME_FUNCTION(Runtime_IsConcurrentRecompilationSupported) {
  SealHandleScope shs(isolate);
100
  DCHECK_EQ(0, args.length());
101 102 103 104 105 106 107
  return isolate->heap()->ToBoolean(
      isolate->concurrent_recompilation_enabled());
}


RUNTIME_FUNCTION(Runtime_OptimizeFunctionOnNextCall) {
  HandleScope scope(isolate);
108 109 110 111 112

  // This function is used by fuzzers, ignore calls with bogus arguments count.
  if (args.length() != 1 && args.length() != 2) {
    return isolate->heap()->undefined_value();
  }
113 114 115 116 117 118 119 120 121

  // This function is used by fuzzers to get coverage for optimizations
  // in compiler. Ignore calls on non-function objects to avoid runtime errors.
  CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
  if (!function_object->IsJSFunction()) {
    return isolate->heap()->undefined_value();
  }
  Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);

122
  // The following condition was lifted from the DCHECK inside
123
  // JSFunction::MarkForOptimization().
124 125 126 127 128
  if (!(function->shared()->allows_lazy_compilation() ||
        (function->code()->kind() == Code::FUNCTION &&
         !function->shared()->optimization_disabled()))) {
    return isolate->heap()->undefined_value();
  }
129

130 131 132 133 134 135
  // If function isn't compiled, compile it now.
  if (!function->shared()->is_compiled() &&
      !Compiler::Compile(function, Compiler::CLEAR_EXCEPTION)) {
    return isolate->heap()->undefined_value();
  }

136
  // If the function is already optimized, just return.
137 138 139 140 141 142 143
  if (function->IsOptimized()) return isolate->heap()->undefined_value();

  function->MarkForOptimization();

  Code* unoptimized = function->shared()->code();
  if (args.length() == 2 && unoptimized->kind() == Code::FUNCTION) {
    CONVERT_ARG_HANDLE_CHECKED(String, type, 1);
144 145
    if (type->IsOneByteEqualTo(STATIC_CHAR_VECTOR("concurrent")) &&
        isolate->concurrent_recompilation_enabled()) {
146
      function->AttemptConcurrentOptimization();
147 148 149 150 151 152
    }
  }

  return isolate->heap()->undefined_value();
}

153 154
RUNTIME_FUNCTION(Runtime_InterpretFunctionOnNextCall) {
  HandleScope scope(isolate);
155
  DCHECK_EQ(1, args.length());
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
  if (!function_object->IsJSFunction()) {
    return isolate->heap()->undefined_value();
  }
  Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);

  // Do not tier down if we are already on optimized code. Replacing optimized
  // code without actual deoptimization can lead to funny bugs.
  if (function->code()->kind() != Code::OPTIMIZED_FUNCTION &&
      function->shared()->HasBytecodeArray()) {
    function->ReplaceCode(*isolate->builtins()->InterpreterEntryTrampoline());
  }
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_BaselineFunctionOnNextCall) {
  HandleScope scope(isolate);
173
  DCHECK_EQ(1, args.length());
174 175 176 177 178 179
  CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
  if (!function_object->IsJSFunction()) {
    return isolate->heap()->undefined_value();
  }
  Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);

180 181 182 183 184 185
  // If function isn't compiled, compile it now.
  if (!function->shared()->is_compiled() &&
      !Compiler::Compile(function, Compiler::CLEAR_EXCEPTION)) {
    return isolate->heap()->undefined_value();
  }

186 187 188 189 190 191 192 193 194 195 196 197 198
  // Do not tier down if we are already on optimized code. Replacing optimized
  // code without actual deoptimization can lead to funny bugs.
  if (function->code()->kind() != Code::OPTIMIZED_FUNCTION &&
      function->code()->kind() != Code::FUNCTION) {
    if (function->shared()->HasBaselineCode()) {
      function->ReplaceCode(function->shared()->code());
    } else {
      function->MarkForBaseline();
    }
  }

  return isolate->heap()->undefined_value();
}
199

200 201
RUNTIME_FUNCTION(Runtime_OptimizeOsr) {
  HandleScope scope(isolate);
202
  DCHECK(args.length() == 0 || args.length() == 1);
203

204
  Handle<JSFunction> function;
205

206 207
  // The optional parameter determines the frame being targeted.
  int stack_depth = args.length() == 1 ? args.smi_at(0) : 0;
208

209 210 211 212 213
  // Find the JavaScript function on the top of the stack.
  JavaScriptFrameIterator it(isolate);
  while (!it.done() && stack_depth--) it.Advance();
  if (!it.done()) function = Handle<JSFunction>(it.frame()->function());
  if (function.is_null()) return isolate->heap()->undefined_value();
214

215 216 217
  // If the function is already optimized, just return.
  if (function->IsOptimized()) return isolate->heap()->undefined_value();

218
  // Make the profiler arm all back edges in unoptimized code.
219 220
  if (it.frame()->type() == StackFrame::JAVA_SCRIPT ||
      it.frame()->type() == StackFrame::INTERPRETED) {
221
    isolate->runtime_profiler()->AttemptOnStackReplacement(
222
        it.frame(), AbstractCode::kMaxLoopNestingMarker);
223 224 225 226 227 228
  }

  return isolate->heap()->undefined_value();
}


229 230
RUNTIME_FUNCTION(Runtime_NeverOptimizeFunction) {
  HandleScope scope(isolate);
231
  DCHECK_EQ(1, args.length());
232
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
233 234
  function->shared()->set_disable_optimization_reason(
      kOptimizationDisabledForTest);
235 236 237 238 239 240 241
  function->shared()->set_optimization_disabled(true);
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_GetOptimizationStatus) {
  HandleScope scope(isolate);
242
  DCHECK(args.length() == 1 || args.length() == 2);
243 244 245
  if (!isolate->use_crankshaft()) {
    return Smi::FromInt(4);  // 4 == "never".
  }
246 247 248 249 250 251 252 253 254

  // This function is used by fuzzers to get coverage for optimizations
  // in compiler. Ignore calls on non-function objects to avoid runtime errors.
  CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
  if (!function_object->IsJSFunction()) {
    return isolate->heap()->undefined_value();
  }
  Handle<JSFunction> function = Handle<JSFunction>::cast(function_object);

255 256
  bool sync_with_compiler_thread = true;
  if (args.length() == 2) {
257 258 259
    CONVERT_ARG_HANDLE_CHECKED(Object, sync_object, 1);
    if (!sync_object->IsString()) return isolate->heap()->undefined_value();
    Handle<String> sync = Handle<String>::cast(sync_object);
260 261 262 263
    if (sync->IsOneByteEqualTo(STATIC_CHAR_VECTOR("no sync"))) {
      sync_with_compiler_thread = false;
    }
  }
264

265 266 267
  if (isolate->concurrent_recompilation_enabled() &&
      sync_with_compiler_thread) {
    while (function->IsInOptimizationQueue()) {
268
      isolate->optimizing_compile_dispatcher()->InstallOptimizedFunctions();
269
      base::OS::Sleep(base::TimeDelta::FromMilliseconds(50));
270 271
    }
  }
272
  if (FLAG_always_opt || FLAG_prepare_always_opt) {
273 274 275
    // With --always-opt, optimization status expectations might not
    // match up, so just return a sentinel.
    return Smi::FromInt(3);  // 3 == "always".
276 277 278 279 280 281 282
  }
  if (FLAG_deopt_every_n_times) {
    return Smi::FromInt(6);  // 6 == "maybe deopted".
  }
  if (function->IsOptimized() && function->code()->is_turbofanned()) {
    return Smi::FromInt(7);  // 7 == "TurboFan compiler".
  }
283 284 285
  if (function->IsInterpreted()) {
    return Smi::FromInt(8);  // 8 == "Interpreted".
  }
286 287 288 289 290 291
  return function->IsOptimized() ? Smi::FromInt(1)   // 1 == "yes".
                                 : Smi::FromInt(2);  // 2 == "no".
}


RUNTIME_FUNCTION(Runtime_UnblockConcurrentRecompilation) {
292
  DCHECK_EQ(0, args.length());
293 294 295 296
  if (FLAG_block_concurrent_recompilation &&
      isolate->concurrent_recompilation_enabled()) {
    isolate->optimizing_compile_dispatcher()->Unblock();
  }
297 298 299 300 301 302
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_GetOptimizationCount) {
  HandleScope scope(isolate);
303
  DCHECK_EQ(1, args.length());
304 305 306 307
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
  return Smi::FromInt(function->shared()->opt_count());
}

308 309 310
static void ReturnThis(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(args.This());
}
311

312 313
RUNTIME_FUNCTION(Runtime_GetUndetectable) {
  HandleScope scope(isolate);
314
  DCHECK_EQ(0, args.length());
315
  v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
316

317 318
  Local<v8::ObjectTemplate> desc = v8::ObjectTemplate::New(v8_isolate);
  desc->MarkAsUndetectable();
319
  desc->SetCallAsFunctionHandler(ReturnThis);
320 321 322 323
  Local<v8::Object> obj;
  if (!desc->NewInstance(v8_isolate->GetCurrentContext()).ToLocal(&obj)) {
    return nullptr;
  }
324 325 326
  return *Utils::OpenHandle(*obj);
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
static void call_as_function(const v8::FunctionCallbackInfo<v8::Value>& args) {
  double v1 = args[0]
                  ->NumberValue(v8::Isolate::GetCurrent()->GetCurrentContext())
                  .ToChecked();
  double v2 = args[1]
                  ->NumberValue(v8::Isolate::GetCurrent()->GetCurrentContext())
                  .ToChecked();
  args.GetReturnValue().Set(
      v8::Number::New(v8::Isolate::GetCurrent(), v1 - v2));
}

// Returns a callable object. The object returns the difference of its two
// parameters when it is called.
RUNTIME_FUNCTION(Runtime_GetCallable) {
  HandleScope scope(isolate);
342
  DCHECK_EQ(0, args.length());
343 344 345 346 347 348 349 350 351 352 353 354
  v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
  Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(v8_isolate);
  Local<ObjectTemplate> instance_template = t->InstanceTemplate();
  instance_template->SetCallAsFunctionHandler(call_as_function);
  v8_isolate->GetCurrentContext();
  Local<v8::Object> instance =
      t->GetFunction(v8_isolate->GetCurrentContext())
          .ToLocalChecked()
          ->NewInstance(v8_isolate->GetCurrentContext())
          .ToLocalChecked();
  return *Utils::OpenHandle(*instance);
}
355

356 357
RUNTIME_FUNCTION(Runtime_ClearFunctionTypeFeedback) {
  HandleScope scope(isolate);
358
  DCHECK_EQ(1, args.length());
359
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
360
  function->ClearTypeFeedbackInfo();
361 362 363 364 365 366 367
  Code* unoptimized = function->shared()->code();
  if (unoptimized->kind() == Code::FUNCTION) {
    unoptimized->ClearInlineCaches();
  }
  return isolate->heap()->undefined_value();
}

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
RUNTIME_FUNCTION(Runtime_CheckWasmWrapperElision) {
  // This only supports the case where the function being exported
  // calls an intermediate function, and the intermediate function
  // calls exactly one imported function
  HandleScope scope(isolate);
  CHECK(args.length() == 2);
  // It takes two parameters, the first one is the JSFunction,
  // The second one is the type
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
  // If type is 0, it means that it is supposed to be a direct call into a WASM
  // function
  // If type is 1, it means that it is supposed to have wrappers
  CONVERT_ARG_HANDLE_CHECKED(Smi, type, 1);
  Handle<Code> export_code = handle(function->code());
  CHECK(export_code->kind() == Code::JS_TO_WASM_FUNCTION);
  int const mask = RelocInfo::ModeMask(RelocInfo::CODE_TARGET);
  // check the type of the $export_fct
  Handle<Code> export_fct;
  int count = 0;
  for (RelocIterator it(*export_code, mask); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
    Address target_address = rinfo->target_address();
    Code* target = Code::GetCodeFromTargetAddress(target_address);
    if (target->kind() == Code::WASM_FUNCTION) {
      ++count;
      export_fct = handle(target);
    }
  }
  CHECK(count == 1);
  // check the type of the intermediate_fct
  Handle<Code> intermediate_fct;
  count = 0;
  for (RelocIterator it(*export_fct, mask); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
    Address target_address = rinfo->target_address();
    Code* target = Code::GetCodeFromTargetAddress(target_address);
    if (target->kind() == Code::WASM_FUNCTION) {
      ++count;
      intermediate_fct = handle(target);
    }
  }
  CHECK(count == 1);
  // check the type of the imported exported function, it should be also a WASM
  // function in our case
  Handle<Code> imported_fct;
413 414 415 416
  CHECK(type->value() == 0 || type->value() == 1);

  Code::Kind target_kind =
      type->value() == 0 ? Code::WASM_FUNCTION : Code::WASM_TO_JS_FUNCTION;
417 418 419 420 421 422 423 424 425 426 427 428 429
  count = 0;
  for (RelocIterator it(*intermediate_fct, mask); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
    Address target_address = rinfo->target_address();
    Code* target = Code::GetCodeFromTargetAddress(target_address);
    if (target->kind() == target_kind) {
      ++count;
      imported_fct = handle(target);
    }
  }
  CHECK_LE(count, 1);
  return isolate->heap()->ToBoolean(count == 1);
}
430 431 432

RUNTIME_FUNCTION(Runtime_NotifyContextDisposed) {
  HandleScope scope(isolate);
433
  DCHECK_EQ(0, args.length());
434
  isolate->heap()->NotifyContextDisposed(true);
435 436 437 438 439 440 441 442
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_SetAllocationTimeout) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 2 || args.length() == 3);
#ifdef DEBUG
443 444
  CONVERT_INT32_ARG_CHECKED(interval, 0);
  CONVERT_INT32_ARG_CHECKED(timeout, 1);
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  isolate->heap()->set_allocation_timeout(timeout);
  FLAG_gc_interval = interval;
  if (args.length() == 3) {
    // Enable/disable inline allocation if requested.
    CONVERT_BOOLEAN_ARG_CHECKED(inline_allocation, 2);
    if (inline_allocation) {
      isolate->heap()->EnableInlineAllocation();
    } else {
      isolate->heap()->DisableInlineAllocation();
    }
  }
#endif
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_DebugPrint) {
  SealHandleScope shs(isolate);
463
  DCHECK_EQ(1, args.length());
464 465 466

  OFStream os(stdout);
#ifdef DEBUG
467
  if (args[0]->IsString() && isolate->context() != nullptr) {
468 469 470 471
    // If we have a string, assume it's a code "marker"
    // and print some interesting cpu debugging info.
    JavaScriptFrameIterator it(isolate);
    JavaScriptFrame* frame = it.frame();
472 473 474
    os << "fp = " << static_cast<void*>(frame->fp())
       << ", sp = " << static_cast<void*>(frame->sp())
       << ", caller_sp = " << static_cast<void*>(frame->caller_sp()) << ": ";
475 476 477 478 479 480 481 482 483 484 485
  } else {
    os << "DebugPrint: ";
  }
  args[0]->Print(os);
  if (args[0]->IsHeapObject()) {
    HeapObject::cast(args[0])->map()->Print(os);
  }
#else
  // ShortPrint is available in release mode. Print is not.
  os << Brief(args[0]);
#endif
486
  os << std::endl;
487 488 489 490 491 492 493

  return args[0];  // return TOS
}


RUNTIME_FUNCTION(Runtime_DebugTrace) {
  SealHandleScope shs(isolate);
494
  DCHECK_EQ(0, args.length());
495 496 497 498 499 500 501 502 503
  isolate->PrintStack(stdout);
  return isolate->heap()->undefined_value();
}


// This will not allocate (flatten the string), but it may run
// very slowly for very deeply nested ConsStrings.  For debugging use only.
RUNTIME_FUNCTION(Runtime_GlobalPrint) {
  SealHandleScope shs(isolate);
504
  DCHECK_EQ(1, args.length());
505 506

  CONVERT_ARG_CHECKED(String, string, 0);
507
  StringCharacterStream stream(string);
508 509 510 511 512 513 514 515 516
  while (stream.HasMore()) {
    uint16_t character = stream.GetNext();
    PrintF("%c", character);
  }
  return string;
}


RUNTIME_FUNCTION(Runtime_SystemBreak) {
517 518 519
  // The code below doesn't create handles, but when breaking here in GDB
  // having a handle scope might be useful.
  HandleScope scope(isolate);
520
  DCHECK_EQ(0, args.length());
521 522 523 524 525 526 527 528
  base::OS::DebugBreak();
  return isolate->heap()->undefined_value();
}


// Sets a v8 flag.
RUNTIME_FUNCTION(Runtime_SetFlags) {
  SealHandleScope shs(isolate);
529
  DCHECK_EQ(1, args.length());
530
  CONVERT_ARG_CHECKED(String, arg, 0);
531
  std::unique_ptr<char[]> flags =
532 533 534 535 536 537 538 539
      arg->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
  FlagList::SetFlagsFromString(flags.get(), StrLength(flags.get()));
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_Abort) {
  SealHandleScope shs(isolate);
540
  DCHECK_EQ(1, args.length());
541 542 543 544 545 546 547 548 549 550 551 552 553
  CONVERT_SMI_ARG_CHECKED(message_id, 0);
  const char* message =
      GetBailoutReason(static_cast<BailoutReason>(message_id));
  base::OS::PrintError("abort: %s\n", message);
  isolate->PrintStack(stderr);
  base::OS::Abort();
  UNREACHABLE();
  return NULL;
}


RUNTIME_FUNCTION(Runtime_AbortJS) {
  HandleScope scope(isolate);
554
  DCHECK_EQ(1, args.length());
555 556 557 558 559 560 561 562 563
  CONVERT_ARG_HANDLE_CHECKED(String, message, 0);
  base::OS::PrintError("abort: %s\n", message->ToCString().get());
  isolate->PrintStack(stderr);
  base::OS::Abort();
  UNREACHABLE();
  return NULL;
}


564
RUNTIME_FUNCTION(Runtime_NativeScriptsCount) {
565
  DCHECK_EQ(0, args.length());
566
  return Smi::FromInt(Natives::GetBuiltinsCount());
567 568
}

569
// TODO(5510): remove this.
570 571
RUNTIME_FUNCTION(Runtime_GetV8Version) {
  HandleScope scope(isolate);
572
  DCHECK_EQ(0, args.length());
573 574 575 576 577 578 579

  const char* version_string = v8::V8::GetVersion();

  return *isolate->factory()->NewStringFromAsciiChecked(version_string);
}


580 581 582
RUNTIME_FUNCTION(Runtime_DisassembleFunction) {
  HandleScope scope(isolate);
#ifdef DEBUG
583
  DCHECK_EQ(1, args.length());
584 585
  // Get the function and make sure it is compiled.
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0);
586
  if (!Compiler::Compile(func, Compiler::KEEP_EXCEPTION)) {
587 588 589 590 591 592 593 594 595
    return isolate->heap()->exception();
  }
  OFStream os(stdout);
  func->code()->Print(os);
  os << std::endl;
#endif  // DEBUG
  return isolate->heap()->undefined_value();
}

596
namespace {
597

598
int StackSize(Isolate* isolate) {
599 600 601 602 603
  int n = 0;
  for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) n++;
  return n;
}

604 605 606 607 608
void PrintIndentation(Isolate* isolate) {
  const int nmax = 80;
  int n = StackSize(isolate);
  if (n <= nmax) {
    PrintF("%4d:%*s", n, n, "");
609
  } else {
610
    PrintF("%4d:%*s", n, nmax, "...");
611 612 613
  }
}

614
}  // namespace
615 616 617

RUNTIME_FUNCTION(Runtime_TraceEnter) {
  SealHandleScope shs(isolate);
618 619 620 621
  DCHECK_EQ(0, args.length());
  PrintIndentation(isolate);
  JavaScriptFrame::PrintTop(isolate, stdout, true, false);
  PrintF(" {\n");
622 623 624 625 626 627
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_TraceExit) {
  SealHandleScope shs(isolate);
628
  DCHECK_EQ(1, args.length());
629
  CONVERT_ARG_CHECKED(Object, obj, 0);
630 631 632 633
  PrintIndentation(isolate);
  PrintF("} -> ");
  obj->ShortPrint();
  PrintF("\n");
634 635 636
  return obj;  // return TOS
}

637 638 639 640 641 642 643
RUNTIME_FUNCTION(Runtime_TraceTailCall) {
  SealHandleScope shs(isolate);
  DCHECK_EQ(0, args.length());
  PrintIndentation(isolate);
  PrintF("} -> tail call ->\n");
  return isolate->heap()->undefined_value();
}
644

645 646
RUNTIME_FUNCTION(Runtime_GetExceptionDetails) {
  HandleScope shs(isolate);
647
  DCHECK_EQ(1, args.length());
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
  CONVERT_ARG_HANDLE_CHECKED(JSObject, exception_obj, 0);

  Factory* factory = isolate->factory();
  Handle<JSMessageObject> message_obj =
      isolate->CreateMessage(exception_obj, nullptr);

  Handle<JSObject> message = factory->NewJSObject(isolate->object_function());

  Handle<String> key;
  Handle<Object> value;

  key = factory->NewStringFromAsciiChecked("start_pos");
  value = handle(Smi::FromInt(message_obj->start_position()), isolate);
  JSObject::SetProperty(message, key, value, STRICT).Assert();

  key = factory->NewStringFromAsciiChecked("end_pos");
  value = handle(Smi::FromInt(message_obj->end_position()), isolate);
  JSObject::SetProperty(message, key, value, STRICT).Assert();

  return *message;
}

670 671
RUNTIME_FUNCTION(Runtime_HaveSameMap) {
  SealHandleScope shs(isolate);
672
  DCHECK_EQ(2, args.length());
673 674 675 676 677 678
  CONVERT_ARG_CHECKED(JSObject, obj1, 0);
  CONVERT_ARG_CHECKED(JSObject, obj2, 1);
  return isolate->heap()->ToBoolean(obj1->map() == obj2->map());
}


ben's avatar
ben committed
679 680
RUNTIME_FUNCTION(Runtime_InNewSpace) {
  SealHandleScope shs(isolate);
681
  DCHECK_EQ(1, args.length());
ben's avatar
ben committed
682 683 684 685
  CONVERT_ARG_CHECKED(Object, obj, 0);
  return isolate->heap()->ToBoolean(isolate->heap()->InNewSpace(obj));
}

686 687 688
RUNTIME_FUNCTION(Runtime_IsAsmWasmCode) {
  SealHandleScope shs(isolate);
  DCHECK_EQ(1, args.length());
689
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
690 691
  if (!function->shared()->HasAsmWasmData()) {
    // Doesn't have wasm data.
692
    return isolate->heap()->false_value();
693 694 695 696
  }
  if (function->shared()->code() !=
      isolate->builtins()->builtin(Builtins::kInstantiateAsmJs)) {
    // Hasn't been compiled yet.
697
    return isolate->heap()->false_value();
698
  }
699
  return isolate->heap()->true_value();
700 701
}

702 703 704 705 706 707 708
RUNTIME_FUNCTION(Runtime_IsWasmCode) {
  SealHandleScope shs(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  bool is_js_to_wasm = function->code()->kind() == Code::JS_TO_WASM_FUNCTION;
  return isolate->heap()->ToBoolean(is_js_to_wasm);
}
ben's avatar
ben committed
709

710 711 712 713 714 715 716 717 718 719 720 721 722
#define ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(Name)       \
  RUNTIME_FUNCTION(Runtime_Has##Name) {                  \
    CONVERT_ARG_CHECKED(JSObject, obj, 0);               \
    return isolate->heap()->ToBoolean(obj->Has##Name()); \
  }

ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastSmiElements)
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastObjectElements)
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastSmiOrObjectElements)
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastDoubleElements)
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastHoleyElements)
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(DictionaryElements)
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(SloppyArgumentsElements)
723
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FixedTypedArrayElements)
724 725 726 727
// Properties test sitting with elements tests - not fooling anyone.
ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastProperties)

#undef ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION
728 729 730 731 732 733 734 735 736 737 738


#define FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, s) \
  RUNTIME_FUNCTION(Runtime_HasFixed##Type##Elements) {                        \
    CONVERT_ARG_CHECKED(JSObject, obj, 0);                                    \
    return isolate->heap()->ToBoolean(obj->HasFixed##Type##Elements());       \
  }

TYPED_ARRAYS(FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION)

#undef FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
739 740 741 742 743 744 745 746


RUNTIME_FUNCTION(Runtime_SpeciesProtector) {
  SealHandleScope shs(isolate);
  DCHECK_EQ(0, args.length());
  return isolate->heap()->ToBoolean(isolate->IsArraySpeciesLookupChainIntact());
}

747 748 749 750
#define CONVERT_ARG_HANDLE_CHECKED_2(Type, name, index) \
  CHECK(Type::Is##Type(args[index]));                   \
  Handle<Type> name = args.at<Type>(index);

751 752 753 754
// Take a compiled wasm module, serialize it and copy the buffer into an array
// buffer, which is then returned.
RUNTIME_FUNCTION(Runtime_SerializeWasmModule) {
  HandleScope shs(isolate);
755
  DCHECK_EQ(1, args.length());
756
  CONVERT_ARG_HANDLE_CHECKED_2(WasmModuleObject, module_obj, 0);
757

758
  Handle<WasmCompiledModule> orig(module_obj->compiled_module());
759 760 761 762 763 764 765 766 767 768 769 770 771
  std::unique_ptr<ScriptData> data =
      WasmCompiledModuleSerializer::SerializeWasmModule(isolate, orig);
  void* buff = isolate->array_buffer_allocator()->Allocate(data->length());
  Handle<JSArrayBuffer> ret = isolate->factory()->NewJSArrayBuffer();
  JSArrayBuffer::Setup(ret, isolate, false, buff, data->length());
  memcpy(buff, data->data(), data->length());
  return *ret;
}

// Take an array buffer and attempt to reconstruct a compiled wasm module.
// Return undefined if unsuccessful.
RUNTIME_FUNCTION(Runtime_DeserializeWasmModule) {
  HandleScope shs(isolate);
772
  DCHECK_EQ(2, args.length());
773
  CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0);
774
  CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, wire_bytes, 1);
775 776 777 778

  Address mem_start = static_cast<Address>(buffer->backing_store());
  int mem_size = static_cast<int>(buffer->byte_length()->Number());

779 780
  // DeserializeWasmModule will allocate. We assume JSArrayBuffer doesn't
  // get relocated.
781
  ScriptData sc(mem_start, mem_size);
782 783 784 785 786
  bool already_external = wire_bytes->is_external();
  if (!already_external) {
    wire_bytes->set_is_external(true);
    isolate->heap()->UnregisterArrayBuffer(*wire_bytes);
  }
787
  MaybeHandle<FixedArray> maybe_compiled_module =
788 789 790 791 792 793 794 795 796
      WasmCompiledModuleSerializer::DeserializeWasmModule(
          isolate, &sc,
          Vector<const uint8_t>(
              reinterpret_cast<uint8_t*>(wire_bytes->backing_store()),
              static_cast<int>(wire_bytes->byte_length()->Number())));
  if (!already_external) {
    wire_bytes->set_is_external(false);
    isolate->heap()->RegisterNewArrayBuffer(*wire_bytes);
  }
797 798 799 800
  Handle<FixedArray> compiled_module;
  if (!maybe_compiled_module.ToHandle(&compiled_module)) {
    return isolate->heap()->undefined_value();
  }
801 802
  return *WasmModuleObject::New(
      isolate, Handle<WasmCompiledModule>::cast(compiled_module));
803
}
804

805 806
RUNTIME_FUNCTION(Runtime_ValidateWasmInstancesChain) {
  HandleScope shs(isolate);
807
  DCHECK_EQ(2, args.length());
808
  CONVERT_ARG_HANDLE_CHECKED_2(WasmModuleObject, module_obj, 0);
809 810 811 812 813 814 815 816
  CONVERT_ARG_HANDLE_CHECKED(Smi, instance_count, 1);
  wasm::testing::ValidateInstancesChain(isolate, module_obj,
                                        instance_count->value());
  return isolate->heap()->ToBoolean(true);
}

RUNTIME_FUNCTION(Runtime_ValidateWasmModuleState) {
  HandleScope shs(isolate);
817
  DCHECK_EQ(1, args.length());
818
  CONVERT_ARG_HANDLE_CHECKED_2(WasmModuleObject, module_obj, 0);
819 820 821 822 823 824
  wasm::testing::ValidateModuleState(isolate, module_obj);
  return isolate->heap()->ToBoolean(true);
}

RUNTIME_FUNCTION(Runtime_ValidateWasmOrphanedInstance) {
  HandleScope shs(isolate);
825
  DCHECK_EQ(1, args.length());
826 827
  CONVERT_ARG_HANDLE_CHECKED_2(WasmInstanceObject, instance, 0);
  wasm::testing::ValidateOrphanedInstance(isolate, instance);
828 829 830
  return isolate->heap()->ToBoolean(true);
}

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
RUNTIME_FUNCTION(Runtime_Verify) {
  HandleScope shs(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
#ifdef VERIFY_HEAP
  object->ObjectVerify();
#else
  CHECK(object->IsObject());
  if (object->IsHeapObject()) {
    CHECK(HeapObject::cast(*object)->map()->IsMap());
  } else {
    CHECK(object->IsSmi());
  }
#endif
  return isolate->heap()->ToBoolean(true);
}

848 849
}  // namespace internal
}  // namespace v8