wasm-module.cc 46.8 KB
Newer Older
1 2 3 4
// Copyright 2015 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 <functional>
6 7
#include <memory>

8
#include "src/code-stubs.h"
9
#include "src/debug/interface-types.h"
10
#include "src/frames-inl.h"
11
#include "src/objects.h"
12
#include "src/property-descriptor.h"
13
#include "src/simulator.h"
14 15
#include "src/snapshot/snapshot.h"
#include "src/v8.h"
16

17
#include "src/wasm/compilation-manager.h"
18
#include "src/wasm/module-compiler.h"
19
#include "src/wasm/module-decoder.h"
20
#include "src/wasm/wasm-code-specialization.h"
21
#include "src/wasm/wasm-js.h"
22
#include "src/wasm/wasm-limits.h"
23
#include "src/wasm/wasm-module.h"
24
#include "src/wasm/wasm-objects.h"
25 26
#include "src/wasm/wasm-result.h"

27 28 29 30 31 32
#if __clang__
// TODO(mostynb@opera.com): remove the using statements and these pragmas.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wheader-hygiene"
#endif

33 34 35
using namespace v8::internal;
using namespace v8::internal::wasm;
namespace base = v8::base;
36

37 38 39 40 41
#if __clang__
// TODO(mostynb@opera.com): remove the using statements and these pragmas.
#pragma clang diagnostic pop
#endif

42 43 44 45 46 47 48 49 50 51
#define TRACE(...)                                      \
  do {                                                  \
    if (FLAG_trace_wasm_instances) PrintF(__VA_ARGS__); \
  } while (false)

#define TRACE_CHAIN(instance)        \
  do {                               \
    instance->PrintInstancesChain(); \
  } while (false)

52 53 54 55 56
#define TRACE_COMPILE(...)                             \
  do {                                                 \
    if (FLAG_trace_wasm_compiler) PrintF(__VA_ARGS__); \
  } while (false)

57 58
namespace {

59

60
void* TryAllocateBackingStore(Isolate* isolate, size_t size,
61 62
                              bool enable_guard_regions, void*& allocation_base,
                              size_t& allocation_length) {
63 64 65 66 67 68 69 70 71 72
  // TODO(eholk): Right now enable_guard_regions has no effect on 32-bit
  // systems. It may be safer to fail instead, given that other code might do
  // things that would be unsafe if they expected guard pages where there
  // weren't any.
  if (enable_guard_regions && kGuardRegionsSupported) {
    // TODO(eholk): On Windows we want to make sure we don't commit the guard
    // pages yet.

    // We always allocate the largest possible offset into the heap, so the
    // addressable memory after the guard page can be made inaccessible.
73
    allocation_length = RoundUp(kWasmMaxHeapOffset, base::OS::CommitPageSize());
74
    DCHECK_EQ(0, size % base::OS::CommitPageSize());
75 76

    // AllocateGuarded makes the whole region inaccessible by default.
77 78 79
    allocation_base =
        isolate->array_buffer_allocator()->Reserve(allocation_length);
    if (allocation_base == nullptr) {
80 81 82
      return nullptr;
    }

83 84
    void* memory = allocation_base;

85
    // Make the part we care about accessible.
86 87
    isolate->array_buffer_allocator()->SetProtection(
        memory, size, v8::ArrayBuffer::Allocator::Protection::kReadWrite);
88 89 90 91 92 93

    reinterpret_cast<v8::Isolate*>(isolate)
        ->AdjustAmountOfExternalAllocatedMemory(size);

    return memory;
  } else {
94 95
    void* memory =
        size == 0 ? nullptr : isolate->array_buffer_allocator()->Allocate(size);
96 97
    allocation_base = memory;
    allocation_length = size;
98 99
    return memory;
  }
100
}
101

102
static void InstanceFinalizer(const v8::WeakCallbackInfo<void>& data) {
103
  DisallowHeapAllocation no_gc;
104
  JSObject** p = reinterpret_cast<JSObject**>(data.GetParameter());
105
  WasmInstanceObject* owner = reinterpret_cast<WasmInstanceObject*>(*p);
106
  Isolate* isolate = reinterpret_cast<Isolate*>(data.GetIsolate());
107
  // If a link to shared memory instances exists, update the list of memory
108
  // instances before the instance is destroyed.
109
  WasmCompiledModule* compiled_module = owner->compiled_module();
110
  TRACE("Finalizing %d {\n", compiled_module->instance_id());
111 112
  DCHECK(compiled_module->has_weak_wasm_module());
  WeakCell* weak_wasm_module = compiled_module->ptr_to_weak_wasm_module();
113

eholk's avatar
eholk committed
114 115 116 117 118 119 120 121 122 123 124 125
  if (trap_handler::UseTrapHandler()) {
    Handle<FixedArray> code_table = compiled_module->code_table();
    for (int i = 0; i < code_table->length(); ++i) {
      Handle<Code> code = code_table->GetValueChecked<Code>(isolate, i);
      int index = code->trap_handler_index()->value();
      if (index >= 0) {
        trap_handler::ReleaseHandlerData(index);
        code->set_trap_handler_index(Smi::FromInt(-1));
      }
    }
  }

126 127 128 129 130 131 132 133 134 135 136 137
  // Since the order of finalizers is not guaranteed, it can be the case
  // that {instance->compiled_module()->module()}, which is a
  // {Managed<WasmModule>} has been collected earlier in this GC cycle.
  // Weak references to this instance won't be cleared until
  // the next GC cycle, so we need to manually break some links (such as
  // the weak references from {WasmMemoryObject::instances}.
  if (owner->has_memory_object()) {
    Handle<WasmMemoryObject> memory(owner->memory_object(), isolate);
    Handle<WasmInstanceObject> instance(owner, isolate);
    WasmMemoryObject::RemoveInstance(isolate, memory, instance);
  }

138
  // weak_wasm_module may have been cleared, meaning the module object
139 140
  // was GC-ed. In that case, there won't be any new instances created,
  // and we don't need to maintain the links between instances.
141
  if (!weak_wasm_module->cleared()) {
142 143 144
    WasmModuleObject* wasm_module =
        WasmModuleObject::cast(weak_wasm_module->value());
    WasmCompiledModule* current_template = wasm_module->compiled_module();
145 146 147 148 149

    TRACE("chain before {\n");
    TRACE_CHAIN(current_template);
    TRACE("}\n");

150
    DCHECK(!current_template->has_weak_prev_instance());
151 152
    WeakCell* next = compiled_module->maybe_ptr_to_weak_next_instance();
    WeakCell* prev = compiled_module->maybe_ptr_to_weak_prev_instance();
153 154 155

    if (current_template == compiled_module) {
      if (next == nullptr) {
156
        WasmCompiledModule::Reset(isolate, compiled_module);
157
      } else {
158 159 160 161
        WasmCompiledModule* next_compiled_module =
            WasmCompiledModule::cast(next->value());
        WasmModuleObject::cast(wasm_module)
            ->set_compiled_module(next_compiled_module);
162
        DCHECK_NULL(prev);
163
        next_compiled_module->reset_weak_prev_instance();
164 165 166 167 168 169 170 171
      }
    } else {
      DCHECK(!(prev == nullptr && next == nullptr));
      // the only reason prev or next would be cleared is if the
      // respective objects got collected, but if that happened,
      // we would have relinked the list.
      if (prev != nullptr) {
        DCHECK(!prev->cleared());
172 173 174 175 176 177
        if (next == nullptr) {
          WasmCompiledModule::cast(prev->value())->reset_weak_next_instance();
        } else {
          WasmCompiledModule::cast(prev->value())
              ->set_ptr_to_weak_next_instance(next);
        }
178 179 180
      }
      if (next != nullptr) {
        DCHECK(!next->cleared());
181 182 183 184 185 186
        if (prev == nullptr) {
          WasmCompiledModule::cast(next->value())->reset_weak_prev_instance();
        } else {
          WasmCompiledModule::cast(next->value())
              ->set_ptr_to_weak_prev_instance(prev);
        }
187 188
      }
    }
189
    TRACE("chain after {\n");
190
    TRACE_CHAIN(wasm_module->compiled_module());
191
    TRACE("}\n");
192
  }
193
  compiled_module->reset_weak_owning_instance();
194
  GlobalHandles::Destroy(reinterpret_cast<Object**>(p));
195
  TRACE("}\n");
196 197
}

198 199 200 201 202 203 204 205 206 207 208
int AdvanceSourcePositionTableIterator(SourcePositionTableIterator& iterator,
                                       int offset) {
  DCHECK(!iterator.done());
  int byte_pos;
  do {
    byte_pos = iterator.source_position().ScriptOffset();
    iterator.Advance();
  } while (!iterator.done() && iterator.code_offset() <= offset);
  return byte_pos;
}

209 210 211 212
void RecordLazyCodeStats(Code* code, Counters* counters) {
  counters->wasm_lazily_compiled_functions()->Increment();
  counters->wasm_generated_code_size()->Increment(code->body_size());
  counters->wasm_reloc_size()->Increment(code->relocation_info()->length());
213 214
}

215 216 217 218 219 220 221 222 223
ModuleEnv CreateModuleEnvFromRuntimeObject(
    Isolate* isolate, Handle<WasmCompiledModule> compiled_module) {
  DisallowHeapAllocation no_gc;
  // Store a vector of handles to be embedded in the generated code.
  // TODO(clemensh): For concurrent compilation, these will have to live in a
  // DeferredHandleScope.
  wasm::ModuleEnv module_env(compiled_module->module(),
                             BUILTIN_CODE(isolate, WasmCompileLazy));

224 225 226 227 228 229 230 231 232 233 234 235 236
  // We set unchecked because the data on the compiled module
  // is authoritative.
  module_env.SetMemSizeUnchecked(compiled_module->has_embedded_mem_size()
                                     ? compiled_module->embedded_mem_size()
                                     : 0);
  module_env.set_mem_start(
      reinterpret_cast<byte*>(compiled_module->has_embedded_mem_start()
                                  ? compiled_module->embedded_mem_start()
                                  : 0));
  module_env.set_globals_start(reinterpret_cast<byte*>(
      compiled_module->has_globals_start() ? compiled_module->globals_start()
                                           : 0));

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  DCHECK_EQ(compiled_module->has_function_tables(),
            compiled_module->has_signature_tables());

  if (compiled_module->has_function_tables()) {
    // TODO(clemensh): For concurrent compilation, these will have to live in a
    // DeferredHandleScope.
    FixedArray* function_tables = compiled_module->ptr_to_function_tables();
    FixedArray* signature_tables = compiled_module->ptr_to_signature_tables();
    DCHECK_EQ(function_tables->length(), signature_tables->length());
    DCHECK_EQ(function_tables->length(), module_env.function_tables().size());
    for (uint32_t i = 0, e = static_cast<uint32_t>(
                             module_env.function_tables().size());
         i < e; ++i) {
      int index = static_cast<int>(i);
      module_env.SetFunctionTable(
          i, handle(FixedArray::cast(function_tables->get(index))),
          handle(FixedArray::cast(signature_tables->get(index))));
    }
  }
  return module_env;
}

259 260
}  // namespace

261 262 263
// static
const WasmExceptionSig wasm::WasmException::empty_sig_(0, 0, nullptr);

264 265 266 267 268
Handle<JSArrayBuffer> wasm::SetupArrayBuffer(
    Isolate* isolate, void* allocation_base, size_t allocation_length,
    void* backing_store, size_t size, bool is_external,
    bool enable_guard_regions, SharedFlag shared) {
  Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer(shared);
269
  DCHECK_GE(kMaxInt, size);
270
  if (shared == SharedFlag::kShared) DCHECK(FLAG_experimental_wasm_threads);
271
  JSArrayBuffer::Setup(buffer, isolate, is_external, allocation_base,
272 273
                       allocation_length, backing_store, static_cast<int>(size),
                       shared);
274
  buffer->set_is_neuterable(false);
275
  buffer->set_is_wasm_buffer(true);
276 277 278 279
  buffer->set_has_guard_region(enable_guard_regions);
  return buffer;
}

280
Handle<JSArrayBuffer> wasm::NewArrayBuffer(Isolate* isolate, size_t size,
281 282
                                           bool enable_guard_regions,
                                           SharedFlag shared) {
283 284 285 286 287
  // Check against kMaxInt, since the byte length is stored as int in the
  // JSArrayBuffer. Note that wasm_max_mem_pages can be raised from the command
  // line, and we don't want to fail a CHECK then.
  if (size > FLAG_wasm_max_mem_pages * WasmModule::kPageSize ||
      size > kMaxInt) {
288 289 290 291 292 293
    // TODO(titzer): lift restriction on maximum memory allocated here.
    return Handle<JSArrayBuffer>::null();
  }

  enable_guard_regions = enable_guard_regions && kGuardRegionsSupported;

294 295
  void* allocation_base = nullptr;  // Set by TryAllocateBackingStore
  size_t allocation_length = 0;     // Set by TryAllocateBackingStore
296 297 298 299 300
  // Do not reserve memory till non zero memory is encountered.
  void* memory =
      (size == 0) ? nullptr
                  : TryAllocateBackingStore(isolate, size, enable_guard_regions,
                                            allocation_base, allocation_length);
301

302
  if (size > 0 && memory == nullptr) {
303 304 305 306 307 308 309 310 311 312 313
    return Handle<JSArrayBuffer>::null();
  }

#if DEBUG
  // Double check the API allocator actually zero-initialized the memory.
  const byte* bytes = reinterpret_cast<const byte*>(memory);
  for (size_t i = 0; i < size; ++i) {
    DCHECK_EQ(0, bytes[i]);
  }
#endif

314
  constexpr bool is_external = false;
315
  return SetupArrayBuffer(isolate, allocation_base, allocation_length, memory,
316
                          size, is_external, enable_guard_regions, shared);
317 318
}

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
void wasm::UnpackAndRegisterProtectedInstructions(
    Isolate* isolate, Handle<FixedArray> code_table) {
  for (int i = 0; i < code_table->length(); ++i) {
    Handle<Code> code;
    // This is sometimes undefined when we're called from cctests.
    if (!code_table->GetValue<Code>(isolate, i).ToHandle(&code)) {
      continue;
    }

    if (code->kind() != Code::WASM_FUNCTION) {
      continue;
    }

    const intptr_t base = reinterpret_cast<intptr_t>(code->entry());

    Zone zone(isolate->allocator(), "Wasm Module");
    ZoneVector<trap_handler::ProtectedInstructionData> unpacked(&zone);
    const int mode_mask =
        RelocInfo::ModeMask(RelocInfo::WASM_PROTECTED_INSTRUCTION_LANDING);
    for (RelocIterator it(*code, mode_mask); !it.done(); it.next()) {
      trap_handler::ProtectedInstructionData data;
      data.instr_offset = it.rinfo()->data();
      data.landing_offset = reinterpret_cast<intptr_t>(it.rinfo()->pc()) - base;
      unpacked.emplace_back(data);
    }
    if (unpacked.size() > 0) {
      int size = code->CodeSize();
      const int index = RegisterHandlerData(reinterpret_cast<void*>(base), size,
                                            unpacked.size(), &unpacked[0]);
      // TODO(eholk): if index is negative, fail.
      DCHECK(index >= 0);
      code->set_trap_handler_index(Smi::FromInt(index));
    }
  }
}

355 356
std::ostream& wasm::operator<<(std::ostream& os, const WasmFunctionName& name) {
  os << "#" << name.function_->func_index;
357
  if (name.function_->name.is_set()) {
358 359 360
    if (name.name_.start()) {
      os << ":";
      os.write(name.name_.start(), name.name_.length());
361 362 363 364 365 366 367
    }
  } else {
    os << "?";
  }
  return os;
}

368
WasmInstanceObject* wasm::GetOwningWasmInstance(Code* code) {
369
  DisallowHeapAllocation no_gc;
370 371
  DCHECK(code->kind() == Code::WASM_FUNCTION ||
         code->kind() == Code::WASM_INTERPRETER_ENTRY);
372
  FixedArray* deopt_data = code->deoptimization_data();
373 374
  DCHECK_EQ(code->kind() == Code::WASM_INTERPRETER_ENTRY ? 1 : 2,
            deopt_data->length());
375
  Object* weak_link = deopt_data->get(0);
376
  DCHECK(weak_link->IsWeakCell());
377
  WeakCell* cell = WeakCell::cast(weak_link);
378
  if (cell->cleared()) return nullptr;
379
  return WasmInstanceObject::cast(cell->value());
380 381
}

382
WasmModule::WasmModule(std::unique_ptr<Zone> owned)
383
    : signature_zone(std::move(owned)) {}
384

385 386
WasmFunction* wasm::GetWasmFunctionForImportWrapper(Isolate* isolate,
                                                    Handle<Object> target) {
387 388
  if (target->IsJSFunction()) {
    Handle<JSFunction> func = Handle<JSFunction>::cast(target);
389 390 391 392 393
    if (func->code()->kind() == Code::JS_TO_WASM_FUNCTION) {
      auto exported = Handle<WasmExportedFunction>::cast(func);
      Handle<WasmInstanceObject> other_instance(exported->instance(), isolate);
      int func_index = exported->function_index();
      return &other_instance->module()->functions[func_index];
394 395 396 397 398
    }
  }
  return nullptr;
}

399
Handle<Code> wasm::UnwrapImportWrapper(Handle<Object> import_wrapper) {
400
  Handle<JSFunction> func = Handle<JSFunction>::cast(import_wrapper);
401 402
  Handle<Code> export_wrapper_code = handle(func->code());
  int mask = RelocInfo::ModeMask(RelocInfo::CODE_TARGET);
403 404 405 406
  for (RelocIterator it(*export_wrapper_code, mask);; it.next()) {
    DCHECK(!it.done());
    Code* target = Code::GetCodeFromTargetAddress(it.rinfo()->target_address());
    if (target->kind() != Code::WASM_FUNCTION &&
407 408
        target->kind() != Code::WASM_TO_JS_FUNCTION &&
        target->kind() != Code::WASM_INTERPRETER_ENTRY)
409 410 411 412 413 414
      continue;
// There should only be this one call to wasm code.
#ifdef DEBUG
    for (it.next(); !it.done(); it.next()) {
      Code* code = Code::GetCodeFromTargetAddress(it.rinfo()->target_address());
      DCHECK(code->kind() != Code::WASM_FUNCTION &&
415 416
             code->kind() != Code::WASM_TO_JS_FUNCTION &&
             code->kind() != Code::WASM_INTERPRETER_ENTRY);
417
    }
418 419
#endif
    return handle(target);
420
  }
421
  UNREACHABLE();
422 423
}

424 425 426
void wasm::UpdateDispatchTables(Isolate* isolate,
                                Handle<FixedArray> dispatch_tables, int index,
                                WasmFunction* function, Handle<Code> code) {
427 428
  DCHECK_EQ(0, dispatch_tables->length() % 4);
  for (int i = 0; i < dispatch_tables->length(); i += 4) {
jgruber's avatar
jgruber committed
429
    int table_index = Smi::ToInt(dispatch_tables->get(i + 1));
430
    Handle<FixedArray> function_table(
431
        FixedArray::cast(dispatch_tables->get(i + 2)), isolate);
432 433
    Handle<FixedArray> signature_table(
        FixedArray::cast(dispatch_tables->get(i + 3)), isolate);
434 435 436
    if (function) {
      // TODO(titzer): the signature might need to be copied to avoid
      // a dangling pointer in the signature map.
437 438
      Handle<WasmInstanceObject> instance(
          WasmInstanceObject::cast(dispatch_tables->get(i)), isolate);
439
      auto& func_table = instance->module()->function_tables[table_index];
440 441
      uint32_t sig_index = func_table.map.FindOrInsert(function->sig);
      signature_table->set(index, Smi::FromInt(static_cast<int>(sig_index)));
442
      function_table->set(index, *code);
443
    } else {
444
      signature_table->set(index, Smi::FromInt(-1));
445
      function_table->set(index, Smi::kZero);
446 447 448 449
    }
  }
}

450

451
void wasm::TableSet(ErrorThrower* thrower, Isolate* isolate,
452
                    Handle<WasmTableObject> table, int64_t index,
453 454 455 456 457 458 459
                    Handle<JSFunction> function) {
  Handle<FixedArray> array(table->functions(), isolate);

  if (index < 0 || index >= array->length()) {
    thrower->RangeError("index out of bounds");
    return;
  }
460
  int index32 = static_cast<int>(index);
461 462 463 464 465 466 467 468 469 470 471

  Handle<FixedArray> dispatch_tables(table->dispatch_tables(), isolate);

  WasmFunction* wasm_function = nullptr;
  Handle<Code> code = Handle<Code>::null();
  Handle<Object> value = handle(isolate->heap()->null_value());

  if (!function.is_null()) {
    wasm_function = GetWasmFunctionForImportWrapper(isolate, function);
    code = UnwrapImportWrapper(function);
    value = Handle<Object>::cast(function);
472
  }
473

474 475
  UpdateDispatchTables(isolate, dispatch_tables, index32, wasm_function, code);
  array->set(index32, *value);
476 477
}

478
Handle<Script> wasm::GetScript(Handle<JSObject> instance) {
479
  WasmCompiledModule* compiled_module =
480 481
      WasmInstanceObject::cast(*instance)->compiled_module();
  return handle(compiled_module->script());
482 483
}

484
bool wasm::IsWasmCodegenAllowed(Isolate* isolate, Handle<Context> context) {
485 486 487 488
  // TODO(wasm): Once wasm has its own CSP policy, we should introduce a
  // separate callback that includes information about the module about to be
  // compiled. For the time being, pass an empty string as placeholder for the
  // sources.
489
  return isolate->allow_code_gen_callback() == nullptr ||
490 491 492
         isolate->allow_code_gen_callback()(
             v8::Utils::ToLocal(context),
             v8::Utils::ToLocal(isolate->factory()->empty_string()));
493 494
}

495
void wasm::DetachWebAssemblyMemoryBuffer(Isolate* isolate,
496 497
                                         Handle<JSArrayBuffer> buffer,
                                         bool free_memory) {
498
  const bool is_external = buffer->is_external();
499
  DCHECK(!buffer->is_neuterable());
500
  if (!is_external) {
501 502
    buffer->set_is_external(true);
    isolate->heap()->UnregisterArrayBuffer(*buffer);
503 504 505 506 507 508 509 510
    if (free_memory) {
      // We need to free the memory before neutering the buffer because
      // FreeBackingStore reads buffer->allocation_base(), which is nulled out
      // by Neuter. This means there is a dangling pointer until we neuter the
      // buffer. Since there is no way for the user to directly call
      // FreeBackingStore, we can ensure this is safe.
      buffer->FreeBackingStore();
    }
511
  }
512 513
  buffer->set_is_neuterable(true);
  buffer->Neuter();
514 515
}

516
void testing::ValidateInstancesChain(Isolate* isolate,
517
                                     Handle<WasmModuleObject> module_obj,
518
                                     int instance_count) {
519 520
  CHECK_GE(instance_count, 0);
  DisallowHeapAllocation no_gc;
521
  WasmCompiledModule* compiled_module = module_obj->compiled_module();
522
  CHECK_EQ(JSObject::cast(compiled_module->ptr_to_weak_wasm_module()->value()),
523
           *module_obj);
524
  Object* prev = nullptr;
525 526 527 528 529
  int found_instances = compiled_module->has_weak_owning_instance() ? 1 : 0;
  WasmCompiledModule* current_instance = compiled_module;
  while (current_instance->has_weak_next_instance()) {
    CHECK((prev == nullptr && !current_instance->has_weak_prev_instance()) ||
          current_instance->ptr_to_weak_prev_instance()->value() == prev);
530
    CHECK_EQ(current_instance->ptr_to_weak_wasm_module()->value(), *module_obj);
531 532 533
    CHECK(current_instance->ptr_to_weak_owning_instance()
              ->value()
              ->IsWasmInstanceObject());
534
    prev = current_instance;
535 536
    current_instance = WasmCompiledModule::cast(
        current_instance->ptr_to_weak_next_instance()->value());
537 538 539 540 541 542
    ++found_instances;
    CHECK_LE(found_instances, instance_count);
  }
  CHECK_EQ(found_instances, instance_count);
}

543
void testing::ValidateModuleState(Isolate* isolate,
544
                                  Handle<WasmModuleObject> module_obj) {
545
  DisallowHeapAllocation no_gc;
546
  WasmCompiledModule* compiled_module = module_obj->compiled_module();
547
  CHECK(compiled_module->has_weak_wasm_module());
548
  CHECK_EQ(compiled_module->ptr_to_weak_wasm_module()->value(), *module_obj);
549 550 551
  CHECK(!compiled_module->has_weak_prev_instance());
  CHECK(!compiled_module->has_weak_next_instance());
  CHECK(!compiled_module->has_weak_owning_instance());
552 553
}

554
void testing::ValidateOrphanedInstance(Isolate* isolate,
555
                                       Handle<WasmInstanceObject> instance) {
556
  DisallowHeapAllocation no_gc;
557
  WasmCompiledModule* compiled_module = instance->compiled_module();
558 559 560
  CHECK(compiled_module->has_weak_wasm_module());
  CHECK(compiled_module->ptr_to_weak_wasm_module()->cleared());
}
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

Handle<JSArray> wasm::GetImports(Isolate* isolate,
                                 Handle<WasmModuleObject> module_object) {
  Handle<WasmCompiledModule> compiled_module(module_object->compiled_module(),
                                             isolate);
  Factory* factory = isolate->factory();

  Handle<String> module_string = factory->InternalizeUtf8String("module");
  Handle<String> name_string = factory->InternalizeUtf8String("name");
  Handle<String> kind_string = factory->InternalizeUtf8String("kind");

  Handle<String> function_string = factory->InternalizeUtf8String("function");
  Handle<String> table_string = factory->InternalizeUtf8String("table");
  Handle<String> memory_string = factory->InternalizeUtf8String("memory");
  Handle<String> global_string = factory->InternalizeUtf8String("global");

  // Create the result array.
  WasmModule* module = compiled_module->module();
  int num_imports = static_cast<int>(module->import_table.size());
580
  Handle<JSArray> array_object = factory->NewJSArray(PACKED_ELEMENTS, 0, 0);
581 582 583 584 585 586 587 588 589 590 591
  Handle<FixedArray> storage = factory->NewFixedArray(num_imports);
  JSArray::SetContent(array_object, storage);
  array_object->set_length(Smi::FromInt(num_imports));

  Handle<JSFunction> object_function =
      Handle<JSFunction>(isolate->native_context()->object_function(), isolate);

  // Populate the result array.
  for (int index = 0; index < num_imports; ++index) {
    WasmImport& import = module->import_table[index];

592
    Handle<JSObject> entry = factory->NewJSObject(object_function);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

    Handle<String> import_kind;
    switch (import.kind) {
      case kExternalFunction:
        import_kind = function_string;
        break;
      case kExternalTable:
        import_kind = table_string;
        break;
      case kExternalMemory:
        import_kind = memory_string;
        break;
      case kExternalGlobal:
        import_kind = global_string;
        break;
      default:
        UNREACHABLE();
    }

    MaybeHandle<String> import_module =
        WasmCompiledModule::ExtractUtf8StringFromModuleBytes(
614
            isolate, compiled_module, import.module_name);
615 616 617

    MaybeHandle<String> import_name =
        WasmCompiledModule::ExtractUtf8StringFromModuleBytes(
618
            isolate, compiled_module, import.field_name);
619 620 621 622 623 624 625 626 627 628 629 630

    JSObject::AddProperty(entry, module_string, import_module.ToHandleChecked(),
                          NONE);
    JSObject::AddProperty(entry, name_string, import_name.ToHandleChecked(),
                          NONE);
    JSObject::AddProperty(entry, kind_string, import_kind, NONE);

    storage->set(index, *entry);
  }

  return array_object;
}
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

Handle<JSArray> wasm::GetExports(Isolate* isolate,
                                 Handle<WasmModuleObject> module_object) {
  Handle<WasmCompiledModule> compiled_module(module_object->compiled_module(),
                                             isolate);
  Factory* factory = isolate->factory();

  Handle<String> name_string = factory->InternalizeUtf8String("name");
  Handle<String> kind_string = factory->InternalizeUtf8String("kind");

  Handle<String> function_string = factory->InternalizeUtf8String("function");
  Handle<String> table_string = factory->InternalizeUtf8String("table");
  Handle<String> memory_string = factory->InternalizeUtf8String("memory");
  Handle<String> global_string = factory->InternalizeUtf8String("global");

  // Create the result array.
  WasmModule* module = compiled_module->module();
  int num_exports = static_cast<int>(module->export_table.size());
649
  Handle<JSArray> array_object = factory->NewJSArray(PACKED_ELEMENTS, 0, 0);
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
  Handle<FixedArray> storage = factory->NewFixedArray(num_exports);
  JSArray::SetContent(array_object, storage);
  array_object->set_length(Smi::FromInt(num_exports));

  Handle<JSFunction> object_function =
      Handle<JSFunction>(isolate->native_context()->object_function(), isolate);

  // Populate the result array.
  for (int index = 0; index < num_exports; ++index) {
    WasmExport& exp = module->export_table[index];

    Handle<String> export_kind;
    switch (exp.kind) {
      case kExternalFunction:
        export_kind = function_string;
        break;
      case kExternalTable:
        export_kind = table_string;
        break;
      case kExternalMemory:
        export_kind = memory_string;
        break;
      case kExternalGlobal:
        export_kind = global_string;
        break;
      default:
        UNREACHABLE();
    }

679 680
    Handle<JSObject> entry = factory->NewJSObject(object_function);

681 682
    MaybeHandle<String> export_name =
        WasmCompiledModule::ExtractUtf8StringFromModuleBytes(
683
            isolate, compiled_module, exp.name);
684 685 686 687 688 689 690 691 692 693

    JSObject::AddProperty(entry, name_string, export_name.ToHandleChecked(),
                          NONE);
    JSObject::AddProperty(entry, kind_string, export_kind, NONE);

    storage->set(index, *entry);
  }

  return array_object;
}
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716

Handle<JSArray> wasm::GetCustomSections(Isolate* isolate,
                                        Handle<WasmModuleObject> module_object,
                                        Handle<String> name,
                                        ErrorThrower* thrower) {
  Handle<WasmCompiledModule> compiled_module(module_object->compiled_module(),
                                             isolate);
  Factory* factory = isolate->factory();

  std::vector<CustomSectionOffset> custom_sections;
  {
    DisallowHeapAllocation no_gc;  // for raw access to string bytes.
    Handle<SeqOneByteString> module_bytes(compiled_module->module_bytes(),
                                          isolate);
    const byte* start =
        reinterpret_cast<const byte*>(module_bytes->GetCharsAddress());
    const byte* end = start + module_bytes->length();
    custom_sections = DecodeCustomSections(start, end);
  }

  std::vector<Handle<Object>> matching_sections;

  // Gather matching sections.
717
  for (auto& section : custom_sections) {
718 719
    MaybeHandle<String> section_name =
        WasmCompiledModule::ExtractUtf8StringFromModuleBytes(
720
            isolate, compiled_module, section.name);
721 722 723 724

    if (!name->Equals(*section_name.ToHandleChecked())) continue;

    // Make a copy of the payload data in the section.
725 726 727 728 729
    size_t size = section.payload.length();
    void* memory =
        size == 0 ? nullptr : isolate->array_buffer_allocator()->Allocate(size);

    if (size && !memory) {
730 731 732
      thrower->RangeError("out of memory allocating custom section data");
      return Handle<JSArray>();
    }
733 734 735 736 737 738 739 740 741 742
    Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer();
    constexpr bool is_external = false;
    JSArrayBuffer::Setup(buffer, isolate, is_external, memory, size, memory,
                         size);
    DisallowHeapAllocation no_gc;  // for raw access to string bytes.
    Handle<SeqOneByteString> module_bytes(compiled_module->module_bytes(),
                                          isolate);
    const byte* start =
        reinterpret_cast<const byte*>(module_bytes->GetCharsAddress());
    memcpy(memory, start + section.payload.offset(), section.payload.length());
743

744
    matching_sections.push_back(buffer);
745 746 747
  }

  int num_custom_sections = static_cast<int>(matching_sections.size());
748
  Handle<JSArray> array_object = factory->NewJSArray(PACKED_ELEMENTS, 0, 0);
749 750 751 752 753 754 755 756 757 758
  Handle<FixedArray> storage = factory->NewFixedArray(num_custom_sections);
  JSArray::SetContent(array_object, storage);
  array_object->set_length(Smi::FromInt(num_custom_sections));

  for (int i = 0; i < num_custom_sections; i++) {
    storage->set(i, *matching_sections[i]);
  }

  return array_object;
}
759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
Handle<FixedArray> wasm::DecodeLocalNames(
    Isolate* isolate, Handle<WasmCompiledModule> compiled_module) {
  Handle<SeqOneByteString> wire_bytes(compiled_module->module_bytes(), isolate);
  LocalNames decoded_locals;
  {
    DisallowHeapAllocation no_gc;
    wasm::DecodeLocalNames(wire_bytes->GetChars(),
                           wire_bytes->GetChars() + wire_bytes->length(),
                           &decoded_locals);
  }
  Handle<FixedArray> locals_names =
      isolate->factory()->NewFixedArray(decoded_locals.max_function_index + 1);
  for (LocalNamesPerFunction& func : decoded_locals.names) {
    Handle<FixedArray> func_locals_names =
        isolate->factory()->NewFixedArray(func.max_local_index + 1);
    locals_names->set(func.function_index, *func_locals_names);
    for (LocalName& name : func.names) {
      Handle<String> name_str =
          WasmCompiledModule::ExtractUtf8StringFromModuleBytes(
              isolate, compiled_module, name.name)
              .ToHandleChecked();
      func_locals_names->set(name.local_index, *name_str);
    }
  }
  return locals_names;
}

787
bool wasm::SyncValidate(Isolate* isolate, const ModuleWireBytes& bytes) {
788
  if (bytes.start() == nullptr || bytes.length() == 0) return false;
789 790
  ModuleResult result = SyncDecodeWasmModule(isolate, bytes.start(),
                                             bytes.end(), true, kWasmOrigin);
791 792 793 794 795 796 797
  return result.ok();
}

MaybeHandle<WasmModuleObject> wasm::SyncCompileTranslatedAsmJs(
    Isolate* isolate, ErrorThrower* thrower, const ModuleWireBytes& bytes,
    Handle<Script> asm_js_script,
    Vector<const byte> asm_js_offset_table_bytes) {
798 799
  ModuleResult result = SyncDecodeWasmModule(isolate, bytes.start(),
                                             bytes.end(), false, kAsmJsOrigin);
800 801
  if (result.failed()) {
    thrower->CompileFailed("Wasm decoding failed", result);
802
    return {};
803 804
  }

805 806
  // Transfer ownership to the {WasmModuleWrapper} generated in
  // {CompileToModuleObject}.
807
  ModuleCompiler helper(isolate, std::move(result.val));
808 809
  return helper.CompileToModuleObject(thrower, bytes, asm_js_script,
                                      asm_js_offset_table_bytes);
810 811 812 813 814 815 816
}

MaybeHandle<WasmModuleObject> wasm::SyncCompile(Isolate* isolate,
                                                ErrorThrower* thrower,
                                                const ModuleWireBytes& bytes) {
  if (!IsWasmCodegenAllowed(isolate, isolate->native_context())) {
    thrower->CompileError("Wasm code generation disallowed in this context");
817
    return {};
818 819
  }

820 821
  ModuleResult result = SyncDecodeWasmModule(isolate, bytes.start(),
                                             bytes.end(), false, kWasmOrigin);
822 823
  if (result.failed()) {
    thrower->CompileFailed("Wasm decoding failed", result);
824
    return {};
825 826
  }

827 828
  // Transfer ownership to the {WasmModuleWrapper} generated in
  // {CompileToModuleObject}.
829
  ModuleCompiler helper(isolate, std::move(result.val));
830 831
  return helper.CompileToModuleObject(thrower, bytes, Handle<Script>(),
                                      Vector<const byte>());
832 833 834 835 836 837
}

MaybeHandle<WasmInstanceObject> wasm::SyncInstantiate(
    Isolate* isolate, ErrorThrower* thrower,
    Handle<WasmModuleObject> module_object, MaybeHandle<JSReceiver> imports,
    MaybeHandle<JSArrayBuffer> memory) {
838 839 840
  InstanceBuilder builder(isolate, thrower, module_object, imports, memory,
                          &InstanceFinalizer);
  return builder.Build();
841 842
}

843 844 845 846 847 848 849 850
MaybeHandle<WasmInstanceObject> wasm::SyncCompileAndInstantiate(
    Isolate* isolate, ErrorThrower* thrower, const ModuleWireBytes& bytes,
    MaybeHandle<JSReceiver> imports, MaybeHandle<JSArrayBuffer> memory) {
  MaybeHandle<WasmModuleObject> module =
      wasm::SyncCompile(isolate, thrower, bytes);
  DCHECK_EQ(thrower->error(), module.is_null());
  if (module.is_null()) return {};

851 852 853
  return wasm::SyncInstantiate(isolate, thrower, module.ToHandleChecked(),
                               Handle<JSReceiver>::null(),
                               Handle<JSArrayBuffer>::null());
854 855
}

856 857 858
namespace v8 {
namespace internal {
namespace wasm {
859

860
void RejectPromise(Isolate* isolate, Handle<Context> context,
861
                   ErrorThrower& thrower, Handle<JSPromise> promise) {
862 863
  v8::Local<v8::Promise::Resolver> resolver =
      v8::Utils::PromiseToLocal(promise).As<v8::Promise::Resolver>();
864
  auto maybe = resolver->Reject(v8::Utils::ToLocal(context),
865
                                v8::Utils::ToLocal(thrower.Reify()));
866
  CHECK_IMPLIES(!maybe.FromMaybe(false), isolate->has_scheduled_exception());
867 868
}

869 870
void ResolvePromise(Isolate* isolate, Handle<Context> context,
                    Handle<JSPromise> promise, Handle<Object> result) {
871 872
  v8::Local<v8::Promise::Resolver> resolver =
      v8::Utils::PromiseToLocal(promise).As<v8::Promise::Resolver>();
873 874
  auto maybe = resolver->Resolve(v8::Utils::ToLocal(context),
                                 v8::Utils::ToLocal(result));
875
  CHECK_IMPLIES(!maybe.FromMaybe(false), isolate->has_scheduled_exception());
876 877
}

878 879 880
}  // namespace wasm
}  // namespace internal
}  // namespace v8
881

882 883 884 885 886 887 888
void wasm::AsyncInstantiate(Isolate* isolate, Handle<JSPromise> promise,
                            Handle<WasmModuleObject> module_object,
                            MaybeHandle<JSReceiver> imports) {
  ErrorThrower thrower(isolate, nullptr);
  MaybeHandle<WasmInstanceObject> instance_object = SyncInstantiate(
      isolate, &thrower, module_object, imports, Handle<JSArrayBuffer>::null());
  if (thrower.error()) {
889
    RejectPromise(isolate, handle(isolate->context()), thrower, promise);
890 891
    return;
  }
892 893
  ResolvePromise(isolate, handle(isolate->context()), promise,
                 instance_object.ToHandleChecked());
894 895
}

896 897
void wasm::AsyncCompile(Isolate* isolate, Handle<JSPromise> promise,
                        const ModuleWireBytes& bytes) {
898 899 900 901 902 903
  if (!FLAG_wasm_async_compilation) {
    ErrorThrower thrower(isolate, "WasmCompile");
    // Compile the module.
    MaybeHandle<WasmModuleObject> module_object =
        SyncCompile(isolate, &thrower, bytes);
    if (thrower.error()) {
904
      RejectPromise(isolate, handle(isolate->context()), thrower, promise);
905 906 907 908 909 910 911
      return;
    }
    Handle<WasmModuleObject> module = module_object.ToHandleChecked();
    ResolvePromise(isolate, handle(isolate->context()), promise, module);
    return;
  }

912 913 914 915
  // Make a copy of the wire bytes in case the user program changes them
  // during asynchronous compilation.
  std::unique_ptr<byte[]> copy(new byte[bytes.length()]);
  memcpy(copy.get(), bytes.start(), bytes.length());
916 917 918
  isolate->wasm_compilation_manager()->StartAsyncCompileJob(
      isolate, std::move(copy), bytes.length(), handle(isolate->context()),
      promise);
919
}
920 921 922

Handle<Code> wasm::CompileLazy(Isolate* isolate) {
  HistogramTimerScope lazy_time_scope(
923
      isolate->counters()->wasm_lazy_compilation_time());
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

  // Find the wasm frame which triggered the lazy compile, to get the wasm
  // instance.
  StackFrameIterator it(isolate);
  // First frame: C entry stub.
  DCHECK(!it.done());
  DCHECK_EQ(StackFrame::EXIT, it.frame()->type());
  it.Advance();
  // Second frame: WasmCompileLazy builtin.
  DCHECK(!it.done());
  Handle<Code> lazy_compile_code(it.frame()->LookupCode(), isolate);
  DCHECK_EQ(Builtins::kWasmCompileLazy, lazy_compile_code->builtin_index());
  Handle<WasmInstanceObject> instance;
  Handle<FixedArray> exp_deopt_data;
  int func_index = -1;
  if (lazy_compile_code->deoptimization_data()->length() > 0) {
940
    // Then it's an indirect call or via JS->wasm wrapper.
941 942 943 944
    DCHECK_LE(2, lazy_compile_code->deoptimization_data()->length());
    exp_deopt_data = handle(lazy_compile_code->deoptimization_data(), isolate);
    auto* weak_cell = WeakCell::cast(exp_deopt_data->get(0));
    instance = handle(WasmInstanceObject::cast(weak_cell->value()), isolate);
jgruber's avatar
jgruber committed
945
    func_index = Smi::ToInt(exp_deopt_data->get(1));
946 947 948 949 950 951 952 953 954
  }
  it.Advance();
  // Third frame: The calling wasm code or js-to-wasm wrapper.
  DCHECK(!it.done());
  DCHECK(it.frame()->is_js_to_wasm() || it.frame()->is_wasm_compiled());
  Handle<Code> caller_code = handle(it.frame()->LookupCode(), isolate);
  if (it.frame()->is_js_to_wasm()) {
    DCHECK(!instance.is_null());
  } else if (instance.is_null()) {
955 956 957
    // Then this is a direct call (otherwise we would have attached the instance
    // via deopt data to the lazy compile stub). Just use the instance of the
    // caller.
958 959 960 961 962 963 964 965 966 967 968 969 970
    instance = handle(wasm::GetOwningWasmInstance(*caller_code), isolate);
  }
  int offset =
      static_cast<int>(it.frame()->pc() - caller_code->instruction_start());
  // Only patch the caller code if this is *no* indirect call.
  // exp_deopt_data will be null if the called function is not exported at all,
  // and its length will be <= 2 if all entries in tables were already patched.
  // Note that this check is conservative: If the first call to an exported
  // function is direct, we will just patch the export tables, and only on the
  // second call we will patch the caller.
  bool patch_caller = caller_code->kind() == Code::JS_TO_WASM_FUNCTION ||
                      exp_deopt_data.is_null() || exp_deopt_data->length() <= 2;

971
  Handle<Code> compiled_code = WasmCompiledModule::CompileLazy(
972 973 974 975 976 977 978 979 980
      isolate, instance, caller_code, offset, func_index, patch_caller);
  if (!exp_deopt_data.is_null() && exp_deopt_data->length() > 2) {
    // See EnsureExportedLazyDeoptData: exp_deopt_data[2...(len-1)] are pairs of
    // <export_table, index> followed by undefined values.
    // Use this information here to patch all export tables.
    DCHECK_EQ(0, exp_deopt_data->length() % 2);
    for (int idx = 2, end = exp_deopt_data->length(); idx < end; idx += 2) {
      if (exp_deopt_data->get(idx)->IsUndefined(isolate)) break;
      FixedArray* exp_table = FixedArray::cast(exp_deopt_data->get(idx));
jgruber's avatar
jgruber committed
981
      int exp_index = Smi::ToInt(exp_deopt_data->get(idx + 1));
982 983 984 985 986 987 988 989 990 991 992 993 994
      DCHECK(exp_table->get(exp_index) == *lazy_compile_code);
      exp_table->set(exp_index, *compiled_code);
    }
    // After processing, remove the list of exported entries, such that we don't
    // do the patching redundantly.
    Handle<FixedArray> new_deopt_data =
        isolate->factory()->CopyFixedArrayUpTo(exp_deopt_data, 2, TENURED);
    lazy_compile_code->set_deoptimization_data(*new_deopt_data);
  }

  return compiled_code;
}

995
void LazyCompilationOrchestrator::CompileFunction(
996
    Isolate* isolate, Handle<WasmInstanceObject> instance, int func_index) {
997 998 999 1000
  Handle<WasmCompiledModule> compiled_module(instance->compiled_module(),
                                             isolate);
  if (Code::cast(compiled_module->code_table()->get(func_index))->kind() ==
      Code::WASM_FUNCTION) {
1001
    return;
1002
  }
1003

1004 1005 1006 1007 1008 1009
  wasm::ModuleEnv module_env =
      CreateModuleEnvFromRuntimeObject(isolate, compiled_module);

  const uint8_t* module_start = compiled_module->module_bytes()->GetChars();

  const WasmFunction* func = &module_env.module()->functions[func_index];
1010
  wasm::FunctionBody body{func->sig, func->code.offset(),
1011 1012
                          module_start + func->code.offset(),
                          module_start + func->code.end_offset()};
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
  // TODO(wasm): Refactor this to only get the name if it is really needed for
  // tracing / debugging.
  std::string func_name;
  {
    wasm::WasmName name = Vector<const char>::cast(
        compiled_module->GetRawFunctionName(func_index));
    // Copy to std::string, because the underlying string object might move on
    // the heap.
    func_name.assign(name.start(), static_cast<size_t>(name.length()));
  }
  ErrorThrower thrower(isolate, "WasmLazyCompile");
  compiler::WasmCompilationUnit unit(isolate, &module_env, body,
1025 1026
                                     CStrVector(func_name.c_str()), func_index,
                                     CEntryStub(isolate, 1).GetCode());
1027
  unit.ExecuteCompilation();
1028
  MaybeHandle<Code> maybe_code = unit.FinishCompilation(&thrower);
1029

1030 1031 1032
  // If there is a pending error, something really went wrong. The module was
  // verified before starting execution with lazy compilation.
  // This might be OOM, but then we cannot continue execution anyway.
1033 1034
  // TODO(clemensh): According to the spec, we can actually skip validation at
  // module creation time, and return a function that always traps here.
1035
  CHECK(!thrower.error());
1036
  Handle<Code> code = maybe_code.ToHandleChecked();
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
  Handle<FixedArray> deopt_data = isolate->factory()->NewFixedArray(2, TENURED);
  Handle<WeakCell> weak_instance = isolate->factory()->NewWeakCell(instance);
  // TODO(wasm): Introduce constants for the indexes in wasm deopt data.
  deopt_data->set(0, *weak_instance);
  deopt_data->set(1, Smi::FromInt(func_index));
  code->set_deoptimization_data(*deopt_data);

  DCHECK_EQ(Builtins::kWasmCompileLazy,
            Code::cast(compiled_module->code_table()->get(func_index))
                ->builtin_index());
  compiled_module->code_table()->set(func_index, *code);

  // Now specialize the generated code for this instance.
  Zone specialization_zone(isolate->allocator(), ZONE_NAME);
  CodeSpecialization code_specialization(isolate, &specialization_zone);
  code_specialization.RelocateDirectCalls(instance);
  code_specialization.ApplyToWasmCode(*code, SKIP_ICACHE_FLUSH);
  Assembler::FlushICache(isolate, code->instruction_start(),
                         code->instruction_size());
1057
  RecordLazyCodeStats(*code, isolate->counters());
1058 1059
}

1060
Handle<Code> LazyCompilationOrchestrator::CompileLazy(
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    Isolate* isolate, Handle<WasmInstanceObject> instance, Handle<Code> caller,
    int call_offset, int exported_func_index, bool patch_caller) {
  struct NonCompiledFunction {
    int offset;
    int func_index;
  };
  std::vector<NonCompiledFunction> non_compiled_functions;
  int func_to_return_idx = exported_func_index;
  wasm::Decoder decoder(nullptr, nullptr);
  bool is_js_to_wasm = caller->kind() == Code::JS_TO_WASM_FUNCTION;
  Handle<WasmCompiledModule> compiled_module(instance->compiled_module(),
                                             isolate);

  if (is_js_to_wasm) {
    non_compiled_functions.push_back({0, exported_func_index});
  } else if (patch_caller) {
    DisallowHeapAllocation no_gc;
    SeqOneByteString* module_bytes = compiled_module->module_bytes();
    SourcePositionTableIterator source_pos_iterator(
1080
        caller->SourcePositionTable());
1081
    DCHECK_EQ(2, caller->deoptimization_data()->length());
jgruber's avatar
jgruber committed
1082
    int caller_func_index = Smi::ToInt(caller->deoptimization_data()->get(1));
1083
    const byte* func_bytes =
1084 1085
        module_bytes->GetChars() +
        compiled_module->module()->functions[caller_func_index].code.offset();
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    for (RelocIterator it(*caller, RelocInfo::kCodeTargetMask); !it.done();
         it.next()) {
      Code* callee =
          Code::GetCodeFromTargetAddress(it.rinfo()->target_address());
      if (callee->builtin_index() != Builtins::kWasmCompileLazy) continue;
      // TODO(clemensh): Introduce safe_cast<T, bool> which (D)CHECKS
      // (depending on the bool) against limits of T and then static_casts.
      size_t offset_l = it.rinfo()->pc() - caller->instruction_start();
      DCHECK_GE(kMaxInt, offset_l);
      int offset = static_cast<int>(offset_l);
      int byte_pos =
          AdvanceSourcePositionTableIterator(source_pos_iterator, offset);
      int called_func_index =
          ExtractDirectCallIndex(decoder, func_bytes + byte_pos);
      non_compiled_functions.push_back({offset, called_func_index});
      // Call offset one instruction after the call. Remember the last called
      // function before that offset.
      if (offset < call_offset) func_to_return_idx = called_func_index;
    }
  }

  // TODO(clemensh): compile all functions in non_compiled_functions in
  // background, wait for func_to_return_idx.
1109
  CompileFunction(isolate, instance, func_to_return_idx);
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122

  if (is_js_to_wasm || patch_caller) {
    DisallowHeapAllocation no_gc;
    // Now patch the code object with all functions which are now compiled.
    int idx = 0;
    for (RelocIterator it(*caller, RelocInfo::kCodeTargetMask); !it.done();
         it.next()) {
      Code* callee =
          Code::GetCodeFromTargetAddress(it.rinfo()->target_address());
      if (callee->builtin_index() != Builtins::kWasmCompileLazy) continue;
      DCHECK_GT(non_compiled_functions.size(), idx);
      int called_func_index = non_compiled_functions[idx].func_index;
      // Check that the callee agrees with our assumed called_func_index.
jgruber's avatar
jgruber committed
1123 1124 1125
      DCHECK_IMPLIES(callee->deoptimization_data()->length() > 0,
                     Smi::ToInt(callee->deoptimization_data()->get(1)) ==
                         called_func_index);
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
      if (is_js_to_wasm) {
        DCHECK_EQ(func_to_return_idx, called_func_index);
      } else {
        DCHECK_EQ(non_compiled_functions[idx].offset,
                  it.rinfo()->pc() - caller->instruction_start());
      }
      ++idx;
      Handle<Code> callee_compiled(
          Code::cast(compiled_module->code_table()->get(called_func_index)));
      if (callee_compiled->builtin_index() == Builtins::kWasmCompileLazy) {
        DCHECK_NE(func_to_return_idx, called_func_index);
        continue;
      }
      DCHECK_EQ(Code::WASM_FUNCTION, callee_compiled->kind());
      it.rinfo()->set_target_address(isolate,
                                     callee_compiled->instruction_start());
    }
    DCHECK_EQ(non_compiled_functions.size(), idx);
  }

  Code* ret =
      Code::cast(compiled_module->code_table()->get(func_to_return_idx));
  DCHECK_EQ(Code::WASM_FUNCTION, ret->kind());
  return handle(ret, isolate);
}
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

const char* wasm::ExternalKindName(WasmExternalKind kind) {
  switch (kind) {
    case kExternalFunction:
      return "function";
    case kExternalTable:
      return "table";
    case kExternalMemory:
      return "memory";
    case kExternalGlobal:
      return "global";
  }
  return "unknown";
}