wasm-debug.cc 49.2 KB
Newer Older
1 2 3 4
// Copyright 2016 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 6
#include "src/wasm/wasm-debug.h"

7
#include <iomanip>
8 9
#include <unordered_map>

10
#include "src/base/optional.h"
11
#include "src/base/platform/wrappers.h"
12
#include "src/codegen/assembler-inl.h"
13
#include "src/common/assert-scope.h"
14
#include "src/compiler/wasm-compiler.h"
15
#include "src/debug/debug-evaluate.h"
16
#include "src/execution/frames-inl.h"
17
#include "src/heap/factory.h"
18
#include "src/wasm/baseline/liftoff-compiler.h"
19
#include "src/wasm/baseline/liftoff-register.h"
20
#include "src/wasm/module-decoder.h"
21
#include "src/wasm/value-type.h"
22
#include "src/wasm/wasm-code-manager.h"
23
#include "src/wasm/wasm-engine.h"
24
#include "src/wasm/wasm-limits.h"
25
#include "src/wasm/wasm-module.h"
26
#include "src/wasm/wasm-objects-inl.h"
27
#include "src/wasm/wasm-opcodes-inl.h"
28
#include "src/wasm/wasm-subtyping.h"
29
#include "src/wasm/wasm-value.h"
30
#include "src/zone/accounting-allocator.h"
31

32 33 34
namespace v8 {
namespace internal {
namespace wasm {
35

36 37
namespace {

38 39
using ImportExportKey = std::pair<ImportExportKindCode, uint32_t>;

40 41
enum ReturnLocation { kAfterBreakpoint, kAfterWasmCall };

42
Address FindNewPC(WasmFrame* frame, WasmCode* wasm_code, int byte_offset,
43
                  ReturnLocation return_location) {
44
  base::Vector<const uint8_t> new_pos_table = wasm_code->source_positions();
45 46

  DCHECK_LE(0, byte_offset);
47

48 49 50 51
  // Find the size of the call instruction by computing the distance from the
  // source position entry to the return address.
  WasmCode* old_code = frame->wasm_code();
  int pc_offset = static_cast<int>(frame->pc() - old_code->instruction_start());
52
  base::Vector<const uint8_t> old_pos_table = old_code->source_positions();
53 54 55 56 57 58 59 60 61
  SourcePositionTableIterator old_it(old_pos_table);
  int call_offset = -1;
  while (!old_it.done() && old_it.code_offset() < pc_offset) {
    call_offset = old_it.code_offset();
    old_it.Advance();
  }
  DCHECK_LE(0, call_offset);
  int call_instruction_size = pc_offset - call_offset;

62 63 64 65
  // If {return_location == kAfterBreakpoint} we search for the first code
  // offset which is marked as instruction (i.e. not the breakpoint).
  // If {return_location == kAfterWasmCall} we return the last code offset
  // associated with the byte offset.
66 67 68 69
  SourcePositionTableIterator it(new_pos_table);
  while (!it.done() && it.source_position().ScriptOffset() != byte_offset) {
    it.Advance();
  }
70 71 72
  if (return_location == kAfterBreakpoint) {
    while (!it.is_statement()) it.Advance();
    DCHECK_EQ(byte_offset, it.source_position().ScriptOffset());
73 74
    return wasm_code->instruction_start() + it.code_offset() +
           call_instruction_size;
75 76 77 78 79 80 81 82
  }

  DCHECK_EQ(kAfterWasmCall, return_location);
  int code_offset;
  do {
    code_offset = it.code_offset();
    it.Advance();
  } while (!it.done() && it.source_position().ScriptOffset() == byte_offset);
83
  return wasm_code->instruction_start() + code_offset + call_instruction_size;
84 85
}

86 87
}  // namespace

88 89 90 91 92 93 94 95
void DebugSideTable::Print(std::ostream& os) const {
  os << "Debug side table (" << num_locals_ << " locals, " << entries_.size()
     << " entries):\n";
  for (auto& entry : entries_) entry.Print(os);
  os << "\n";
}

void DebugSideTable::Entry::Print(std::ostream& os) const {
96 97 98
  os << std::setw(6) << std::hex << pc_offset_ << std::dec << " stack height "
     << stack_height_ << " [";
  for (auto& value : changed_values_) {
99
    os << " " << value.type.name() << ":";
100
    switch (value.storage) {
101 102 103 104 105 106 107 108 109 110 111 112 113 114
      case kConstant:
        os << "const#" << value.i32_const;
        break;
      case kRegister:
        os << "reg#" << value.reg_code;
        break;
      case kStack:
        os << "stack#" << value.stack_offset;
        break;
    }
  }
  os << " ]\n";
}

115 116 117 118 119
class DebugInfoImpl {
 public:
  explicit DebugInfoImpl(NativeModule* native_module)
      : native_module_(native_module) {}

120 121 122
  DebugInfoImpl(const DebugInfoImpl&) = delete;
  DebugInfoImpl& operator=(const DebugInfoImpl&) = delete;

123 124
  int GetNumLocals(Address pc) {
    FrameInspectionScope scope(this, pc);
125
    if (!scope.is_inspectable()) return 0;
126 127 128
    return scope.debug_side_table->num_locals();
  }

129
  WasmValue GetLocalValue(int local, Address pc, Address fp,
130
                          Address debug_break_fp, Isolate* isolate) {
131
    FrameInspectionScope scope(this, pc);
132
    return GetValue(scope.debug_side_table, scope.debug_side_table_entry, local,
133
                    fp, debug_break_fp, isolate);
134 135
  }

136 137
  int GetStackDepth(Address pc) {
    FrameInspectionScope scope(this, pc);
138
    if (!scope.is_inspectable()) return 0;
139 140 141
    int num_locals = scope.debug_side_table->num_locals();
    int stack_height = scope.debug_side_table_entry->stack_height();
    return stack_height - num_locals;
142 143
  }

144
  WasmValue GetStackValue(int index, Address pc, Address fp,
145
                          Address debug_break_fp, Isolate* isolate) {
146
    FrameInspectionScope scope(this, pc);
147 148
    int num_locals = scope.debug_side_table->num_locals();
    int value_count = scope.debug_side_table_entry->stack_height();
149
    if (num_locals + index >= value_count) return {};
150
    return GetValue(scope.debug_side_table, scope.debug_side_table_entry,
151
                    num_locals + index, fp, debug_break_fp, isolate);
152 153
  }

154 155 156 157 158 159
  const WasmFunction& GetFunctionAtAddress(Address pc) {
    FrameInspectionScope scope(this, pc);
    auto* module = native_module_->module();
    return module->functions[scope.code->index()];
  }

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  WireBytesRef GetExportName(ImportExportKindCode kind, uint32_t index) {
    base::MutexGuard guard(&mutex_);
    if (!export_names_) {
      export_names_ =
          std::make_unique<std::map<ImportExportKey, WireBytesRef>>();
      for (auto exp : native_module_->module()->export_table) {
        auto exp_key = std::make_pair(exp.kind, exp.index);
        if (export_names_->find(exp_key) != export_names_->end()) continue;
        export_names_->insert(std::make_pair(exp_key, exp.name));
      }
    }
    auto it = export_names_->find(std::make_pair(kind, index));
    if (it != export_names_->end()) return it->second;
    return {};
  }

  std::pair<WireBytesRef, WireBytesRef> GetImportName(ImportExportKindCode kind,
                                                      uint32_t index) {
    base::MutexGuard guard(&mutex_);
    if (!import_names_) {
      import_names_ = std::make_unique<
          std::map<ImportExportKey, std::pair<WireBytesRef, WireBytesRef>>>();
      for (auto imp : native_module_->module()->import_table) {
        import_names_->insert(
            std::make_pair(std::make_pair(imp.kind, imp.index),
                           std::make_pair(imp.module_name, imp.field_name)));
      }
    }
    auto it = import_names_->find(std::make_pair(kind, index));
    if (it != import_names_->end()) return it->second;
    return {};
  }

193 194 195 196 197 198 199 200 201
  WireBytesRef GetTypeName(int type_index) {
    base::MutexGuard guard(&mutex_);
    if (!type_names_) {
      type_names_ = std::make_unique<NameMap>(DecodeNameMap(
          native_module_->wire_bytes(), NameSectionKindCode::kType));
    }
    return type_names_->GetName(type_index);
  }

202 203 204
  WireBytesRef GetLocalName(int func_index, int local_index) {
    base::MutexGuard guard(&mutex_);
    if (!local_names_) {
205 206
      local_names_ = std::make_unique<IndirectNameMap>(DecodeIndirectNameMap(
          native_module_->wire_bytes(), NameSectionKindCode::kLocal));
207 208 209 210
    }
    return local_names_->GetName(func_index, local_index);
  }

211 212 213 214 215 216 217 218 219
  WireBytesRef GetFieldName(int struct_index, int field_index) {
    base::MutexGuard guard(&mutex_);
    if (!field_names_) {
      field_names_ = std::make_unique<IndirectNameMap>(DecodeIndirectNameMap(
          native_module_->wire_bytes(), NameSectionKindCode::kField));
    }
    return field_names_->GetName(struct_index, field_index);
  }

220 221
  // If the frame position is not in the list of breakpoints, return that
  // position. Return 0 otherwise.
222 223
  // This is used to generate a "dead breakpoint" in Liftoff, which is necessary
  // for OSR to find the correct return address.
224
  int DeadBreakpoint(WasmFrame* frame, base::Vector<const int> breakpoints) {
225 226
    const auto& function =
        native_module_->module()->functions[frame->function_index()];
227 228 229 230 231 232 233
    int offset = frame->position() - function.code.offset();
    if (std::binary_search(breakpoints.begin(), breakpoints.end(), offset)) {
      return 0;
    }
    return offset;
  }

234 235
  // Find the dead breakpoint (see above) for the top wasm frame, if that frame
  // is in the function of the given index.
236
  int DeadBreakpoint(int func_index, base::Vector<const int> breakpoints,
237 238 239 240 241 242 243 244
                     Isolate* isolate) {
    StackTraceFrameIterator it(isolate);
    if (it.done() || !it.is_wasm()) return 0;
    auto* wasm_frame = WasmFrame::cast(it.frame());
    if (static_cast<int>(wasm_frame->function_index()) != func_index) return 0;
    return DeadBreakpoint(wasm_frame, breakpoints);
  }

245
  WasmCode* RecompileLiftoffWithBreakpoints(int func_index,
246
                                            base::Vector<const int> offsets,
247
                                            int dead_breakpoint) {
248
    DCHECK(!mutex_.TryLock());  // Mutex is held externally.
249

250 251 252 253
    ForDebugging for_debugging = offsets.size() == 1 && offsets[0] == 0
                                     ? kForStepping
                                     : kWithBreakpoints;

254 255 256 257 258 259 260 261 262
    // Check the cache first.
    for (auto begin = cached_debugging_code_.begin(), it = begin,
              end = cached_debugging_code_.end();
         it != end; ++it) {
      if (it->func_index == func_index &&
          it->breakpoint_offsets.as_vector() == offsets &&
          it->dead_breakpoint == dead_breakpoint) {
        // Rotate the cache entry to the front (for LRU).
        for (; it != begin; --it) std::iter_swap(it, it - 1);
263 264 265 266
        if (for_debugging == kWithBreakpoints) {
          // Re-install the code, in case it was replaced in the meantime.
          native_module_->ReinstallDebugCode(it->code);
        }
267 268 269 270
        return it->code;
      }
    }

271
    // Recompile the function with Liftoff, setting the new breakpoints.
272
    // Not thread-safe. The caller is responsible for locking {mutex_}.
273 274
    CompilationEnv env = native_module_->CreateCompilationEnv();
    auto* function = &native_module_->module()->functions[func_index];
275
    base::Vector<const uint8_t> wire_bytes = native_module_->wire_bytes();
276 277 278
    FunctionBody body{function->sig, function->code.offset(),
                      wire_bytes.begin() + function->code.offset(),
                      wire_bytes.begin() + function->code.end_offset()};
279
    std::unique_ptr<DebugSideTable> debug_sidetable;
280

281 282
    // Debug side tables for stepping are generated lazily.
    bool generate_debug_sidetable = for_debugging == kWithBreakpoints;
283 284
    Counters* counters = nullptr;
    WasmFeatures unused_detected;
285
    WasmCompilationResult result = ExecuteLiftoffCompilation(
286 287 288
        &env, body, func_index, for_debugging, counters, &unused_detected,
        offsets, generate_debug_sidetable ? &debug_sidetable : nullptr,
        dead_breakpoint);
289 290 291
    // Liftoff compilation failure is a FATAL error. We rely on complete Liftoff
    // support for debugging.
    if (!result.succeeded()) FATAL("Liftoff compilation failed");
292
    DCHECK_EQ(generate_debug_sidetable, debug_sidetable != nullptr);
293

294 295 296
    WasmCode* new_code = native_module_->PublishCode(
        native_module_->AddCompiledCode(std::move(result)));

297
    DCHECK(new_code->is_inspectable());
298
    if (generate_debug_sidetable) {
299 300 301 302
      base::MutexGuard lock(&debug_side_tables_mutex_);
      DCHECK_EQ(0, debug_side_tables_.count(new_code));
      debug_side_tables_.emplace(new_code, std::move(debug_sidetable));
    }
303

304 305 306
    // Insert new code into the cache. Insert before existing elements for LRU.
    cached_debugging_code_.insert(
        cached_debugging_code_.begin(),
307
        CachedDebuggingCode{func_index, base::OwnedVector<int>::Of(offsets),
308 309 310 311 312 313 314 315 316 317 318 319 320
                            dead_breakpoint, new_code});
    // Increase the ref count (for the cache entry).
    new_code->IncRef();
    // Remove exceeding element.
    if (cached_debugging_code_.size() > kMaxCachedDebuggingCode) {
      // Put the code in the surrounding CodeRefScope to delay deletion until
      // after the mutex is released.
      WasmCodeRefScope::AddRef(cached_debugging_code_.back().code);
      cached_debugging_code_.back().code->DecRefOnLiveCode();
      cached_debugging_code_.pop_back();
    }
    DCHECK_GE(kMaxCachedDebuggingCode, cached_debugging_code_.size());

321
    return new_code;
322 323
  }

324
  void SetBreakpoint(int func_index, int offset, Isolate* isolate) {
325 326 327
    // Put the code ref scope outside of the mutex, so we don't unnecessarily
    // hold the mutex while freeing code.
    WasmCodeRefScope wasm_code_ref_scope;
328

329 330 331
    // Hold the mutex while modifying breakpoints, to ensure consistency when
    // multiple isolates set/remove breakpoints at the same time.
    base::MutexGuard guard(&mutex_);
332

333 334 335
    // offset == 0 indicates flooding and should not happen here.
    DCHECK_NE(0, offset);

336 337 338 339
    // Get the set of previously set breakpoints, to check later whether a new
    // breakpoint was actually added.
    std::vector<int> all_breakpoints = FindAllBreakpoints(func_index);

340 341 342 343 344 345 346 347
    auto& isolate_data = per_isolate_data_[isolate];
    std::vector<int>& breakpoints =
        isolate_data.breakpoints_per_function[func_index];
    auto insertion_point =
        std::lower_bound(breakpoints.begin(), breakpoints.end(), offset);
    if (insertion_point != breakpoints.end() && *insertion_point == offset) {
      // The breakpoint is already set for this isolate.
      return;
348
    }
349 350
    breakpoints.insert(insertion_point, offset);

351 352 353 354 355 356
    DCHECK(std::is_sorted(all_breakpoints.begin(), all_breakpoints.end()));
    // Find the insertion position within {all_breakpoints}.
    insertion_point = std::lower_bound(all_breakpoints.begin(),
                                       all_breakpoints.end(), offset);
    bool breakpoint_exists =
        insertion_point != all_breakpoints.end() && *insertion_point == offset;
357 358 359
    // If the breakpoint was already set before, then we can just reuse the old
    // code. Otherwise, recompile it. In any case, rewrite this isolate's stack
    // to make sure that it uses up-to-date code containing the breakpoint.
360
    WasmCode* new_code;
361
    if (breakpoint_exists) {
362 363
      new_code = native_module_->GetCode(func_index);
    } else {
364
      all_breakpoints.insert(insertion_point, offset);
365
      int dead_breakpoint =
366
          DeadBreakpoint(func_index, base::VectorOf(all_breakpoints), isolate);
367
      new_code = RecompileLiftoffWithBreakpoints(
368
          func_index, base::VectorOf(all_breakpoints), dead_breakpoint);
369 370
    }
    UpdateReturnAddresses(isolate, new_code, isolate_data.stepping_frame);
371 372 373 374 375 376 377 378 379 380 381
  }

  std::vector<int> FindAllBreakpoints(int func_index) {
    DCHECK(!mutex_.TryLock());  // Mutex must be held externally.
    std::set<int> breakpoints;
    for (auto& data : per_isolate_data_) {
      auto it = data.second.breakpoints_per_function.find(func_index);
      if (it == data.second.breakpoints_per_function.end()) continue;
      for (int offset : it->second) breakpoints.insert(offset);
    }
    return {breakpoints.begin(), breakpoints.end()};
382 383
  }

384
  void UpdateBreakpoints(int func_index, base::Vector<int> breakpoints,
385 386
                         Isolate* isolate, StackFrameId stepping_frame,
                         int dead_breakpoint) {
387
    DCHECK(!mutex_.TryLock());  // Mutex is held externally.
388 389
    WasmCode* new_code = RecompileLiftoffWithBreakpoints(
        func_index, breakpoints, dead_breakpoint);
390
    UpdateReturnAddresses(isolate, new_code, stepping_frame);
391 392
  }

393
  void FloodWithBreakpoints(WasmFrame* frame, ReturnLocation return_location) {
394
    // 0 is an invalid offset used to indicate flooding.
395
    constexpr int kFloodingBreakpoints[] = {0};
396 397
    DCHECK(frame->wasm_code()->is_liftoff());
    // Generate an additional source position for the current byte offset.
398
    base::MutexGuard guard(&mutex_);
399
    WasmCode* new_code = RecompileLiftoffWithBreakpoints(
400
        frame->function_index(), base::ArrayVector(kFloodingBreakpoints), 0);
401
    UpdateReturnAddress(frame, new_code, return_location);
402 403

    per_isolate_data_[frame->isolate()].stepping_frame = frame->id();
404 405
  }

406 407 408 409 410 411 412 413
  bool PrepareStep(WasmFrame* frame) {
    WasmCodeRefScope wasm_code_ref_scope;
    wasm::WasmCode* code = frame->wasm_code();
    if (!code->is_liftoff()) return false;  // Cannot step in TurboFan code.
    if (IsAtReturn(frame)) return false;    // Will return after this step.
    FloodWithBreakpoints(frame, kAfterBreakpoint);
    return true;
  }
414

415 416 417 418 419
  void PrepareStepOutTo(WasmFrame* frame) {
    WasmCodeRefScope wasm_code_ref_scope;
    wasm::WasmCode* code = frame->wasm_code();
    if (!code->is_liftoff()) return;  // Cannot step out to TurboFan code.
    FloodWithBreakpoints(frame, kAfterWasmCall);
420 421
  }

422 423 424 425 426 427 428
  void ClearStepping(WasmFrame* frame) {
    WasmCodeRefScope wasm_code_ref_scope;
    base::MutexGuard guard(&mutex_);
    auto* code = frame->wasm_code();
    if (code->for_debugging() != kForStepping) return;
    int func_index = code->index();
    std::vector<int> breakpoints = FindAllBreakpoints(func_index);
429
    int dead_breakpoint = DeadBreakpoint(frame, base::VectorOf(breakpoints));
430
    WasmCode* new_code = RecompileLiftoffWithBreakpoints(
431
        func_index, base::VectorOf(breakpoints), dead_breakpoint);
432 433 434
    UpdateReturnAddress(frame, new_code, kAfterBreakpoint);
  }

435 436 437 438 439
  void ClearStepping(Isolate* isolate) {
    base::MutexGuard guard(&mutex_);
    auto it = per_isolate_data_.find(isolate);
    if (it != per_isolate_data_.end()) it->second.stepping_frame = NO_ID;
  }
440

441
  bool IsStepping(WasmFrame* frame) {
442
    Isolate* isolate = frame->wasm_instance().GetIsolate();
443
    if (isolate->debug()->last_step_action() == StepInto) return true;
444 445 446 447
    base::MutexGuard guard(&mutex_);
    auto it = per_isolate_data_.find(isolate);
    return it != per_isolate_data_.end() &&
           it->second.stepping_frame == frame->id();
448 449
  }

450
  void RemoveBreakpoint(int func_index, int position, Isolate* isolate) {
451 452 453 454 455 456 457 458 459 460
    // Put the code ref scope outside of the mutex, so we don't unnecessarily
    // hold the mutex while freeing code.
    WasmCodeRefScope wasm_code_ref_scope;

    // Hold the mutex while modifying breakpoints, to ensure consistency when
    // multiple isolates set/remove breakpoints at the same time.
    base::MutexGuard guard(&mutex_);

    const auto& function = native_module_->module()->functions[func_index];
    int offset = position - function.code.offset();
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475
    auto& isolate_data = per_isolate_data_[isolate];
    std::vector<int>& breakpoints =
        isolate_data.breakpoints_per_function[func_index];
    DCHECK_LT(0, offset);
    auto insertion_point =
        std::lower_bound(breakpoints.begin(), breakpoints.end(), offset);
    if (insertion_point == breakpoints.end()) return;
    if (*insertion_point != offset) return;
    breakpoints.erase(insertion_point);

    std::vector<int> remaining = FindAllBreakpoints(func_index);
    // If the breakpoint is still set in another isolate, don't remove it.
    DCHECK(std::is_sorted(remaining.begin(), remaining.end()));
    if (std::binary_search(remaining.begin(), remaining.end(), offset)) return;
476
    int dead_breakpoint =
477 478
        DeadBreakpoint(func_index, base::VectorOf(remaining), isolate);
    UpdateBreakpoints(func_index, base::VectorOf(remaining), isolate,
479
                      isolate_data.stepping_frame, dead_breakpoint);
480 481
  }

482
  void RemoveDebugSideTables(base::Vector<WasmCode* const> codes) {
483
    base::MutexGuard guard(&debug_side_tables_mutex_);
484 485
    for (auto* code : codes) {
      debug_side_tables_.erase(code);
486
    }
487 488
  }

489
  DebugSideTable* GetDebugSideTableIfExists(const WasmCode* code) const {
490
    base::MutexGuard guard(&debug_side_tables_mutex_);
491 492 493 494
    auto it = debug_side_tables_.find(code);
    return it == debug_side_tables_.end() ? nullptr : it->second.get();
  }

495 496 497 498 499 500 501 502 503 504 505 506
  static bool HasRemovedBreakpoints(const std::vector<int>& removed,
                                    const std::vector<int>& remaining) {
    DCHECK(std::is_sorted(remaining.begin(), remaining.end()));
    for (int offset : removed) {
      // Return true if we removed a breakpoint which is not part of remaining.
      if (!std::binary_search(remaining.begin(), remaining.end(), offset)) {
        return true;
      }
    }
    return false;
  }

507
  void RemoveIsolate(Isolate* isolate) {
508 509 510 511
    // Put the code ref scope outside of the mutex, so we don't unnecessarily
    // hold the mutex while freeing code.
    WasmCodeRefScope wasm_code_ref_scope;

512
    base::MutexGuard guard(&mutex_);
513 514
    auto per_isolate_data_it = per_isolate_data_.find(isolate);
    if (per_isolate_data_it == per_isolate_data_.end()) return;
515 516 517 518
    std::unordered_map<int, std::vector<int>> removed_per_function =
        std::move(per_isolate_data_it->second.breakpoints_per_function);
    per_isolate_data_.erase(per_isolate_data_it);
    for (auto& entry : removed_per_function) {
519 520 521 522
      int func_index = entry.first;
      std::vector<int>& removed = entry.second;
      std::vector<int> remaining = FindAllBreakpoints(func_index);
      if (HasRemovedBreakpoints(removed, remaining)) {
523 524
        RecompileLiftoffWithBreakpoints(func_index, base::VectorOf(remaining),
                                        0);
525 526
      }
    }
527 528
  }

529
 private:
530
  struct FrameInspectionScope {
531
    FrameInspectionScope(DebugInfoImpl* debug_info, Address pc)
532
        : code(wasm::GetWasmCodeManager()->LookupCode(pc)),
533
          pc_offset(static_cast<int>(pc - code->instruction_start())),
534 535 536
          debug_side_table(code->is_inspectable()
                               ? debug_info->GetDebugSideTable(code)
                               : nullptr),
537 538
          debug_side_table_entry(debug_side_table
                                     ? debug_side_table->GetEntry(pc_offset)
539 540 541 542 543
                                     : nullptr) {
      DCHECK_IMPLIES(code->is_inspectable(), debug_side_table_entry != nullptr);
    }

    bool is_inspectable() const { return debug_side_table_entry; }
544 545 546 547 548 549 550 551

    wasm::WasmCodeRefScope wasm_code_ref_scope;
    wasm::WasmCode* code;
    int pc_offset;
    const DebugSideTable* debug_side_table;
    const DebugSideTable::Entry* debug_side_table_entry;
  };

552
  const DebugSideTable* GetDebugSideTable(WasmCode* code) {
553
    DCHECK(code->is_inspectable());
554 555 556
    {
      // Only hold the mutex temporarily. We can't hold it while generating the
      // debug side table, because compilation takes the {NativeModule} lock.
557
      base::MutexGuard guard(&debug_side_tables_mutex_);
558 559
      auto it = debug_side_tables_.find(code);
      if (it != debug_side_tables_.end()) return it->second.get();
560 561 562
    }

    // Otherwise create the debug side table now.
563
    std::unique_ptr<DebugSideTable> debug_side_table =
564
        GenerateLiftoffDebugSideTable(code);
565
    DebugSideTable* ret = debug_side_table.get();
566

567 568
    // Check cache again, maybe another thread concurrently generated a debug
    // side table already.
569
    {
570
      base::MutexGuard guard(&debug_side_tables_mutex_);
571 572 573
      auto& slot = debug_side_tables_[code];
      if (slot != nullptr) return slot.get();
      slot = std::move(debug_side_table);
574
    }
575 576 577

    // Print the code together with the debug table, if requested.
    code->MaybePrint();
578
    return ret;
579 580 581 582
  }

  // Get the value of a local (including parameters) or stack value. Stack
  // values follow the locals in the same index space.
583 584
  WasmValue GetValue(const DebugSideTable* debug_side_table,
                     const DebugSideTable::Entry* debug_side_table_entry,
585
                     int index, Address stack_frame_base,
586
                     Address debug_break_fp, Isolate* isolate) const {
587 588 589
    const auto* value =
        debug_side_table->FindValue(debug_side_table_entry, index);
    if (value->is_constant()) {
590 591 592
      DCHECK(value->type == kWasmI32 || value->type == kWasmI64);
      return value->type == kWasmI32 ? WasmValue(value->i32_const)
                                     : WasmValue(int64_t{value->i32_const});
593
    }
594

595 596
    if (value->is_register()) {
      auto reg = LiftoffRegister::from_liftoff_code(value->reg_code);
597 598 599 600 601 602
      auto gp_addr = [debug_break_fp](Register reg) {
        return debug_break_fp +
               WasmDebugBreakFrameConstants::GetPushedGpRegisterOffset(
                   reg.code());
      };
      if (reg.is_gp_pair()) {
603
        DCHECK_EQ(kWasmI64, value->type);
604 605 606 607 608 609
        uint32_t low_word = ReadUnalignedValue<uint32_t>(gp_addr(reg.low_gp()));
        uint32_t high_word =
            ReadUnalignedValue<uint32_t>(gp_addr(reg.high_gp()));
        return WasmValue((uint64_t{high_word} << 32) | low_word);
      }
      if (reg.is_gp()) {
610 611 612 613 614 615 616 617 618 619 620
        if (value->type == kWasmI32) {
          return WasmValue(ReadUnalignedValue<uint32_t>(gp_addr(reg.gp())));
        } else if (value->type == kWasmI64) {
          return WasmValue(ReadUnalignedValue<uint64_t>(gp_addr(reg.gp())));
        } else if (value->type.is_reference()) {
          Handle<Object> obj(
              Object(ReadUnalignedValue<Address>(gp_addr(reg.gp()))), isolate);
          return WasmValue(obj, value->type);
        } else {
          UNREACHABLE();
        }
621
      }
622
      DCHECK(reg.is_fp() || reg.is_fp_pair());
623 624 625 626 627 628
      // ifdef here to workaround unreachable code for is_fp_pair.
#ifdef V8_TARGET_ARCH_ARM
      int code = reg.is_fp_pair() ? reg.low_fp().code() : reg.fp().code();
#else
      int code = reg.fp().code();
#endif
629 630
      Address spilled_addr =
          debug_break_fp +
631
          WasmDebugBreakFrameConstants::GetPushedFpRegisterOffset(code);
632
      if (value->type == kWasmF32) {
633
        return WasmValue(ReadUnalignedValue<float>(spilled_addr));
634
      } else if (value->type == kWasmF64) {
635
        return WasmValue(ReadUnalignedValue<double>(spilled_addr));
636
      } else if (value->type == kWasmS128) {
637 638 639 640 641
        return WasmValue(Simd128(ReadUnalignedValue<int16>(spilled_addr)));
      } else {
        // All other cases should have been handled above.
        UNREACHABLE();
      }
642 643
    }

644
    // Otherwise load the value from the stack.
645
    Address stack_address = stack_frame_base - value->stack_offset;
646
    switch (value->type.kind()) {
647
      case kI32:
648
        return WasmValue(ReadUnalignedValue<int32_t>(stack_address));
649
      case kI64:
650
        return WasmValue(ReadUnalignedValue<int64_t>(stack_address));
651
      case kF32:
652
        return WasmValue(ReadUnalignedValue<float>(stack_address));
653
      case kF64:
654
        return WasmValue(ReadUnalignedValue<double>(stack_address));
655
      case kS128:
656
        return WasmValue(Simd128(ReadUnalignedValue<int16>(stack_address)));
657 658 659 660 661 662 663
      case kRef:
      case kOptRef:
      case kRtt:
      case kRttWithDepth: {
        Handle<Object> obj(Object(ReadUnalignedValue<Address>(stack_address)),
                           isolate);
        return WasmValue(obj, value->type);
664
      }
665 666
      case kI8:
      case kI16:
667
      case kVoid:
668 669
      case kBottom:
        UNREACHABLE();
670 671 672
    }
  }

673 674 675
  // After installing a Liftoff code object with a different set of breakpoints,
  // update return addresses on the stack so that execution resumes in the new
  // code. The frame layout itself should be independent of breakpoints.
676 677
  void UpdateReturnAddresses(Isolate* isolate, WasmCode* new_code,
                             StackFrameId stepping_frame) {
678 679 680 681 682
    // The first return location is after the breakpoint, others are after wasm
    // calls.
    ReturnLocation return_location = kAfterBreakpoint;
    for (StackTraceFrameIterator it(isolate); !it.done();
         it.Advance(), return_location = kAfterWasmCall) {
683
      // We still need the flooded function for stepping.
684
      if (it.frame()->id() == stepping_frame) continue;
685
      if (!it.is_wasm()) continue;
686
      WasmFrame* frame = WasmFrame::cast(it.frame());
687 688
      if (frame->native_module() != new_code->native_module()) continue;
      if (frame->function_index() != new_code->index()) continue;
689
      if (!frame->wasm_code()->is_liftoff()) continue;
690
      UpdateReturnAddress(frame, new_code, return_location);
691 692 693
    }
  }

694
  void UpdateReturnAddress(WasmFrame* frame, WasmCode* new_code,
695 696 697 698 699
                           ReturnLocation return_location) {
    DCHECK(new_code->is_liftoff());
    DCHECK_EQ(frame->function_index(), new_code->index());
    DCHECK_EQ(frame->native_module(), new_code->native_module());
    DCHECK(frame->wasm_code()->is_liftoff());
700 701
    Address new_pc =
        FindNewPC(frame, new_code, frame->byte_offset(), return_location);
702 703 704
#ifdef DEBUG
    int old_position = frame->position();
#endif
705 706 707 708 709
#if V8_TARGET_ARCH_X64
    if (frame->wasm_code()->for_debugging()) {
      base::Memory<Address>(frame->fp() - kOSRTargetOffset) = new_pc;
    }
#else
710 711
    PointerAuthentication::ReplacePC(frame->pc_address(), new_pc,
                                     kSystemPointerSize);
712
#endif
713 714 715 716
    // The frame position should still be the same after OSR.
    DCHECK_EQ(old_position, frame->position());
  }

717
  bool IsAtReturn(WasmFrame* frame) {
718
    DisallowGarbageCollection no_gc;
719 720 721 722 723 724 725 726 727 728 729
    int position = frame->position();
    NativeModule* native_module =
        frame->wasm_instance().module_object().native_module();
    uint8_t opcode = native_module->wire_bytes()[position];
    if (opcode == kExprReturn) return true;
    // Another implicit return is at the last kExprEnd in the function body.
    int func_index = frame->function_index();
    WireBytesRef code = native_module->module()->functions[func_index].code;
    return static_cast<size_t>(position) == code.end_offset() - 1;
  }

730 731 732
  // Isolate-specific data, for debugging modules that are shared by multiple
  // isolates.
  struct PerIsolateDebugData {
733 734 735 736
    // Keeps track of the currently set breakpoints (by offset within that
    // function).
    std::unordered_map<int, std::vector<int>> breakpoints_per_function;

737 738 739 740 741
    // Store the frame ID when stepping, to avoid overwriting that frame when
    // setting or removing a breakpoint.
    StackFrameId stepping_frame = NO_ID;
  };

742 743
  NativeModule* const native_module_;

744
  mutable base::Mutex debug_side_tables_mutex_;
745

746
  // DebugSideTable per code object, lazily initialized.
747
  std::unordered_map<const WasmCode*, std::unique_ptr<DebugSideTable>>
748
      debug_side_tables_;
749

750 751 752
  // {mutex_} protects all fields below.
  mutable base::Mutex mutex_;

753 754 755 756 757 758 759
  // Cache a fixed number of WasmCode objects that were generated for debugging.
  // This is useful especially in stepping, because stepping code is cleared on
  // every pause and re-installed on the next step.
  // This is a LRU cache (most recently used entries first).
  static constexpr size_t kMaxCachedDebuggingCode = 3;
  struct CachedDebuggingCode {
    int func_index;
760
    base::OwnedVector<const int> breakpoint_offsets;
761 762 763 764 765
    int dead_breakpoint;
    WasmCode* code;
  };
  std::vector<CachedDebuggingCode> cached_debugging_code_;

766 767 768 769 770 771 772 773
  // Names of exports, lazily derived from the exports table.
  std::unique_ptr<std::map<ImportExportKey, wasm::WireBytesRef>> export_names_;

  // Names of imports, lazily derived from the imports table.
  std::unique_ptr<std::map<ImportExportKey,
                           std::pair<wasm::WireBytesRef, wasm::WireBytesRef>>>
      import_names_;

774 775
  // Names of types, lazily decoded from the wire bytes.
  std::unique_ptr<NameMap> type_names_;
776
  // Names of locals, lazily decoded from the wire bytes.
777 778 779
  std::unique_ptr<IndirectNameMap> local_names_;
  // Names of struct fields, lazily decoded from the wire bytes.
  std::unique_ptr<IndirectNameMap> field_names_;
780

781 782
  // Isolate-specific data.
  std::unordered_map<Isolate*, PerIsolateDebugData> per_isolate_data_;
783 784 785 786 787 788 789
};

DebugInfo::DebugInfo(NativeModule* native_module)
    : impl_(std::make_unique<DebugInfoImpl>(native_module)) {}

DebugInfo::~DebugInfo() = default;

790
int DebugInfo::GetNumLocals(Address pc) { return impl_->GetNumLocals(pc); }
791

792
WasmValue DebugInfo::GetLocalValue(int local, Address pc, Address fp,
793 794
                                   Address debug_break_fp, Isolate* isolate) {
  return impl_->GetLocalValue(local, pc, fp, debug_break_fp, isolate);
795 796
}

797
int DebugInfo::GetStackDepth(Address pc) { return impl_->GetStackDepth(pc); }
798

799
WasmValue DebugInfo::GetStackValue(int index, Address pc, Address fp,
800 801
                                   Address debug_break_fp, Isolate* isolate) {
  return impl_->GetStackValue(index, pc, fp, debug_break_fp, isolate);
802 803
}

804 805 806 807
const wasm::WasmFunction& DebugInfo::GetFunctionAtAddress(Address pc) {
  return impl_->GetFunctionAtAddress(pc);
}

808 809 810 811 812 813 814 815 816 817
WireBytesRef DebugInfo::GetExportName(ImportExportKindCode code,
                                      uint32_t index) {
  return impl_->GetExportName(code, index);
}

std::pair<WireBytesRef, WireBytesRef> DebugInfo::GetImportName(
    ImportExportKindCode code, uint32_t index) {
  return impl_->GetImportName(code, index);
}

818 819 820 821
WireBytesRef DebugInfo::GetTypeName(int type_index) {
  return impl_->GetTypeName(type_index);
}

822 823 824 825
WireBytesRef DebugInfo::GetLocalName(int func_index, int local_index) {
  return impl_->GetLocalName(func_index, local_index);
}

826 827 828 829
WireBytesRef DebugInfo::GetFieldName(int struct_index, int field_index) {
  return impl_->GetFieldName(struct_index, field_index);
}

830 831 832
void DebugInfo::SetBreakpoint(int func_index, int offset,
                              Isolate* current_isolate) {
  impl_->SetBreakpoint(func_index, offset, current_isolate);
833 834
}

835 836 837 838 839 840 841
bool DebugInfo::PrepareStep(WasmFrame* frame) {
  return impl_->PrepareStep(frame);
}

void DebugInfo::PrepareStepOutTo(WasmFrame* frame) {
  impl_->PrepareStepOutTo(frame);
}
842

843 844 845
void DebugInfo::ClearStepping(Isolate* isolate) {
  impl_->ClearStepping(isolate);
}
846

847 848
void DebugInfo::ClearStepping(WasmFrame* frame) { impl_->ClearStepping(frame); }

849
bool DebugInfo::IsStepping(WasmFrame* frame) {
850 851 852
  return impl_->IsStepping(frame);
}

853 854 855 856 857
void DebugInfo::RemoveBreakpoint(int func_index, int offset,
                                 Isolate* current_isolate) {
  impl_->RemoveBreakpoint(func_index, offset, current_isolate);
}

858
void DebugInfo::RemoveDebugSideTables(base::Vector<WasmCode* const> code) {
859 860 861
  impl_->RemoveDebugSideTables(code);
}

862 863 864 865 866
DebugSideTable* DebugInfo::GetDebugSideTableIfExists(
    const WasmCode* code) const {
  return impl_->GetDebugSideTableIfExists(code);
}

867 868 869 870
void DebugInfo::RemoveIsolate(Isolate* isolate) {
  return impl_->RemoveIsolate(isolate);
}

871 872
}  // namespace wasm

873 874
namespace {

875
// Return the next breakable position at or after {offset_in_func} in function
876 877 878 879 880
// {func_index}, or 0 if there is none.
// Note that 0 is never a breakable position in wasm, since the first byte
// contains the locals count for the function.
int FindNextBreakablePosition(wasm::NativeModule* native_module, int func_index,
                              int offset_in_func) {
881 882 883 884 885 886 887 888 889 890
  AccountingAllocator alloc;
  Zone tmp(&alloc, ZONE_NAME);
  wasm::BodyLocalDecls locals(&tmp);
  const byte* module_start = native_module->wire_bytes().begin();
  const wasm::WasmFunction& func =
      native_module->module()->functions[func_index];
  wasm::BytecodeIterator iterator(module_start + func.code.offset(),
                                  module_start + func.code.end_offset(),
                                  &locals);
  DCHECK_LT(0, locals.encoded_size);
891
  if (offset_in_func < 0) return 0;
892 893 894 895
  for (; iterator.has_next(); iterator.next()) {
    if (iterator.pc_offset() < static_cast<uint32_t>(offset_in_func)) continue;
    if (!wasm::WasmOpcodes::IsBreakable(iterator.current())) continue;
    return static_cast<int>(iterator.pc_offset());
896
  }
897
  return 0;
898 899 900 901 902 903 904
}

}  // namespace

// static
bool WasmScript::SetBreakPoint(Handle<Script> script, int* position,
                               Handle<BreakPoint> break_point) {
905
  DCHECK_NE(kOnEntryBreakpointPosition, *position);
906

907 908 909 910 911 912 913
  // Find the function for this breakpoint.
  const wasm::WasmModule* module = script->wasm_native_module()->module();
  int func_index = GetContainingWasmFunction(module, *position);
  if (func_index < 0) return false;
  const wasm::WasmFunction& func = module->functions[func_index];
  int offset_in_func = *position - func.code.offset();

914 915 916 917
  int breakable_offset = FindNextBreakablePosition(script->wasm_native_module(),
                                                   func_index, offset_in_func);
  if (breakable_offset == 0) return false;
  *position = func.code.offset() + breakable_offset;
918

919 920 921 922
  return WasmScript::SetBreakPointForFunction(script, func_index,
                                              breakable_offset, break_point);
}

923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
// static
void WasmScript::SetBreakPointOnEntry(Handle<Script> script,
                                      Handle<BreakPoint> break_point) {
  // Special handling for on-entry breakpoints.
  AddBreakpointToInfo(script, kOnEntryBreakpointPosition, break_point);
  script->set_break_on_entry(true);

  // Update the "break_on_entry" flag on all live instances.
  i::WeakArrayList weak_instance_list = script->wasm_weak_instance_list();
  for (int i = 0; i < weak_instance_list.length(); ++i) {
    if (weak_instance_list.Get(i)->IsCleared()) continue;
    i::WasmInstanceObject instance =
        i::WasmInstanceObject::cast(weak_instance_list.Get(i)->GetHeapObject());
    instance.set_break_on_entry(true);
  }
}

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
// static
bool WasmScript::SetBreakPointOnFirstBreakableForFunction(
    Handle<Script> script, int func_index, Handle<BreakPoint> break_point) {
  if (func_index < 0) return false;
  int offset_in_func = 0;

  int breakable_offset = FindNextBreakablePosition(script->wasm_native_module(),
                                                   func_index, offset_in_func);
  if (breakable_offset == 0) return false;
  return WasmScript::SetBreakPointForFunction(script, func_index,
                                              breakable_offset, break_point);
}

// static
bool WasmScript::SetBreakPointForFunction(Handle<Script> script, int func_index,
955
                                          int offset,
956 957 958 959
                                          Handle<BreakPoint> break_point) {
  Isolate* isolate = script->GetIsolate();

  DCHECK_LE(0, func_index);
960
  DCHECK_NE(0, offset);
961 962

  // Find the function for this breakpoint.
963 964
  wasm::NativeModule* native_module = script->wasm_native_module();
  const wasm::WasmModule* module = native_module->module();
965 966
  const wasm::WasmFunction& func = module->functions[func_index];

967
  // Insert new break point into {wasm_breakpoint_infos} of the script.
968
  AddBreakpointToInfo(script, func.code.offset() + offset, break_point);
969

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  native_module->GetDebugInfo()->SetBreakpoint(func_index, offset, isolate);

  return true;
}

namespace {

int GetBreakpointPos(Isolate* isolate, Object break_point_info_or_undef) {
  if (break_point_info_or_undef.IsUndefined(isolate)) return kMaxInt;
  return BreakPointInfo::cast(break_point_info_or_undef).source_position();
}

int FindBreakpointInfoInsertPos(Isolate* isolate,
                                Handle<FixedArray> breakpoint_infos,
                                int position) {
  // Find insert location via binary search, taking care of undefined values on
986 987 988
  // the right. {position} is either {kOnEntryBreakpointPosition} (which is -1),
  // or positive.
  DCHECK(position == WasmScript::kOnEntryBreakpointPosition || position > 0);
989 990 991 992 993 994 995 996 997 998

  int left = 0;                            // inclusive
  int right = breakpoint_infos->length();  // exclusive
  while (right - left > 1) {
    int mid = left + (right - left) / 2;
    Object mid_obj = breakpoint_infos->get(mid);
    if (GetBreakpointPos(isolate, mid_obj) <= position) {
      left = mid;
    } else {
      right = mid;
999 1000 1001
    }
  }

1002 1003
  int left_pos = GetBreakpointPos(isolate, breakpoint_infos->get(left));
  return left_pos < position ? left + 1 : left;
1004 1005
}

1006 1007
}  // namespace

1008 1009 1010
// static
bool WasmScript::ClearBreakPoint(Handle<Script> script, int position,
                                 Handle<BreakPoint> break_point) {
1011 1012
  if (!script->has_wasm_breakpoint_infos()) return false;

1013
  Isolate* isolate = script->GetIsolate();
1014
  Handle<FixedArray> breakpoint_infos(script->wasm_breakpoint_infos(), isolate);
1015

1016
  int pos = FindBreakpointInfoInsertPos(isolate, breakpoint_infos, position);
1017

1018 1019
  // Does a BreakPointInfo object already exist for this position?
  if (pos == breakpoint_infos->length()) return false;
1020

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
  Handle<BreakPointInfo> info(BreakPointInfo::cast(breakpoint_infos->get(pos)),
                              isolate);
  BreakPointInfo::ClearBreakPoint(isolate, info, break_point);

  // Check if there are no more breakpoints at this location.
  if (info->GetBreakPointCount(isolate) == 0) {
    // Update array by moving breakpoints up one position.
    for (int i = pos; i < breakpoint_infos->length() - 1; i++) {
      Object entry = breakpoint_infos->get(i + 1);
      breakpoint_infos->set(i, entry);
      if (entry.IsUndefined(isolate)) break;
1032
    }
1033 1034
    // Make sure last array element is empty as a result.
    breakpoint_infos->set_undefined(breakpoint_infos->length() - 1);
1035
  }
1036 1037 1038 1039 1040 1041 1042 1043

  // Remove the breakpoint from DebugInfo and recompile.
  wasm::NativeModule* native_module = script->wasm_native_module();
  const wasm::WasmModule* module = native_module->module();
  int func_index = GetContainingWasmFunction(module, position);
  native_module->GetDebugInfo()->RemoveBreakpoint(func_index, position,
                                                  isolate);

1044 1045 1046
  return true;
}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
// static
bool WasmScript::ClearBreakPointById(Handle<Script> script, int breakpoint_id) {
  if (!script->has_wasm_breakpoint_infos()) {
    return false;
  }
  Isolate* isolate = script->GetIsolate();
  Handle<FixedArray> breakpoint_infos(script->wasm_breakpoint_infos(), isolate);
  // If the array exists, it should not be empty.
  DCHECK_LT(0, breakpoint_infos->length());

  for (int i = 0, e = breakpoint_infos->length(); i < e; ++i) {
    Handle<Object> obj(breakpoint_infos->get(i), isolate);
    if (obj->IsUndefined(isolate)) {
      continue;
    }
    Handle<BreakPointInfo> breakpoint_info = Handle<BreakPointInfo>::cast(obj);
    Handle<BreakPoint> breakpoint;
    if (BreakPointInfo::GetBreakPointById(isolate, breakpoint_info,
                                          breakpoint_id)
            .ToHandle(&breakpoint)) {
      DCHECK(breakpoint->id() == breakpoint_id);
      return WasmScript::ClearBreakPoint(
          script, breakpoint_info->source_position(), breakpoint);
    }
  }
  return false;
}

1075 1076 1077 1078 1079 1080
// static
void WasmScript::ClearAllBreakpoints(Script script) {
  script.set_wasm_breakpoint_infos(
      ReadOnlyRoots(script.GetIsolate()).empty_fixed_array());
}

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
// static
void WasmScript::AddBreakpointToInfo(Handle<Script> script, int position,
                                     Handle<BreakPoint> break_point) {
  Isolate* isolate = script->GetIsolate();
  Handle<FixedArray> breakpoint_infos;
  if (script->has_wasm_breakpoint_infos()) {
    breakpoint_infos = handle(script->wasm_breakpoint_infos(), isolate);
  } else {
    breakpoint_infos =
        isolate->factory()->NewFixedArray(4, AllocationType::kOld);
    script->set_wasm_breakpoint_infos(*breakpoint_infos);
  }

  int insert_pos =
      FindBreakpointInfoInsertPos(isolate, breakpoint_infos, position);

  // If a BreakPointInfo object already exists for this position, add the new
  // breakpoint object and return.
  if (insert_pos < breakpoint_infos->length() &&
      GetBreakpointPos(isolate, breakpoint_infos->get(insert_pos)) ==
          position) {
    Handle<BreakPointInfo> old_info(
        BreakPointInfo::cast(breakpoint_infos->get(insert_pos)), isolate);
    BreakPointInfo::SetBreakPoint(isolate, old_info, break_point);
    return;
  }

  // Enlarge break positions array if necessary.
  bool need_realloc = !breakpoint_infos->get(breakpoint_infos->length() - 1)
                           .IsUndefined(isolate);
  Handle<FixedArray> new_breakpoint_infos = breakpoint_infos;
  if (need_realloc) {
    new_breakpoint_infos = isolate->factory()->NewFixedArray(
        2 * breakpoint_infos->length(), AllocationType::kOld);
    script->set_wasm_breakpoint_infos(*new_breakpoint_infos);
    // Copy over the entries [0, insert_pos).
    for (int i = 0; i < insert_pos; ++i)
      new_breakpoint_infos->set(i, breakpoint_infos->get(i));
  }

  // Move elements [insert_pos, ...] up by one.
  for (int i = breakpoint_infos->length() - 1; i >= insert_pos; --i) {
    Object entry = breakpoint_infos->get(i);
    if (entry.IsUndefined(isolate)) continue;
    new_breakpoint_infos->set(i + 1, entry);
  }

  // Generate new BreakpointInfo.
  Handle<BreakPointInfo> breakpoint_info =
      isolate->factory()->NewBreakPointInfo(position);
  BreakPointInfo::SetBreakPoint(isolate, breakpoint_info, break_point);

  // Now insert new position at insert_pos.
  new_breakpoint_infos->set(insert_pos, *breakpoint_info);
}

// static
bool WasmScript::GetPossibleBreakpoints(
    wasm::NativeModule* native_module, const v8::debug::Location& start,
    const v8::debug::Location& end,
    std::vector<v8::debug::BreakLocation>* locations) {
1142
  DisallowGarbageCollection no_gc;
1143

1144 1145 1146 1147
  const wasm::WasmModule* module = native_module->module();
  const std::vector<wasm::WasmFunction>& functions = module->functions;

  if (start.GetLineNumber() != 0 || start.GetColumnNumber() < 0 ||
1148
      (!end.IsEmpty() &&
1149 1150
       (end.GetLineNumber() != 0 || end.GetColumnNumber() < 0 ||
        end.GetColumnNumber() < start.GetColumnNumber())))
1151 1152 1153 1154 1155
    return false;

  // start_func_index, start_offset and end_func_index is inclusive.
  // end_offset is exclusive.
  // start_offset and end_offset are module-relative byte offsets.
1156 1157 1158 1159 1160 1161
  // We set strict to false because offsets may be between functions.
  int start_func_index =
      GetNearestWasmFunction(module, start.GetColumnNumber());
  if (start_func_index < 0) return false;
  uint32_t start_offset = start.GetColumnNumber();
  int end_func_index;
1162
  uint32_t end_offset;
1163

1164 1165 1166 1167 1168 1169
  if (end.IsEmpty()) {
    // Default: everything till the end of the Script.
    end_func_index = static_cast<uint32_t>(functions.size() - 1);
    end_offset = functions[end_func_index].code.end_offset();
  } else {
    // If end is specified: Use it and check for valid input.
1170 1171 1172
    end_offset = end.GetColumnNumber();
    end_func_index = GetNearestWasmFunction(module, end_offset);
    DCHECK_GE(end_func_index, start_func_index);
1173 1174
  }

1175 1176 1177
  if (start_func_index == end_func_index &&
      start_offset > functions[end_func_index].code.end_offset())
    return false;
1178 1179 1180 1181
  AccountingAllocator alloc;
  Zone tmp(&alloc, ZONE_NAME);
  const byte* module_start = native_module->wire_bytes().begin();

1182
  for (int func_idx = start_func_index; func_idx <= end_func_index;
1183 1184 1185 1186 1187 1188 1189 1190 1191
       ++func_idx) {
    const wasm::WasmFunction& func = functions[func_idx];
    if (func.code.length() == 0) continue;

    wasm::BodyLocalDecls locals(&tmp);
    wasm::BytecodeIterator iterator(module_start + func.code.offset(),
                                    module_start + func.code.end_offset(),
                                    &locals);
    DCHECK_LT(0u, locals.encoded_size);
1192 1193
    for (; iterator.has_next(); iterator.next()) {
      uint32_t total_offset = func.code.offset() + iterator.pc_offset();
1194 1195 1196 1197 1198
      if (total_offset >= end_offset) {
        DCHECK_EQ(end_func_index, func_idx);
        break;
      }
      if (total_offset < start_offset) continue;
1199
      if (!wasm::WasmOpcodes::IsBreakable(iterator.current())) continue;
1200
      locations->emplace_back(0, total_offset, debug::kCommonBreakLocation);
1201 1202 1203 1204 1205
    }
  }
  return true;
}

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
namespace {

bool CheckBreakPoint(Isolate* isolate, Handle<BreakPoint> break_point,
                     StackFrameId frame_id) {
  if (break_point->condition().length() == 0) return true;

  HandleScope scope(isolate);
  Handle<String> condition(break_point->condition(), isolate);
  Handle<Object> result;
  // The Wasm engine doesn't perform any sort of inlining.
  const int inlined_jsframe_index = 0;
  const bool throw_on_side_effect = false;
  if (!DebugEvaluate::Local(isolate, frame_id, inlined_jsframe_index, condition,
                            throw_on_side_effect)
           .ToHandle(&result)) {
    isolate->clear_pending_exception();
    return false;
  }
  return result->BooleanValue(isolate);
}

}  // namespace

1229 1230 1231
// static
MaybeHandle<FixedArray> WasmScript::CheckBreakPoints(Isolate* isolate,
                                                     Handle<Script> script,
1232 1233
                                                     int position,
                                                     StackFrameId frame_id) {
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
  if (!script->has_wasm_breakpoint_infos()) return {};

  Handle<FixedArray> breakpoint_infos(script->wasm_breakpoint_infos(), isolate);
  int insert_pos =
      FindBreakpointInfoInsertPos(isolate, breakpoint_infos, position);
  if (insert_pos >= breakpoint_infos->length()) return {};

  Handle<Object> maybe_breakpoint_info(breakpoint_infos->get(insert_pos),
                                       isolate);
  if (maybe_breakpoint_info->IsUndefined(isolate)) return {};
  Handle<BreakPointInfo> breakpoint_info =
      Handle<BreakPointInfo>::cast(maybe_breakpoint_info);
  if (breakpoint_info->source_position() != position) return {};

  Handle<Object> break_points(breakpoint_info->break_points(), isolate);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
  if (!break_points->IsFixedArray()) {
    if (!CheckBreakPoint(isolate, Handle<BreakPoint>::cast(break_points),
                         frame_id)) {
      return {};
    }
    Handle<FixedArray> break_points_hit = isolate->factory()->NewFixedArray(1);
    break_points_hit->set(0, *break_points);
    return break_points_hit;
  }

  Handle<FixedArray> array = Handle<FixedArray>::cast(break_points);
  Handle<FixedArray> break_points_hit =
      isolate->factory()->NewFixedArray(array->length());
  int break_points_hit_count = 0;
  for (int i = 0; i < array->length(); ++i) {
    Handle<BreakPoint> break_point(BreakPoint::cast(array->get(i)), isolate);
    if (CheckBreakPoint(isolate, break_point, frame_id)) {
      break_points_hit->set(break_points_hit_count++, *break_point);
    }
1268
  }
1269 1270
  if (break_points_hit_count == 0) return {};
  break_points_hit->Shrink(isolate, break_points_hit_count);
1271 1272 1273
  return break_points_hit;
}

1274 1275
}  // namespace internal
}  // namespace v8