wasm-code-manager.cc 55 KB
Newer Older
1 2 3 4
// Copyright 2017 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/wasm/wasm-code-manager.h"
6

7 8
#include <iomanip>

9
#include "src/assembler-inl.h"
10
#include "src/base/adapters.h"
11 12 13 14
#include "src/base/macros.h"
#include "src/base/platform/platform.h"
#include "src/disassembler.h"
#include "src/globals.h"
15
#include "src/log.h"
16
#include "src/macro-assembler-inl.h"
17 18
#include "src/macro-assembler.h"
#include "src/objects-inl.h"
19
#include "src/ostreams.h"
20
#include "src/snapshot/embedded-data.h"
21
#include "src/vector.h"
22
#include "src/wasm/compilation-environment.h"
23
#include "src/wasm/function-compiler.h"
24
#include "src/wasm/jump-table-assembler.h"
25
#include "src/wasm/wasm-import-wrapper-cache.h"
26 27 28 29 30 31
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-objects-inl.h"
#include "src/wasm/wasm-objects.h"

#define TRACE_HEAP(...)                                   \
  do {                                                    \
32
    if (FLAG_trace_wasm_native_heap) PrintF(__VA_ARGS__); \
33 34
  } while (false)

35 36 37 38
namespace v8 {
namespace internal {
namespace wasm {

39 40
using trap_handler::ProtectedInstructionData;

41 42 43
void DisjointAllocationPool::Merge(base::AddressRegion region) {
  auto dest_it = regions_.begin();
  auto dest_end = regions_.end();
44

45 46
  // Skip over dest regions strictly before {region}.
  while (dest_it != dest_end && dest_it->end() < region.begin()) ++dest_it;
47

48
  // After last dest region: insert and done.
49
  if (dest_it == dest_end) {
50
    regions_.push_back(region);
51 52 53 54
    return;
  }

  // Adjacent (from below) to dest: merge and done.
55 56 57 58 59
  if (dest_it->begin() == region.end()) {
    base::AddressRegion merged_region{region.begin(),
                                      region.size() + dest_it->size()};
    DCHECK_EQ(merged_region.end(), dest_it->end());
    *dest_it = merged_region;
60 61 62 63
    return;
  }

  // Before dest: insert and done.
64 65
  if (dest_it->begin() > region.end()) {
    regions_.insert(dest_it, region);
66 67
    return;
  }
68

69 70 71 72 73
  // Src is adjacent from above. Merge and check whether the merged region is
  // now adjacent to the next region.
  DCHECK_EQ(dest_it->end(), region.begin());
  dest_it->set_size(dest_it->size() + region.size());
  DCHECK_EQ(dest_it->end(), region.end());
74 75
  auto next_dest = dest_it;
  ++next_dest;
76 77 78 79
  if (next_dest != dest_end && dest_it->end() == next_dest->begin()) {
    dest_it->set_size(dest_it->size() + next_dest->size());
    DCHECK_EQ(dest_it->end(), next_dest->end());
    regions_.erase(next_dest);
80 81 82
  }
}

83 84 85 86 87 88
base::AddressRegion DisjointAllocationPool::Allocate(size_t size) {
  for (auto it = regions_.begin(), end = regions_.end(); it != end; ++it) {
    if (size > it->size()) continue;
    base::AddressRegion ret{it->begin(), size};
    if (size == it->size()) {
      regions_.erase(it);
89
    } else {
90
      *it = base::AddressRegion{it->begin() + size, it->size() - size};
91
    }
92
    return ret;
93
  }
94
  return {};
95 96
}

97 98
Address WasmCode::constant_pool() const {
  if (FLAG_enable_embedded_constant_pool) {
99
    if (constant_pool_offset_ < code_comments_offset_) {
100
      return instruction_start() + constant_pool_offset_;
101 102
    }
  }
103
  return kNullAddress;
104 105
}

106 107 108 109 110 111 112
Address WasmCode::code_comments() const {
  if (code_comments_offset_ < unpadded_binary_size_) {
    return instruction_start() + code_comments_offset_;
  }
  return kNullAddress;
}

113 114 115 116 117 118 119 120 121
size_t WasmCode::trap_handler_index() const {
  CHECK(HasTrapHandlerIndex());
  return static_cast<size_t>(trap_handler_index_);
}

void WasmCode::set_trap_handler_index(size_t value) {
  trap_handler_index_ = value;
}

122
void WasmCode::RegisterTrapHandlerData() {
123
  DCHECK(!HasTrapHandlerIndex());
124
  if (kind() != WasmCode::kFunction) return;
125
  if (protected_instructions_.is_empty()) return;
126 127 128 129 130 131

  Address base = instruction_start();

  size_t size = instructions().size();
  const int index =
      RegisterHandlerData(base, size, protected_instructions().size(),
132
                          protected_instructions().start());
133 134 135 136 137 138

  // TODO(eholk): if index is negative, fail.
  CHECK_LE(0, index);
  set_trap_handler_index(static_cast<size_t>(index));
}

139 140
bool WasmCode::HasTrapHandlerIndex() const { return trap_handler_index_ >= 0; }

141
bool WasmCode::ShouldBeLogged(Isolate* isolate) {
142 143 144
  // The return value is cached in {WasmEngine::IsolateData::log_codes}. Ensure
  // to call {WasmEngine::EnableCodeLogging} if this return value would change
  // for any isolate. Otherwise we might lose code events.
145
  return isolate->logger()->is_listening_to_code_events() ||
146
         isolate->is_profiling();
147 148 149 150
}

void WasmCode::LogCode(Isolate* isolate) const {
  DCHECK(ShouldBeLogged(isolate));
151
  if (IsAnonymous()) return;
152

153 154
  ModuleWireBytes wire_bytes(native_module()->wire_bytes());
  // TODO(herhut): Allow to log code without on-heap round-trip of the name.
155
  WireBytesRef name_ref =
156
      native_module()->module()->LookupFunctionName(wire_bytes, index());
157 158
  WasmName name_vec = wire_bytes.GetNameOrNull(name_ref);
  if (!name_vec.is_empty()) {
159
    HandleScope scope(isolate);
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    MaybeHandle<String> maybe_name = isolate->factory()->NewStringFromUtf8(
        Vector<const char>::cast(name_vec));
    Handle<String> name;
    if (!maybe_name.ToHandle(&name)) {
      name = isolate->factory()->NewStringFromAsciiChecked("<name too long>");
    }
    int name_length;
    auto cname =
        name->ToCString(AllowNullsFlag::DISALLOW_NULLS,
                        RobustnessFlag::ROBUST_STRING_TRAVERSAL, &name_length);
    PROFILE(isolate,
            CodeCreateEvent(CodeEventListener::FUNCTION_TAG, this,
                            {cname.get(), static_cast<size_t>(name_length)}));
  } else {
    EmbeddedVector<char, 32> generated_name;
175 176
    int length = SNPrintF(generated_name, "wasm-function[%d]", index());
    generated_name.Truncate(length);
177 178
    PROFILE(isolate, CodeCreateEvent(CodeEventListener::FUNCTION_TAG, this,
                                     generated_name));
179
  }
180

181 182 183
  if (!source_positions().is_empty()) {
    LOG_CODE_EVENT(isolate, CodeLinePosInfoRecordEvent(instruction_start(),
                                                       source_positions()));
184 185 186
  }
}

187 188 189 190 191 192 193 194 195
void WasmCode::Validate() const {
#ifdef DEBUG
  // We expect certain relocation info modes to never appear in {WasmCode}
  // objects or to be restricted to a small set of valid values. Hence the
  // iteration below does not use a mask, but visits all relocation data.
  for (RelocIterator it(instructions(), reloc_info(), constant_pool());
       !it.done(); it.next()) {
    RelocInfo::Mode mode = it.rinfo()->rmode();
    switch (mode) {
196 197 198 199 200
      case RelocInfo::WASM_CALL: {
        Address target = it.rinfo()->wasm_call_address();
        WasmCode* code = native_module_->Lookup(target);
        CHECK_NOT_NULL(code);
        CHECK_EQ(WasmCode::kJumpTable, code->kind());
201
        CHECK_EQ(native_module()->jump_table_, code);
202 203 204
        CHECK(code->contains(target));
        break;
      }
205 206 207
      case RelocInfo::WASM_STUB_CALL: {
        Address target = it.rinfo()->wasm_stub_call_address();
        WasmCode* code = native_module_->Lookup(target);
208
        CHECK_NOT_NULL(code);
209 210 211 212 213
#ifdef V8_EMBEDDED_BUILTINS
        CHECK_EQ(WasmCode::kJumpTable, code->kind());
        CHECK_EQ(native_module()->runtime_stub_table_, code);
        CHECK(code->contains(target));
#else
214
        CHECK_EQ(WasmCode::kRuntimeStub, code->kind());
215
        CHECK_EQ(target, code->instruction_start());
216
#endif
217 218
        break;
      }
219 220 221 222 223 224
      case RelocInfo::INTERNAL_REFERENCE:
      case RelocInfo::INTERNAL_REFERENCE_ENCODED: {
        Address target = it.rinfo()->target_internal_reference();
        CHECK(contains(target));
        break;
      }
225 226 227 228 229 230 231 232 233 234 235 236
      case RelocInfo::EXTERNAL_REFERENCE:
      case RelocInfo::CONST_POOL:
      case RelocInfo::VENEER_POOL:
        // These are OK to appear.
        break;
      default:
        FATAL("Unexpected mode: %d", mode);
    }
  }
#endif
}

237 238 239 240 241 242 243 244
void WasmCode::MaybePrint(const char* name) const {
  // Determines whether flags want this code to be printed.
  if ((FLAG_print_wasm_code && kind() == kFunction) ||
      (FLAG_print_wasm_stub_code && kind() != kFunction) || FLAG_print_code) {
    Print(name);
  }
}

245
void WasmCode::Print(const char* name) const {
246
  StdoutStream os;
247
  os << "--- WebAssembly code ---\n";
248
  Disassemble(name, os);
249
  os << "--- End code ---\n";
250 251
}

252
void WasmCode::Disassemble(const char* name, std::ostream& os,
253
                           Address current_pc) const {
254
  if (name) os << "name: " << name << "\n";
255
  if (!IsAnonymous()) os << "index: " << index() << "\n";
256
  os << "kind: " << GetWasmCodeKindAsString(kind_) << "\n";
257
  os << "compiler: " << (is_liftoff() ? "Liftoff" : "TurboFan") << "\n";
258 259 260
  size_t padding = instructions().size() - unpadded_binary_size_;
  os << "Body (size = " << instructions().size() << " = "
     << unpadded_binary_size_ << " + " << padding << " padding)\n";
261

262
#ifdef ENABLE_DISASSEMBLER
263 264
  size_t instruction_size = unpadded_binary_size_;
  if (constant_pool_offset_ < instruction_size) {
265 266 267 268 269
    instruction_size = constant_pool_offset_;
  }
  if (safepoint_table_offset_ && safepoint_table_offset_ < instruction_size) {
    instruction_size = safepoint_table_offset_;
  }
270 271 272
  if (handler_table_offset_ && handler_table_offset_ < instruction_size) {
    instruction_size = handler_table_offset_;
  }
273
  DCHECK_LT(0, instruction_size);
274
  os << "Instructions (size = " << instruction_size << ")\n";
275
  Disassembler::Decode(nullptr, &os, instructions().start(),
276 277
                       instructions().start() + instruction_size,
                       CodeReference(this), current_pc);
278 279
  os << "\n";

280 281 282 283 284 285 286 287
  if (handler_table_offset_ > 0) {
    HandlerTable table(instruction_start(), handler_table_offset_);
    os << "Exception Handler Table (size = " << table.NumberOfReturnEntries()
       << "):\n";
    table.HandlerTableReturnPrint(os);
    os << "\n";
  }

288 289 290 291 292 293 294 295 296
  if (!protected_instructions_.is_empty()) {
    os << "Protected instructions:\n pc offset  land pad\n";
    for (auto& data : protected_instructions()) {
      os << std::setw(10) << std::hex << data.instr_offset << std::setw(10)
         << std::hex << data.landing_offset << "\n";
    }
    os << "\n";
  }

297 298 299 300 301 302 303
  if (!source_positions().is_empty()) {
    os << "Source positions:\n pc offset  position\n";
    for (SourcePositionTableIterator it(source_positions()); !it.done();
         it.Advance()) {
      os << std::setw(10) << std::hex << it.code_offset() << std::dec
         << std::setw(10) << it.source_position().ScriptOffset()
         << (it.is_statement() ? "  statement" : "") << "\n";
304
    }
305
    os << "\n";
306
  }
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321
  if (safepoint_table_offset_ > 0) {
    SafepointTable table(instruction_start(), safepoint_table_offset_,
                         stack_slots_);
    os << "Safepoints (size = " << table.size() << ")\n";
    for (uint32_t i = 0; i < table.length(); i++) {
      uintptr_t pc_offset = table.GetPcOffset(i);
      os << reinterpret_cast<const void*>(instruction_start() + pc_offset);
      os << std::setw(6) << std::hex << pc_offset << "  " << std::dec;
      table.PrintEntry(i, os);
      os << " (sp -> fp)";
      SafepointEntry entry = table.GetEntry(i);
      if (entry.trampoline_pc() != -1) {
        os << " trampoline: " << std::hex << entry.trampoline_pc() << std::dec;
      }
322
      if (entry.has_deoptimization_index()) {
323 324 325 326 327 328 329
        os << " deopt: " << std::setw(6) << entry.deoptimization_index();
      }
      os << "\n";
    }
    os << "\n";
  }

330
  os << "RelocInfo (size = " << reloc_info_.size() << ")\n";
331 332
  for (RelocIterator it(instructions(), reloc_info(), constant_pool());
       !it.done(); it.next()) {
333
    it.rinfo()->Print(nullptr, os);
334 335
  }
  os << "\n";
336 337 338 339 340 341

  if (code_comments_offset() < unpadded_binary_size_) {
    Address code_comments = reinterpret_cast<Address>(instructions().start() +
                                                      code_comments_offset());
    PrintCodeCommentsSection(os, code_comments);
  }
342
#endif  // ENABLE_DISASSEMBLER
343 344
}

345 346
const char* GetWasmCodeKindAsString(WasmCode::Kind kind) {
  switch (kind) {
347
    case WasmCode::kFunction:
348
      return "wasm function";
349
    case WasmCode::kWasmToJsWrapper:
350
      return "wasm-to-js";
351 352
    case WasmCode::kRuntimeStub:
      return "runtime-stub";
353 354
    case WasmCode::kInterpreterEntry:
      return "interpreter entry";
355 356
    case WasmCode::kJumpTable:
      return "jump table";
357 358 359 360
  }
  return "unknown kind";
}

361 362 363 364 365 366 367 368
WasmCode::~WasmCode() {
  if (HasTrapHandlerIndex()) {
    CHECK_LT(trap_handler_index(),
             static_cast<size_t>(std::numeric_limits<int>::max()));
    trap_handler::ReleaseHandlerData(static_cast<int>(trap_handler_index()));
  }
}

369 370
NativeModule::NativeModule(WasmEngine* engine, const WasmFeatures& enabled,
                           bool can_request_more, VirtualMemory code_space,
371
                           std::shared_ptr<const WasmModule> module,
372 373
                           std::shared_ptr<Counters> async_counters,
                           std::shared_ptr<NativeModule>* shared_this)
374 375
    : enabled_features_(enabled),
      module_(std::move(module)),
376 377
      import_wrapper_cache_(std::unique_ptr<WasmImportWrapperCache>(
          new WasmImportWrapperCache(this))),
378
      free_code_space_(code_space.region()),
379
      engine_(engine),
380
      can_request_more_memory_(can_request_more),
381 382
      use_trap_handler_(trap_handler::IsTrapHandlerEnabled() ? kUseTrapHandler
                                                             : kNoTrapHandler) {
383 384 385 386 387 388 389
  // We receive a pointer to an empty {std::shared_ptr}, and install ourselve
  // there.
  DCHECK_NOT_NULL(shared_this);
  DCHECK_NULL(*shared_this);
  shared_this->reset(this);
  compilation_state_ =
      CompilationState::New(*shared_this, std::move(async_counters));
390
  DCHECK_NOT_NULL(module_);
391
  owned_code_space_.emplace_back(std::move(code_space));
392
  owned_code_.reserve(num_functions());
393

394
  uint32_t num_wasm_functions = module_->num_declared_functions;
395
  if (num_wasm_functions > 0) {
396
    code_table_.reset(new WasmCode* [num_wasm_functions] {});
397

398 399
    jump_table_ = CreateEmptyJumpTable(
        JumpTableAssembler::SizeForNumberOfSlots(num_wasm_functions));
400
  }
401 402
}

403
void NativeModule::ReserveCodeTableForTesting(uint32_t max_functions) {
404
  DCHECK_LE(num_functions(), max_functions);
405
  WasmCode** new_table = new WasmCode* [max_functions] {};
406 407 408 409
  if (module_->num_declared_functions > 0) {
    memcpy(new_table, code_table_.get(),
           module_->num_declared_functions * sizeof(*new_table));
  }
410
  code_table_.reset(new_table);
411 412

  // Re-allocate jump table.
413 414
  jump_table_ = CreateEmptyJumpTable(
      JumpTableAssembler::SizeForNumberOfSlots(max_functions));
415 416
}

417
void NativeModule::LogWasmCodes(Isolate* isolate) {
418
  if (!WasmCode::ShouldBeLogged(isolate)) return;
419 420 421

  // TODO(titzer): we skip the logging of the import wrappers
  // here, but they should be included somehow.
422
  for (WasmCode* code : code_table()) {
423 424 425 426
    if (code != nullptr) code->LogCode(isolate);
  }
}

427
CompilationEnv NativeModule::CreateCompilationEnv() const {
428 429
  return {module(), use_trap_handler_, kRuntimeExceptionSupport,
          enabled_features_};
430 431
}

432
WasmCode* NativeModule::AddCodeForTesting(Handle<Code> code) {
433
  return AddAndPublishAnonymousCode(code, WasmCode::kFunction);
434 435
}

436
void NativeModule::SetLazyBuiltin() {
437
  uint32_t num_wasm_functions = module_->num_declared_functions;
438 439
  if (num_wasm_functions == 0) return;
  // Fill the jump table with jumps to the lazy compile stub.
440
  Address lazy_compile_target = runtime_stub_entry(WasmCode::kWasmCompileLazy);
441
  for (uint32_t i = 0; i < num_wasm_functions; ++i) {
442 443 444 445
    JumpTableAssembler::EmitLazyCompileJumpSlot(
        jump_table_->instruction_start(), i,
        i + module_->num_imported_functions, lazy_compile_target,
        WasmCode::kNoFlushICache);
446
  }
447 448
  FlushInstructionCache(jump_table_->instructions().start(),
                        jump_table_->instructions().size());
449 450
}

451 452
// TODO(mstarzinger): Remove {Isolate} parameter once {V8_EMBEDDED_BUILTINS}
// was removed and embedded builtins are no longer optional.
453
void NativeModule::SetRuntimeStubs(Isolate* isolate) {
454 455 456 457 458 459
  DCHECK_EQ(kNullAddress, runtime_stub_entries_[0]);  // Only called once.
#ifdef V8_EMBEDDED_BUILTINS
  WasmCode* jump_table =
      CreateEmptyJumpTable(JumpTableAssembler::SizeForNumberOfStubSlots(
          WasmCode::kRuntimeStubCount));
  Address base = jump_table->instruction_start();
460
  EmbeddedData embedded_data = EmbeddedData::FromBlob();
461 462 463 464 465 466 467
#define RUNTIME_STUB(Name) {Builtins::k##Name, WasmCode::k##Name},
#define RUNTIME_STUB_TRAP(Name) RUNTIME_STUB(ThrowWasm##Name)
  std::pair<Builtins::Name, WasmCode::RuntimeStubId> wasm_runtime_stubs[] = {
      WASM_RUNTIME_STUB_LIST(RUNTIME_STUB, RUNTIME_STUB_TRAP)};
#undef RUNTIME_STUB
#undef RUNTIME_STUB_TRAP
  for (auto pair : wasm_runtime_stubs) {
468 469 470 471
    CHECK(embedded_data.ContainsBuiltin(pair.first));
    Address builtin = embedded_data.InstructionStartOfBuiltin(pair.first);
    JumpTableAssembler::EmitRuntimeStubSlot(base, pair.second, builtin,
                                            WasmCode::kNoFlushICache);
472 473 474 475 476 477 478 479 480
    uint32_t slot_offset =
        JumpTableAssembler::StubSlotIndexToOffset(pair.second);
    runtime_stub_entries_[pair.second] = base + slot_offset;
  }
  FlushInstructionCache(jump_table->instructions().start(),
                        jump_table->instructions().size());
  DCHECK_NULL(runtime_stub_table_);
  runtime_stub_table_ = jump_table;
#else  // V8_EMBEDDED_BUILTINS
481
  HandleScope scope(isolate);
482
  USE(runtime_stub_table_);  // Actually unused, but avoids ifdef's in header.
483 484 485 486 487
#define COPY_BUILTIN(Name)                                        \
  runtime_stub_entries_[WasmCode::k##Name] =                      \
      AddAndPublishAnonymousCode(                                 \
          isolate->builtins()->builtin_handle(Builtins::k##Name), \
          WasmCode::kRuntimeStub, #Name)                          \
488
          ->instruction_start();
489
#define COPY_BUILTIN_TRAP(Name) COPY_BUILTIN(ThrowWasm##Name)
490
  WASM_RUNTIME_STUB_LIST(COPY_BUILTIN, COPY_BUILTIN_TRAP)
491
#undef COPY_BUILTIN_TRAP
492
#undef COPY_BUILTIN
493 494
#endif  // V8_EMBEDDED_BUILTINS
  DCHECK_NE(kNullAddress, runtime_stub_entries_[0]);
495 496
}

497 498 499
WasmCode* NativeModule::AddAndPublishAnonymousCode(Handle<Code> code,
                                                   WasmCode::Kind kind,
                                                   const char* name) {
500 501 502 503 504
  // For off-heap builtins, we create a copy of the off-heap instruction stream
  // instead of the on-heap code object containing the trampoline. Ensure that
  // we do not apply the on-heap reloc info to the off-heap instructions.
  const size_t relocation_size =
      code->is_off_heap_trampoline() ? 0 : code->relocation_size();
505
  OwnedVector<byte> reloc_info;
506
  if (relocation_size > 0) {
507
    reloc_info = OwnedVector<byte>::New(relocation_size);
508 509
    memcpy(reloc_info.start(), code->relocation_start(), relocation_size);
  }
510 511
  Handle<ByteArray> source_pos_table(code->SourcePositionTable(),
                                     code->GetIsolate());
512 513
  OwnedVector<byte> source_pos =
      OwnedVector<byte>::New(source_pos_table->length());
514 515 516 517
  if (source_pos_table->length() > 0) {
    source_pos_table->copy_out(0, source_pos.start(),
                               source_pos_table->length());
  }
518
  Vector<const byte> instructions(
519 520
      reinterpret_cast<byte*>(code->InstructionStart()),
      static_cast<size_t>(code->InstructionSize()));
521 522
  const uint32_t stack_slots = static_cast<uint32_t>(
      code->has_safepoint_info() ? code->stack_slots() : 0);
523 524 525 526

  // TODO(jgruber,v8:8758): Remove this translation. It exists only because
  // Code objects contains real offsets but WasmCode expects an offset of 0 to
  // mean 'empty'.
527 528 529 530 531 532 533 534 535
  const size_t safepoint_table_offset = static_cast<size_t>(
      code->has_safepoint_table() ? code->safepoint_table_offset() : 0);
  const size_t handler_table_offset = static_cast<size_t>(
      code->has_handler_table() ? code->handler_table_offset() : 0);
  const size_t constant_pool_offset =
      static_cast<size_t>(code->constant_pool_offset());
  const size_t code_comments_offset =
      static_cast<size_t>(code->code_comments_offset());

536 537
  Vector<uint8_t> dst_code_bytes = AllocateForCode(instructions.size());
  memcpy(dst_code_bytes.begin(), instructions.start(), instructions.size());
538

539
  // Apply the relocation delta by iterating over the RelocInfo.
540 541
  intptr_t delta = reinterpret_cast<Address>(dst_code_bytes.begin()) -
                   code->InstructionStart();
542
  int mode_mask = RelocInfo::kApplyMask |
543
                  RelocInfo::ModeMask(RelocInfo::WASM_STUB_CALL);
544 545
  Address constant_pool_start =
      reinterpret_cast<Address>(dst_code_bytes.begin()) + constant_pool_offset;
546
  RelocIterator orig_it(*code, mode_mask);
547 548
  for (RelocIterator it(dst_code_bytes, reloc_info.as_vector(),
                        constant_pool_start, mode_mask);
549
       !it.done(); it.next(), orig_it.next()) {
550 551
    RelocInfo::Mode mode = it.rinfo()->rmode();
    if (RelocInfo::IsWasmStubCall(mode)) {
552
      uint32_t stub_call_tag = orig_it.rinfo()->wasm_call_tag();
553
      DCHECK_LT(stub_call_tag, WasmCode::kRuntimeStubCount);
554 555 556
      Address entry = runtime_stub_entry(
          static_cast<WasmCode::RuntimeStubId>(stub_call_tag));
      it.rinfo()->set_wasm_stub_call_address(entry, SKIP_ICACHE_FLUSH);
557
    } else {
558
      it.rinfo()->apply(delta);
559 560
    }
  }
561

562
  // Flush the i-cache after relocation.
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
  FlushInstructionCache(dst_code_bytes.start(), dst_code_bytes.size());

  std::unique_ptr<WasmCode> new_code{new WasmCode{
      this,                                     // native_module
      WasmCode::kAnonymousFuncIndex,            // index
      dst_code_bytes,                           // instructions
      stack_slots,                              // stack_slots
      0,                                        // tagged_parameter_slots
      safepoint_table_offset,                   // safepoint_table_offset
      handler_table_offset,                     // handler_table_offset
      constant_pool_offset,                     // constant_pool_offset
      code_comments_offset,                     // code_comments_offset
      instructions.size(),                      // unpadded_binary_size
      OwnedVector<ProtectedInstructionData>{},  // protected_instructions
      std::move(reloc_info),                    // reloc_info
      std::move(source_pos),                    // source positions
      kind,                                     // kind
      WasmCode::kOther}};                       // tier
581 582 583 584
  new_code->MaybePrint(name);
  new_code->Validate();

  return PublishCode(std::move(new_code));
585 586
}

587
std::unique_ptr<WasmCode> NativeModule::AddCode(
588
    uint32_t index, const CodeDesc& desc, uint32_t stack_slots,
589
    uint32_t tagged_parameter_slots,
590
    OwnedVector<trap_handler::ProtectedInstructionData> protected_instructions,
591
    OwnedVector<const byte> source_position_table, WasmCode::Kind kind,
592
    WasmCode::Tier tier) {
593 594 595 596 597 598 599 600 601 602 603
  return AddCodeWithCodeSpace(index, desc, stack_slots, tagged_parameter_slots,
                              std::move(protected_instructions),
                              std::move(source_position_table), kind, tier,
                              AllocateForCode(desc.instr_size));
}

std::unique_ptr<WasmCode> NativeModule::AddCodeWithCodeSpace(
    uint32_t index, const CodeDesc& desc, uint32_t stack_slots,
    uint32_t tagged_parameter_slots,
    OwnedVector<ProtectedInstructionData> protected_instructions,
    OwnedVector<const byte> source_position_table, WasmCode::Kind kind,
604
    WasmCode::Tier tier, Vector<uint8_t> dst_code_bytes) {
605
  OwnedVector<byte> reloc_info;
606
  if (desc.reloc_size > 0) {
607
    reloc_info = OwnedVector<byte>::New(desc.reloc_size);
608 609 610
    memcpy(reloc_info.start(), desc.buffer + desc.buffer_size - desc.reloc_size,
           desc.reloc_size);
  }
611

612 613 614
  // TODO(jgruber,v8:8758): Remove this translation. It exists only because
  // CodeDesc contains real offsets but WasmCode expects an offset of 0 to mean
  // 'empty'.
615 616 617 618 619 620 621 622 623 624
  const size_t safepoint_table_offset = static_cast<size_t>(
      desc.safepoint_table_size == 0 ? 0 : desc.safepoint_table_offset);
  const size_t handler_table_offset = static_cast<size_t>(
      desc.handler_table_size == 0 ? 0 : desc.handler_table_offset);
  const size_t constant_pool_offset =
      static_cast<size_t>(desc.constant_pool_offset);
  const size_t code_comments_offset =
      static_cast<size_t>(desc.code_comments_offset);
  const size_t instr_size = static_cast<size_t>(desc.instr_size);

625 626
  memcpy(dst_code_bytes.begin(), desc.buffer,
         static_cast<size_t>(desc.instr_size));
627

628
  // Apply the relocation delta by iterating over the RelocInfo.
629
  intptr_t delta = dst_code_bytes.begin() - desc.buffer;
630
  int mode_mask = RelocInfo::kApplyMask |
631
                  RelocInfo::ModeMask(RelocInfo::WASM_CALL) |
632
                  RelocInfo::ModeMask(RelocInfo::WASM_STUB_CALL);
633 634 635 636
  Address constant_pool_start =
      reinterpret_cast<Address>(dst_code_bytes.begin()) + constant_pool_offset;
  for (RelocIterator it(dst_code_bytes, reloc_info.as_vector(),
                        constant_pool_start, mode_mask);
637 638
       !it.done(); it.next()) {
    RelocInfo::Mode mode = it.rinfo()->rmode();
639 640 641 642 643 644
    if (RelocInfo::IsWasmCall(mode)) {
      uint32_t call_tag = it.rinfo()->wasm_call_tag();
      Address target = GetCallTargetForFunction(call_tag);
      it.rinfo()->set_wasm_call_address(target, SKIP_ICACHE_FLUSH);
    } else if (RelocInfo::IsWasmStubCall(mode)) {
      uint32_t stub_call_tag = it.rinfo()->wasm_call_tag();
645
      DCHECK_LT(stub_call_tag, WasmCode::kRuntimeStubCount);
646 647 648
      Address entry = runtime_stub_entry(
          static_cast<WasmCode::RuntimeStubId>(stub_call_tag));
      it.rinfo()->set_wasm_stub_call_address(entry, SKIP_ICACHE_FLUSH);
649 650 651 652
    } else {
      it.rinfo()->apply(delta);
    }
  }
653

654
  // Flush the i-cache after relocation.
655 656 657 658 659 660 661
  FlushInstructionCache(dst_code_bytes.start(), dst_code_bytes.size());

  std::unique_ptr<WasmCode> code{new WasmCode{
      this, index, dst_code_bytes, stack_slots, tagged_parameter_slots,
      safepoint_table_offset, handler_table_offset, constant_pool_offset,
      code_comments_offset, instr_size, std::move(protected_instructions),
      std::move(reloc_info), std::move(source_position_table), kind, tier}};
662 663 664
  code->MaybePrint();
  code->Validate();

665 666 667 668
  code->RegisterTrapHandlerData();

  return code;
}
669

670
WasmCode* NativeModule::PublishCode(std::unique_ptr<WasmCode> code) {
671
  base::MutexGuard lock(&allocation_mutex_);
672 673 674 675 676 677
  return PublishCodeLocked(std::move(code));
}

WasmCode* NativeModule::PublishCodeLocked(std::unique_ptr<WasmCode> code) {
  // The caller must hold the {allocation_mutex_}, thus we fail to lock it here.
  DCHECK(!allocation_mutex_.TryLock());
678 679 680
  // Skip publishing code if there is an active redirection to the interpreter
  // for the given function index, in order to preserve the redirection.
  if (!code->IsAnonymous() && !has_interpreter_redirection(code->index())) {
681 682 683 684 685 686 687 688 689 690
    DCHECK_LT(code->index(), num_functions());
    DCHECK_LE(module_->num_imported_functions, code->index());

    // Update code table, except for interpreter entries that would overwrite
    // existing code.
    uint32_t slot_idx = code->index() - module_->num_imported_functions;
    if (code->kind() != WasmCode::kInterpreterEntry ||
        code_table_[slot_idx] == nullptr) {
      code_table_[slot_idx] = code.get();
    }
691

692 693 694 695 696 697 698 699 700 701 702
    // Patch jump table.
    JumpTableAssembler::PatchJumpTableSlot(jump_table_->instruction_start(),
                                           slot_idx, code->instruction_start(),
                                           WasmCode::kFlushICache);
  }
  if (code->kind_ == WasmCode::Kind::kInterpreterEntry) {
    SetInterpreterRedirection(code->index());
  }
  WasmCode* ret = code.get();
  owned_code_.emplace_back(std::move(code));
  return ret;
703 704
}

705 706
WasmCode* NativeModule::AddDeserializedCode(
    uint32_t index, Vector<const byte> instructions, uint32_t stack_slots,
707 708 709
    uint32_t tagged_parameter_slots, size_t safepoint_table_offset,
    size_t handler_table_offset, size_t constant_pool_offset,
    size_t code_comments_offset, size_t unpadded_binary_size,
710
    OwnedVector<ProtectedInstructionData> protected_instructions,
711
    OwnedVector<const byte> reloc_info,
712 713
    OwnedVector<const byte> source_position_table, WasmCode::Kind kind,
    WasmCode::Tier tier) {
714 715
  Vector<uint8_t> dst_code_bytes = AllocateForCode(instructions.size());
  memcpy(dst_code_bytes.begin(), instructions.start(), instructions.size());
716

717
  std::unique_ptr<WasmCode> code{new WasmCode{
718
      this, index, dst_code_bytes, stack_slots, tagged_parameter_slots,
719 720
      safepoint_table_offset, handler_table_offset, constant_pool_offset,
      code_comments_offset, unpadded_binary_size,
721
      std::move(protected_instructions), std::move(reloc_info),
722 723 724
      std::move(source_position_table), kind, tier}};

  code->RegisterTrapHandlerData();
725 726 727 728

  // Note: we do not flush the i-cache here, since the code needs to be
  // relocated anyway. The caller is responsible for flushing the i-cache later.

729
  return PublishCode(std::move(code));
730 731
}

732
std::vector<WasmCode*> NativeModule::SnapshotCodeTable() const {
733
  base::MutexGuard lock(&allocation_mutex_);
734 735
  std::vector<WasmCode*> result;
  result.reserve(code_table().size());
736
  for (WasmCode* code : code_table()) result.push_back(code);
737 738 739
  return result;
}

740
WasmCode* NativeModule::CreateEmptyJumpTable(uint32_t jump_table_size) {
741
  // Only call this if we really need a jump table.
742
  DCHECK_LT(0, jump_table_size);
743
  Vector<uint8_t> code_space = AllocateForCode(jump_table_size);
744
  ZapCode(reinterpret_cast<Address>(code_space.begin()), code_space.size());
745 746 747
  std::unique_ptr<WasmCode> code{new WasmCode{
      this,                                     // native_module
      WasmCode::kAnonymousFuncIndex,            // index
748
      code_space,                               // instructions
749 750 751 752 753 754 755 756 757 758 759 760 761
      0,                                        // stack_slots
      0,                                        // tagged_parameter_slots
      0,                                        // safepoint_table_offset
      0,                                        // handler_table_offset
      jump_table_size,                          // constant_pool_offset
      jump_table_size,                          // code_comments_offset
      jump_table_size,                          // unpadded_binary_size
      OwnedVector<ProtectedInstructionData>{},  // protected_instructions
      OwnedVector<const uint8_t>{},             // reloc_info
      OwnedVector<const uint8_t>{},             // source_pos
      WasmCode::kJumpTable,                     // kind
      WasmCode::kOther}};                       // tier
  return PublishCode(std::move(code));
762 763
}

764
Vector<byte> NativeModule::AllocateForCode(size_t size) {
765
  base::MutexGuard lock(&allocation_mutex_);
766
  DCHECK_LT(0, size);
767
  v8::PageAllocator* page_allocator = GetPlatformPageAllocator();
768
  // This happens under a lock assumed by the caller.
769
  size = RoundUp<kCodeAlignment>(size);
770 771
  base::AddressRegion code_space = free_code_space_.Allocate(size);
  if (code_space.is_empty()) {
772 773 774 775 776
    if (!can_request_more_memory_) {
      V8::FatalProcessOutOfMemory(nullptr,
                                  "NativeModule::AllocateForCode reservation");
      UNREACHABLE();
    }
777

778 779
    Address hint = owned_code_space_.empty() ? kNullAddress
                                             : owned_code_space_.back().end();
780

781 782
    VirtualMemory new_mem = engine_->code_manager()->TryAllocate(
        size, reinterpret_cast<void*>(hint));
783 784 785 786 787
    if (!new_mem.IsReserved()) {
      V8::FatalProcessOutOfMemory(nullptr,
                                  "NativeModule::AllocateForCode reservation");
      UNREACHABLE();
    }
788 789
    engine_->code_manager()->AssignRanges(new_mem.address(), new_mem.end(),
                                          this);
790

791
    free_code_space_.Merge(new_mem.region());
792
    owned_code_space_.emplace_back(std::move(new_mem));
793 794
    code_space = free_code_space_.Allocate(size);
    DCHECK(!code_space.is_empty());
795
  }
796
  const Address page_size = page_allocator->AllocatePageSize();
797 798 799 800
  Address commit_start = RoundUp(code_space.begin(), page_size);
  Address commit_end = RoundUp(code_space.end(), page_size);
  // {commit_start} will be either code_space.start or the start of the next
  // page. {commit_end} will be the start of the page after the one in which
801 802 803 804 805 806 807
  // the allocation ends.
  // We start from an aligned start, and we know we allocated vmem in
  // page multiples.
  // We just need to commit what's not committed. The page in which we
  // start is already committed (or we start at the beginning of a page).
  // The end needs to be committed all through the end of the page.
  if (commit_start < commit_end) {
808 809 810
    committed_code_space_.fetch_add(commit_end - commit_start);
    // Committed code cannot grow bigger than maximum code space size.
    DCHECK_LE(committed_code_space_.load(), kMaxWasmCodeMemory);
811
#if V8_OS_WIN
812
    // On Windows, we cannot commit a region that straddles different
813 814
    // reservations of virtual memory. Because we bump-allocate, and because, if
    // we need more memory, we append that memory at the end of the
815 816
    // owned_code_space_ list, we traverse that list in reverse order to find
    // the reservation(s) that guide how to chunk the region to commit.
817 818 819 820 821
    for (auto& vmem : base::Reversed(owned_code_space_)) {
      if (commit_end <= vmem.address() || vmem.end() <= commit_start) continue;
      Address start = std::max(commit_start, vmem.address());
      Address end = std::min(commit_end, vmem.end());
      size_t commit_size = static_cast<size_t>(end - start);
822
      if (!engine_->code_manager()->Commit(start, commit_size)) {
823 824 825
        V8::FatalProcessOutOfMemory(nullptr,
                                    "NativeModule::AllocateForCode commit");
        UNREACHABLE();
826
      }
827 828 829 830 831
      // Opportunistically reduce the commit range. This might terminate the
      // loop early.
      if (commit_start == start) commit_start = end;
      if (commit_end == end) commit_end = start;
      if (commit_start >= commit_end) break;
832 833
    }
#else
834 835
    if (!engine_->code_manager()->Commit(commit_start,
                                         commit_end - commit_start)) {
836 837 838
      V8::FatalProcessOutOfMemory(nullptr,
                                  "NativeModule::AllocateForCode commit");
      UNREACHABLE();
839 840 841
    }
#endif
  }
842 843
  DCHECK(IsAligned(code_space.begin(), kCodeAlignment));
  allocated_code_space_.Merge(code_space);
844 845
  generated_code_size_.fetch_add(code_space.size(), std::memory_order_relaxed);

846 847 848
  TRACE_HEAP("Code alloc for %p: %" PRIxPTR ",+%zu\n", this, code_space.begin(),
             size);
  return {reinterpret_cast<byte*>(code_space.begin()), code_space.size()};
849 850
}

851 852 853
namespace {
class NativeModuleWireBytesStorage final : public WireBytesStorage {
 public:
854 855 856
  explicit NativeModuleWireBytesStorage(
      std::shared_ptr<OwnedVector<const uint8_t>> wire_bytes)
      : wire_bytes_(std::move(wire_bytes)) {}
857 858

  Vector<const uint8_t> GetCode(WireBytesRef ref) const final {
859
    return wire_bytes_->as_vector().SubVector(ref.offset(), ref.end_offset());
860 861 862
  }

 private:
863
  const std::shared_ptr<OwnedVector<const uint8_t>> wire_bytes_;
864 865 866
};
}  // namespace

867 868 869 870 871
void NativeModule::SetWireBytes(OwnedVector<const uint8_t> wire_bytes) {
  auto shared_wire_bytes =
      std::make_shared<OwnedVector<const uint8_t>>(std::move(wire_bytes));
  wire_bytes_ = shared_wire_bytes;
  if (!shared_wire_bytes->is_empty()) {
872
    compilation_state_->SetWireBytesStorage(
873 874
        std::make_shared<NativeModuleWireBytesStorage>(
            std::move(shared_wire_bytes)));
875 876 877
  }
}

878
WasmCode* NativeModule::Lookup(Address pc) const {
879
  base::MutexGuard lock(&allocation_mutex_);
880
  if (owned_code_.empty()) return nullptr;
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
  // First update the sorted portion counter.
  if (owned_code_sorted_portion_ == 0) ++owned_code_sorted_portion_;
  while (owned_code_sorted_portion_ < owned_code_.size() &&
         owned_code_[owned_code_sorted_portion_ - 1]->instruction_start() <=
             owned_code_[owned_code_sorted_portion_]->instruction_start()) {
    ++owned_code_sorted_portion_;
  }
  // Execute at most two rounds: First check whether the {pc} is within the
  // sorted portion of {owned_code_}. If it's not, then sort the whole vector
  // and retry.
  while (true) {
    auto iter =
        std::upper_bound(owned_code_.begin(), owned_code_.end(), pc,
                         [](Address pc, const std::unique_ptr<WasmCode>& code) {
                           DCHECK_NE(kNullAddress, pc);
                           DCHECK_NOT_NULL(code);
                           return pc < code->instruction_start();
                         });
    if (iter != owned_code_.begin()) {
      --iter;
      WasmCode* candidate = iter->get();
      DCHECK_NOT_NULL(candidate);
      if (candidate->contains(pc)) return candidate;
    }
    if (owned_code_sorted_portion_ == owned_code_.size()) return nullptr;
    std::sort(owned_code_.begin(), owned_code_.end(),
              [](const std::unique_ptr<WasmCode>& code1,
                 const std::unique_ptr<WasmCode>& code2) {
                return code1->instruction_start() < code2->instruction_start();
              });
    owned_code_sorted_portion_ = owned_code_.size();
  }
913 914
}

915 916 917 918 919 920 921
Address NativeModule::GetCallTargetForFunction(uint32_t func_index) const {
  // TODO(clemensh): Measure performance win of returning instruction start
  // directly if we have turbofan code. Downside: Redirecting functions (e.g.
  // for debugging) gets much harder.

  // Return the jump table slot for that function index.
  DCHECK_NOT_NULL(jump_table_);
922
  uint32_t slot_idx = func_index - module_->num_imported_functions;
923 924 925
  uint32_t slot_offset = JumpTableAssembler::SlotIndexToOffset(slot_idx);
  DCHECK_LT(slot_offset, jump_table_->instructions().size());
  return jump_table_->instruction_start() + slot_offset;
926 927
}

928 929
uint32_t NativeModule::GetFunctionIndexFromJumpTableSlot(
    Address slot_address) const {
930
  DCHECK(is_jump_table_slot(slot_address));
931
  uint32_t slot_offset =
932
      static_cast<uint32_t>(slot_address - jump_table_->instruction_start());
933
  uint32_t slot_idx = JumpTableAssembler::SlotOffsetToIndex(slot_offset);
934 935
  DCHECK_LT(slot_idx, module_->num_declared_functions);
  return module_->num_imported_functions + slot_idx;
936 937
}

938 939 940
void NativeModule::DisableTrapHandler() {
  // Switch {use_trap_handler_} from true to false.
  DCHECK(use_trap_handler_);
941
  use_trap_handler_ = kNoTrapHandler;
942 943 944

  // Clear the code table (just to increase the chances to hit an error if we
  // forget to re-add all code).
945
  uint32_t num_wasm_functions = module_->num_declared_functions;
946 947 948 949 950 951
  memset(code_table_.get(), 0, num_wasm_functions * sizeof(WasmCode*));

  // TODO(clemensh): Actually free the owned code, such that the memory can be
  // recycled.
}

952 953 954 955 956 957 958 959 960 961 962 963
const char* NativeModule::GetRuntimeStubName(Address runtime_stub_entry) const {
#define RETURN_NAME(Name)                                               \
  if (runtime_stub_entries_[WasmCode::k##Name] == runtime_stub_entry) { \
    return #Name;                                                       \
  }
#define RETURN_NAME_TRAP(Name) RETURN_NAME(ThrowWasm##Name)
  WASM_RUNTIME_STUB_LIST(RETURN_NAME, RETURN_NAME_TRAP)
#undef RETURN_NAME_TRAP
#undef RETURN_NAME
  return "<unknown>";
}

964 965
NativeModule::~NativeModule() {
  TRACE_HEAP("Deleting native module: %p\n", reinterpret_cast<void*>(this));
966 967
  // Cancel all background compilation before resetting any field of the
  // NativeModule or freeing anything.
968
  compilation_state_->AbortCompilation();
969
  engine_->FreeNativeModule(this);
970 971
}

972 973 974
WasmCodeManager::WasmCodeManager(WasmMemoryTracker* memory_tracker,
                                 size_t max_committed)
    : memory_tracker_(memory_tracker),
975 976
      remaining_uncommitted_code_space_(max_committed),
      critical_uncommitted_code_space_(max_committed / 2) {
977 978 979 980
  DCHECK_LE(max_committed, kMaxWasmCodeMemory);
}

bool WasmCodeManager::Commit(Address start, size_t size) {
981 982
  // TODO(v8:8462) Remove eager commit once perf supports remapping.
  if (FLAG_perf_prof) return true;
983
  DCHECK(IsAligned(start, AllocatePageSize()));
984
  DCHECK(IsAligned(size, AllocatePageSize()));
985 986 987
  // Reserve the size. Use CAS loop to avoid underflow on
  // {remaining_uncommitted_}. Temporary underflow would allow concurrent
  // threads to over-commit.
988
  size_t old_value = remaining_uncommitted_code_space_.load();
989 990
  while (true) {
    if (old_value < size) return false;
991 992
    if (remaining_uncommitted_code_space_.compare_exchange_weak(
            old_value, old_value - size)) {
993 994
      break;
    }
995
  }
996 997 998 999
  PageAllocator::Permission permission = FLAG_wasm_write_protect_code_memory
                                             ? PageAllocator::kReadWrite
                                             : PageAllocator::kReadWriteExecute;

1000 1001
  bool ret =
      SetPermissions(GetPlatformPageAllocator(), start, size, permission);
1002 1003 1004
  TRACE_HEAP("Setting rw permissions for %p:%p\n",
             reinterpret_cast<void*>(start),
             reinterpret_cast<void*>(start + size));
1005

1006 1007
  if (!ret) {
    // Highly unlikely.
1008
    remaining_uncommitted_code_space_.fetch_add(size);
1009 1010 1011 1012 1013
    return false;
  }
  return ret;
}

1014
void WasmCodeManager::AssignRanges(Address start, Address end,
1015
                                   NativeModule* native_module) {
1016
  base::MutexGuard lock(&native_modules_mutex_);
1017 1018 1019
  lookup_map_.insert(std::make_pair(start, std::make_pair(end, native_module)));
}

1020
VirtualMemory WasmCodeManager::TryAllocate(size_t size, void* hint) {
1021
  v8::PageAllocator* page_allocator = GetPlatformPageAllocator();
1022
  DCHECK_GT(size, 0);
1023
  size = RoundUp(size, page_allocator->AllocatePageSize());
1024 1025 1026 1027
  if (!memory_tracker_->ReserveAddressSpace(size,
                                            WasmMemoryTracker::kHardLimit)) {
    return {};
  }
1028
  if (hint == nullptr) hint = page_allocator->GetRandomMmapAddr();
1029

1030 1031
  VirtualMemory mem(page_allocator, size, hint,
                    page_allocator->AllocatePageSize());
1032 1033 1034
  if (!mem.IsReserved()) {
    memory_tracker_->ReleaseReservation(size);
    return {};
1035
  }
1036 1037 1038
  TRACE_HEAP("VMem alloc: %p:%p (%zu)\n",
             reinterpret_cast<void*>(mem.address()),
             reinterpret_cast<void*>(mem.end()), mem.size());
1039 1040 1041 1042 1043 1044

  // TODO(v8:8462) Remove eager commit once perf supports remapping.
  if (FLAG_perf_prof) {
    SetPermissions(GetPlatformPageAllocator(), mem.address(), mem.size(),
                   PageAllocator::kReadWriteExecute);
  }
1045
  return mem;
1046 1047
}

1048 1049
void WasmCodeManager::SetMaxCommittedMemoryForTesting(size_t limit) {
  remaining_uncommitted_code_space_.store(limit);
1050
  critical_uncommitted_code_space_.store(limit / 2);
1051 1052
}

1053
// static
1054
size_t WasmCodeManager::EstimateNativeModuleCodeSize(const WasmModule* module) {
1055
  constexpr size_t kCodeSizeMultiplier = 4;
1056 1057
  constexpr size_t kCodeOverhead = 32;     // for prologue, stack check, ...
  constexpr size_t kStaticCodeSize = 512;  // runtime stubs, ...
1058
  constexpr size_t kImportSize = 64 * kSystemPointerSize;
1059

1060
  size_t estimate = kStaticCodeSize;
1061
  for (auto& function : module->functions) {
1062
    estimate += kCodeOverhead + kCodeSizeMultiplier * function.code.length();
1063
  }
1064 1065 1066
  estimate +=
      JumpTableAssembler::SizeForNumberOfSlots(module->num_declared_functions);
  estimate += kImportSize * module->num_imported_functions;
1067 1068

  return estimate;
1069 1070
}

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
// static
size_t WasmCodeManager::EstimateNativeModuleNonCodeSize(
    const WasmModule* module) {
  size_t wasm_module_estimate = EstimateStoredSize(module);

  uint32_t num_wasm_functions = module->num_declared_functions;

  // TODO(wasm): Include wire bytes size.
  size_t native_module_estimate =
      sizeof(NativeModule) +                     /* NativeModule struct */
      (sizeof(WasmCode*) * num_wasm_functions) + /* code table size */
      (sizeof(WasmCode) * num_wasm_functions);   /* code object size */

  return wasm_module_estimate + native_module_estimate;
}

1087
std::shared_ptr<NativeModule> WasmCodeManager::NewNativeModule(
1088 1089 1090
    WasmEngine* engine, Isolate* isolate, const WasmFeatures& enabled,
    size_t code_size_estimate, bool can_request_more,
    std::shared_ptr<const WasmModule> module) {
1091
  DCHECK_EQ(this, isolate->wasm_engine()->code_manager());
1092 1093
  if (remaining_uncommitted_code_space_.load() <
      critical_uncommitted_code_space_.load()) {
1094 1095
    (reinterpret_cast<v8::Isolate*>(isolate))
        ->MemoryPressureNotification(MemoryPressureLevel::kCritical);
1096 1097
    critical_uncommitted_code_space_.store(
        remaining_uncommitted_code_space_.load() / 2);
1098 1099
  }

1100
  // If the code must be contiguous, reserve enough address space up front.
1101 1102
  size_t code_vmem_size =
      kRequiresCodeRange ? kMaxWasmCodeMemory : code_size_estimate;
1103
  // Try up to two times; getting rid of dead JSArrayBuffer allocations might
1104 1105 1106
  // require two GCs because the first GC maybe incremental and may have
  // floating garbage.
  static constexpr int kAllocationRetries = 2;
1107
  VirtualMemory code_space;
1108
  for (int retries = 0;; ++retries) {
1109 1110
    code_space = TryAllocate(code_vmem_size);
    if (code_space.IsReserved()) break;
1111 1112
    if (retries == kAllocationRetries) {
      V8::FatalProcessOutOfMemory(isolate, "WasmCodeManager::NewNativeModule");
1113
      UNREACHABLE();
1114 1115 1116 1117 1118 1119
    }
    // Run one GC, then try the allocation again.
    isolate->heap()->MemoryPressureNotification(MemoryPressureLevel::kCritical,
                                                true);
  }

1120 1121 1122
  Address start = code_space.address();
  size_t size = code_space.size();
  Address end = code_space.end();
1123 1124 1125 1126 1127
  std::shared_ptr<NativeModule> ret;
  new NativeModule(engine, enabled, can_request_more, std::move(code_space),
                   std::move(module), isolate->async_counters(), &ret);
  // The constructor initialized the shared_ptr.
  DCHECK_NOT_NULL(ret);
1128
  TRACE_HEAP("New NativeModule %p: Mem: %" PRIuPTR ",+%zu\n", ret.get(), start,
1129
             size);
1130 1131
  base::MutexGuard lock(&native_modules_mutex_);
  lookup_map_.insert(std::make_pair(start, std::make_pair(end, ret.get())));
1132
  return ret;
1133 1134
}

1135 1136
bool NativeModule::SetExecutable(bool executable) {
  if (is_executable_ == executable) return true;
1137
  TRACE_HEAP("Setting module %p as executable: %d.\n", this, executable);
1138

1139 1140
  v8::PageAllocator* page_allocator = GetPlatformPageAllocator();

1141
  if (FLAG_wasm_write_protect_code_memory) {
1142 1143
    PageAllocator::Permission permission =
        executable ? PageAllocator::kReadExecute : PageAllocator::kReadWrite;
1144
#if V8_OS_WIN
1145 1146 1147 1148 1149 1150 1151 1152 1153
    // On windows, we need to switch permissions per separate virtual memory
    // reservation. This is really just a problem when the NativeModule is
    // growable (meaning can_request_more_memory_). That's 32-bit in production,
    // or unittests.
    // For now, in that case, we commit at reserved memory granularity.
    // Technically, that may be a waste, because we may reserve more than we
    // use. On 32-bit though, the scarce resource is the address space -
    // committed or not.
    if (can_request_more_memory_) {
1154
      for (auto& vmem : owned_code_space_) {
1155 1156
        if (!SetPermissions(page_allocator, vmem.address(), vmem.size(),
                            permission)) {
1157 1158 1159 1160
          return false;
        }
        TRACE_HEAP("Set %p:%p to executable:%d\n", vmem.address(), vmem.end(),
                   executable);
1161
      }
1162 1163
      is_executable_ = executable;
      return true;
1164 1165
    }
#endif
1166
    for (auto& region : allocated_code_space_.regions()) {
1167
      // allocated_code_space_ is fine-grained, so we need to
1168
      // page-align it.
1169 1170 1171
      size_t region_size =
          RoundUp(region.size(), page_allocator->AllocatePageSize());
      if (!SetPermissions(page_allocator, region.begin(), region_size,
1172
                          permission)) {
1173 1174 1175
        return false;
      }
      TRACE_HEAP("Set %p:%p to executable:%d\n",
1176 1177
                 reinterpret_cast<void*>(region.begin()),
                 reinterpret_cast<void*>(region.end()), executable);
1178 1179 1180 1181 1182 1183
    }
  }
  is_executable_ = executable;
  return true;
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
void NativeModule::SampleCodeSize(
    Counters* counters, NativeModule::CodeSamplingTime sampling_time) const {
  size_t code_size = sampling_time == kSampling
                         ? committed_code_space()
                         : generated_code_size_.load(std::memory_order_relaxed);
  int code_size_mb = static_cast<int>(code_size / MB);
  Histogram* histogram = nullptr;
  switch (sampling_time) {
    case kAfterBaseline:
      histogram = counters->wasm_module_code_size_mb_after_baseline();
      break;
1195 1196 1197
    case kAfterTopTier:
      histogram = counters->wasm_module_code_size_mb_after_top_tier();
      break;
1198 1199 1200 1201 1202 1203 1204
    case kSampling:
      histogram = counters->wasm_module_code_size_mb();
      break;
  }
  histogram->AddSample(code_size_mb);
}

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
namespace {
WasmCode::Tier GetCodeTierForExecutionTier(ExecutionTier tier) {
  switch (tier) {
    case ExecutionTier::kInterpreter:
      return WasmCode::Tier::kOther;
    case ExecutionTier::kBaseline:
      return WasmCode::Tier::kLiftoff;
    case ExecutionTier::kOptimized:
      return WasmCode::Tier::kTurbofan;
  }
}

WasmCode::Kind GetCodeKindForExecutionTier(ExecutionTier tier) {
  switch (tier) {
    case ExecutionTier::kInterpreter:
      return WasmCode::Kind::kInterpreterEntry;
    case ExecutionTier::kBaseline:
    case ExecutionTier::kOptimized:
      return WasmCode::Kind::kFunction;
  }
}
}  // namespace

WasmCode* NativeModule::AddCompiledCode(WasmCompilationResult result) {
1229 1230
  return AddCompiledCode({&result, 1})[0];
}
1231

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
std::vector<WasmCode*> NativeModule::AddCompiledCode(
    Vector<WasmCompilationResult> results) {
  DCHECK(!results.is_empty());
  // First, allocate code space for all the results.
  size_t total_code_space = 0;
  for (auto& result : results) {
    DCHECK(result.succeeded());
    total_code_space += RoundUp<kCodeAlignment>(result.code_desc.instr_size);
  }
  Vector<byte> code_space = AllocateForCode(total_code_space);

  std::vector<std::unique_ptr<WasmCode>> generated_code;
  generated_code.reserve(results.size());

  // Now copy the generated code into the code space and relocate it.
  for (auto& result : results) {
    DCHECK_EQ(result.code_desc.buffer, result.instr_buffer.get());
    size_t code_size = RoundUp<kCodeAlignment>(result.code_desc.instr_size);
    Vector<byte> this_code_space = code_space.SubVector(0, code_size);
    code_space += code_size;
    generated_code.emplace_back(AddCodeWithCodeSpace(
        result.func_index, result.code_desc, result.frame_slot_count,
        result.tagged_parameter_slots, std::move(result.protected_instructions),
        std::move(result.source_positions),
        GetCodeKindForExecutionTier(result.result_tier),
        GetCodeTierForExecutionTier(result.result_tier), this_code_space));
  }
  DCHECK_EQ(0, code_space.size());

  // Under the {allocation_mutex_}, publish the code.
  std::vector<WasmCode*> returned_code;
  returned_code.reserve(results.size());
  {
    base::MutexGuard lock(&allocation_mutex_);
    for (auto& result : generated_code) {
      returned_code.push_back(PublishCodeLocked(std::move(result)));
    }
  }
1270

1271
  return returned_code;
1272 1273
}

1274 1275 1276 1277
void NativeModule::FreeCode(Vector<WasmCode* const> codes) {
  // TODO(clemensh): Implement.
}

1278
void WasmCodeManager::FreeNativeModule(NativeModule* native_module) {
1279
  base::MutexGuard lock(&native_modules_mutex_);
1280
  TRACE_HEAP("Freeing NativeModule %p\n", native_module);
1281 1282 1283 1284 1285 1286 1287 1288
  for (auto& code_space : native_module->owned_code_space_) {
    DCHECK(code_space.IsReserved());
    TRACE_HEAP("VMem Release: %" PRIxPTR ":%" PRIxPTR " (%zu)\n",
               code_space.address(), code_space.end(), code_space.size());
    lookup_map_.erase(code_space.address());
    memory_tracker_->ReleaseReservation(code_space.size());
    code_space.Free();
    DCHECK(!code_space.IsReserved());
1289
  }
1290
  native_module->owned_code_space_.clear();
1291

1292
  size_t code_size = native_module->committed_code_space_.load();
1293 1294
  DCHECK(IsAligned(code_size, AllocatePageSize()));
  remaining_uncommitted_code_space_.fetch_add(code_size);
1295 1296
  // Remaining code space cannot grow bigger than maximum code space size.
  DCHECK_LE(remaining_uncommitted_code_space_.load(), kMaxWasmCodeMemory);
1297 1298
}

1299
NativeModule* WasmCodeManager::LookupNativeModule(Address pc) const {
1300
  base::MutexGuard lock(&native_modules_mutex_);
1301 1302 1303 1304 1305
  if (lookup_map_.empty()) return nullptr;

  auto iter = lookup_map_.upper_bound(pc);
  if (iter == lookup_map_.begin()) return nullptr;
  --iter;
1306 1307
  Address region_start = iter->first;
  Address region_end = iter->second.first;
1308 1309 1310
  NativeModule* candidate = iter->second.second;

  DCHECK_NOT_NULL(candidate);
1311
  return region_start <= pc && pc < region_end ? candidate : nullptr;
1312 1313 1314 1315 1316
}

WasmCode* WasmCodeManager::LookupCode(Address pc) const {
  NativeModule* candidate = LookupNativeModule(pc);
  return candidate ? candidate->Lookup(pc) : nullptr;
1317 1318
}

1319 1320
size_t WasmCodeManager::remaining_uncommitted_code_space() const {
  return remaining_uncommitted_code_space_.load();
1321 1322
}

1323 1324
// TODO(v8:7424): Code protection scopes are not yet supported with shared code
// enabled and need to be revisited to work with --wasm-shared-code as well.
1325 1326 1327
NativeModuleModificationScope::NativeModuleModificationScope(
    NativeModule* native_module)
    : native_module_(native_module) {
1328 1329
  if (FLAG_wasm_write_protect_code_memory && native_module_ &&
      (native_module_->modification_scope_depth_++) == 0) {
1330 1331 1332
    bool success = native_module_->SetExecutable(false);
    CHECK(success);
  }
1333 1334 1335
}

NativeModuleModificationScope::~NativeModuleModificationScope() {
1336 1337
  if (FLAG_wasm_write_protect_code_memory && native_module_ &&
      (native_module_->modification_scope_depth_--) == 1) {
1338 1339 1340
    bool success = native_module_->SetExecutable(true);
    CHECK(success);
  }
1341 1342
}

1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
namespace {
thread_local WasmCodeRefScope* current_code_refs_scope = nullptr;

// Receives a vector by value which is modified in this function.
void DecrementRefCount(std::vector<WasmCode*> code_vec) {
  // Decrement the ref counter of all given code objects. Keep the ones whose
  // ref count drops to zero.
  auto remaining_elements_it = code_vec.begin();
  for (auto it = code_vec.begin(), end = code_vec.end(); it != end; ++it) {
    if ((*it)->DecRef()) *remaining_elements_it++ = *it;
  }
  code_vec.resize(remaining_elements_it - code_vec.begin());

  // Sort the vector by NativeModule, then by instruction start.
  std::sort(code_vec.begin(), code_vec.end(),
            [](const WasmCode* a, const WasmCode* b) {
              return a->native_module() == b->native_module()
                         ? a->instruction_start() < b->instruction_start()
                         : a->native_module() < b->native_module();
            });
  // For each native module, free all its code objects at once.
  auto range_begin = code_vec.begin();
  while (range_begin != code_vec.end()) {
    NativeModule* native_module = (*range_begin)->native_module();
    auto range_end = range_begin + 1;
    while (range_end < code_vec.end() &&
           (*range_end)->native_module() == native_module) {
      ++range_end;
    }
    size_t range_size = static_cast<size_t>(range_end - range_begin);
    Vector<WasmCode*> code_vec{&*range_begin, range_size};
    native_module->FreeCode(code_vec);
    range_begin = range_end;
  }
}

}  // namespace

WasmCodeRefScope::WasmCodeRefScope()
    : previous_scope_(current_code_refs_scope) {
  current_code_refs_scope = this;
}

WasmCodeRefScope::~WasmCodeRefScope() {
  DCHECK_EQ(this, current_code_refs_scope);
  current_code_refs_scope = previous_scope_;
  DecrementRefCount({code_ptrs_.begin(), code_ptrs_.end()});
}

// static
void WasmCodeRefScope::AddRef(WasmCode* code) {
  WasmCodeRefScope* current_scope = current_code_refs_scope;
  // TODO(clemensh): Remove early return, activate DCHECK instead.
  // DCHECK_NOT_NULL(current_scope);
  if (!current_scope) return;
  auto entry = current_scope->code_ptrs_.insert(code);
  // If we added a new entry, increment the ref counter.
  if (entry.second) code->IncRef();
}

1403 1404 1405
}  // namespace wasm
}  // namespace internal
}  // namespace v8
1406
#undef TRACE_HEAP