wasm-debug.cc 30 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 <unordered_map>

7
#include "src/assembler-inl.h"
8
#include "src/assert-scope.h"
9
#include "src/base/optional.h"
10
#include "src/compiler/wasm-compiler.h"
11
#include "src/debug/debug-scopes.h"
12
#include "src/debug/debug.h"
13
#include "src/frames-inl.h"
14
#include "src/heap/factory.h"
15
#include "src/identity-map.h"
16 17
#include "src/isolate.h"
#include "src/wasm/module-decoder.h"
18
#include "src/wasm/wasm-code-manager.h"
19 20
#include "src/wasm/wasm-interpreter.h"
#include "src/wasm/wasm-limits.h"
21
#include "src/wasm/wasm-module.h"
22
#include "src/wasm/wasm-objects-inl.h"
23
#include "src/zone/accounting-allocator.h"
24

25 26 27
namespace v8 {
namespace internal {
namespace wasm {
28

29 30
namespace {

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
template <bool internal, typename... Args>
Handle<String> PrintFToOneByteString(Isolate* isolate, const char* format,
                                     Args... args) {
  // Maximum length of a formatted value name ("param#%d", "local#%d",
  // "global#%d").
  constexpr int kMaxStrLen = 18;
  EmbeddedVector<char, kMaxStrLen> value;
  int len = SNPrintF(value, format, args...);
  CHECK(len > 0 && len < value.length());
  Vector<uint8_t> name = Vector<uint8_t>::cast(value.SubVector(0, len));
  return internal
             ? isolate->factory()->InternalizeOneByteString(name)
             : isolate->factory()->NewStringFromOneByte(name).ToHandleChecked();
}

46 47
Handle<Object> WasmValueToValueObject(Isolate* isolate, WasmValue value) {
  switch (value.type()) {
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    case kWasmI32:
      if (Smi::IsValid(value.to<int32_t>()))
        return handle(Smi::FromInt(value.to<int32_t>()), isolate);
      return PrintFToOneByteString<false>(isolate, "%d", value.to<int32_t>());
    case kWasmI64:
      if (Smi::IsValid(value.to<int64_t>()))
        return handle(Smi::FromIntptr(value.to<int64_t>()), isolate);
      return PrintFToOneByteString<false>(isolate, "%" PRId64,
                                          value.to<int64_t>());
    case kWasmF32:
      return isolate->factory()->NewNumber(value.to<float>());
    case kWasmF64:
      return isolate->factory()->NewNumber(value.to<double>());
    default:
      UNIMPLEMENTED();
      return isolate->factory()->undefined_value();
  }
}

67 68 69 70 71 72
MaybeHandle<String> GetLocalName(Isolate* isolate,
                                 Handle<WasmDebugInfo> debug_info,
                                 int func_index, int local_index) {
  DCHECK_LE(0, func_index);
  DCHECK_LE(0, local_index);
  if (!debug_info->has_locals_names()) {
73 74
    Handle<WasmModuleObject> module_object(
        debug_info->wasm_instance()->module_object(), isolate);
75
    Handle<FixedArray> locals_names = DecodeLocalNames(isolate, module_object);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    debug_info->set_locals_names(*locals_names);
  }

  Handle<FixedArray> locals_names(debug_info->locals_names(), isolate);
  if (func_index >= locals_names->length() ||
      locals_names->get(func_index)->IsUndefined(isolate)) {
    return {};
  }

  Handle<FixedArray> func_locals_names(
      FixedArray::cast(locals_names->get(func_index)), isolate);
  if (local_index >= func_locals_names->length() ||
      func_locals_names->get(local_index)->IsUndefined(isolate)) {
    return {};
  }
91
  return handle(String::cast(func_locals_names->get(local_index)), isolate);
92 93
}

94
class InterpreterHandle {
95
  MOVE_ONLY_NO_DEFAULT_CONSTRUCTOR(InterpreterHandle);
96
  Isolate* isolate_;
97 98
  const WasmModule* module_;
  WasmInterpreter interpreter_;
99 100
  StepAction next_step_action_ = StepNone;
  int last_step_stack_depth_ = 0;
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  std::unordered_map<Address, uint32_t> activations_;

  uint32_t StartActivation(Address frame_pointer) {
    WasmInterpreter::Thread* thread = interpreter_.GetThread(0);
    uint32_t activation_id = thread->StartActivation();
    DCHECK_EQ(0, activations_.count(frame_pointer));
    activations_.insert(std::make_pair(frame_pointer, activation_id));
    return activation_id;
  }

  void FinishActivation(Address frame_pointer, uint32_t activation_id) {
    WasmInterpreter::Thread* thread = interpreter_.GetThread(0);
    thread->FinishActivation(activation_id);
    DCHECK_EQ(1, activations_.count(frame_pointer));
    activations_.erase(frame_pointer);
  }

  std::pair<uint32_t, uint32_t> GetActivationFrameRange(
      WasmInterpreter::Thread* thread, Address frame_pointer) {
    DCHECK_EQ(1, activations_.count(frame_pointer));
    uint32_t activation_id = activations_.find(frame_pointer)->second;
    uint32_t num_activations = static_cast<uint32_t>(activations_.size() - 1);
    uint32_t frame_base = thread->ActivationFrameBase(activation_id);
    uint32_t frame_limit = activation_id == num_activations
                               ? thread->GetFrameCount()
                               : thread->ActivationFrameBase(activation_id + 1);
    DCHECK_LE(frame_base, frame_limit);
    DCHECK_LE(frame_limit, thread->GetFrameCount());
    return {frame_base, frame_limit};
  }
131

132 133 134
  static Vector<const byte> GetBytes(WasmDebugInfo* debug_info) {
    // Return raw pointer into heap. The WasmInterpreter will make its own copy
    // of this data anyway, and there is no heap allocation in-between.
135 136 137
    NativeModule* native_module =
        debug_info->wasm_instance()->module_object()->native_module();
    return native_module->wire_bytes();
138
  }
139

140
 public:
141
  // TODO(wasm): properly handlify this constructor.
142 143
  InterpreterHandle(Isolate* isolate, WasmDebugInfo* debug_info)
      : isolate_(isolate),
144
        module_(debug_info->wasm_instance()->module_object()->module()),
145
        interpreter_(isolate, module_, GetBytes(debug_info),
146
                     handle(debug_info->wasm_instance(), isolate)) {}
147 148 149

  ~InterpreterHandle() { DCHECK_EQ(0, activations_.size()); }

150
  WasmInterpreter* interpreter() { return &interpreter_; }
151
  const WasmModule* module() const { return module_; }
152

153 154 155 156 157 158 159 160 161 162 163 164
  void PrepareStep(StepAction step_action) {
    next_step_action_ = step_action;
    last_step_stack_depth_ = CurrentStackDepth();
  }

  void ClearStepping() { next_step_action_ = StepNone; }

  int CurrentStackDepth() {
    DCHECK_EQ(1, interpreter()->GetThreadCount());
    return interpreter()->GetThread(0)->GetFrameCount();
  }

165 166 167
  // Returns true if exited regularly, false if a trap/exception occurred and
  // was not handled inside this activation. In the latter case, a pending
  // exception will have been set on the isolate.
168
  bool Execute(Handle<WasmInstanceObject> instance_object,
169
               Address frame_pointer, uint32_t func_index, Address arg_buffer) {
170
    DCHECK_GE(module()->functions.size(), func_index);
171
    FunctionSig* sig = module()->functions[func_index].sig;
172 173
    DCHECK_GE(kMaxInt, sig->parameter_count());
    int num_params = static_cast<int>(sig->parameter_count());
174
    ScopedVector<WasmValue> wasm_args(num_params);
175
    Address arg_buf_ptr = arg_buffer;
176
    for (int i = 0; i < num_params; ++i) {
177 178
      uint32_t param_size = static_cast<uint32_t>(
          ValueTypes::ElementSizeInBytes(sig->GetParam(i)));
179 180 181 182
#define CASE_ARG_TYPE(type, ctype)                                    \
  case type:                                                          \
    DCHECK_EQ(param_size, sizeof(ctype));                             \
    wasm_args[i] = WasmValue(ReadUnalignedValue<ctype>(arg_buf_ptr)); \
183 184 185 186 187 188 189 190 191 192
    break;
      switch (sig->GetParam(i)) {
        CASE_ARG_TYPE(kWasmI32, uint32_t)
        CASE_ARG_TYPE(kWasmI64, uint64_t)
        CASE_ARG_TYPE(kWasmF32, float)
        CASE_ARG_TYPE(kWasmF64, double)
#undef CASE_ARG_TYPE
        default:
          UNREACHABLE();
      }
193
      arg_buf_ptr += param_size;
194 195
    }

196 197
    uint32_t activation_id = StartActivation(frame_pointer);

198
    WasmInterpreter::Thread* thread = interpreter_.GetThread(0);
199
    thread->InitFrame(&module()->functions[func_index], wasm_args.start());
200 201 202 203
    bool finished = false;
    while (!finished) {
      // TODO(clemensh): Add occasional StackChecks.
      WasmInterpreter::State state = ContinueExecution(thread);
204
      switch (state) {
205
        case WasmInterpreter::State::PAUSED:
206
          NotifyDebugEventListeners(thread);
207
          break;
208 209
        case WasmInterpreter::State::FINISHED:
          // Perfect, just break the switch and exit the loop.
210
          finished = true;
211
          break;
212 213 214 215 216 217
        case WasmInterpreter::State::TRAPPED: {
          int message_id =
              WasmOpcodes::TrapReasonToMessageId(thread->GetTrapReason());
          Handle<Object> exception = isolate_->factory()->NewWasmRuntimeError(
              static_cast<MessageTemplate::Template>(message_id));
          isolate_->Throw(*exception);
218 219 220 221
          // Handle this exception. Return without trying to read back the
          // return value.
          auto result = thread->HandleException(isolate_);
          return result == WasmInterpreter::Thread::HANDLED;
222
        } break;
223
        case WasmInterpreter::State::STOPPED:
224 225 226
          // An exception happened, and the current activation was unwound.
          DCHECK_EQ(thread->ActivationFrameBase(activation_id),
                    thread->GetFrameCount());
227 228
          return false;
        // RUNNING should never occur here.
229 230 231 232
        case WasmInterpreter::State::RUNNING:
        default:
          UNREACHABLE();
      }
233
    }
234 235 236 237 238 239

    // Copy back the return value
    DCHECK_GE(kV8MaxWasmFunctionReturns, sig->return_count());
    // TODO(wasm): Handle multi-value returns.
    DCHECK_EQ(1, kV8MaxWasmFunctionReturns);
    if (sig->return_count()) {
240
      WasmValue ret_val = thread->GetReturnValue(0);
241 242 243 244 245
#define CASE_RET_TYPE(type, ctype)                               \
  case type:                                                     \
    DCHECK_EQ(ValueTypes::ElementSizeInBytes(sig->GetReturn(0)), \
              sizeof(ctype));                                    \
    WriteUnalignedValue<ctype>(arg_buffer, ret_val.to<ctype>()); \
246 247 248 249 250 251 252 253 254 255 256
    break;
      switch (sig->GetReturn(0)) {
        CASE_RET_TYPE(kWasmI32, uint32_t)
        CASE_RET_TYPE(kWasmI64, uint64_t)
        CASE_RET_TYPE(kWasmF32, float)
        CASE_RET_TYPE(kWasmF64, double)
#undef CASE_RET_TYPE
        default:
          UNREACHABLE();
      }
    }
257 258 259

    FinishActivation(frame_pointer, activation_id);

260
    return true;
261
  }
262

263 264 265 266 267 268 269 270
  WasmInterpreter::State ContinueExecution(WasmInterpreter::Thread* thread) {
    switch (next_step_action_) {
      case StepNone:
        return thread->Run();
      case StepIn:
        return thread->Step();
      case StepOut:
        thread->AddBreakFlags(WasmInterpreter::BreakFlag::AfterReturn);
271
        return thread->Run();
272 273 274 275 276 277 278 279 280 281 282 283 284
      case StepNext: {
        int stack_depth = thread->GetFrameCount();
        if (stack_depth == last_step_stack_depth_) return thread->Step();
        thread->AddBreakFlags(stack_depth > last_step_stack_depth_
                                  ? WasmInterpreter::BreakFlag::AfterReturn
                                  : WasmInterpreter::BreakFlag::AfterCall);
        return thread->Run();
      }
      default:
        UNREACHABLE();
    }
  }

285 286 287 288 289
  Handle<WasmInstanceObject> GetInstanceObject() {
    StackTraceFrameIterator it(isolate_);
    WasmInterpreterEntryFrame* frame =
        WasmInterpreterEntryFrame::cast(it.frame());
    Handle<WasmInstanceObject> instance_obj(frame->wasm_instance(), isolate_);
290 291
    // Check that this is indeed the instance which is connected to this
    // interpreter.
292
    DCHECK_EQ(this, Managed<InterpreterHandle>::cast(
293
                        instance_obj->debug_info()->interpreter_handle())
294
                        ->raw());
295 296 297
    return instance_obj;
  }

298
  void NotifyDebugEventListeners(WasmInterpreter::Thread* thread) {
299 300 301
    // Enter the debugger.
    DebugScope debug_scope(isolate_->debug());

302
    // Check whether we hit a breakpoint.
303
    if (isolate_->debug()->break_points_active()) {
304 305 306
      Handle<WasmModuleObject> module_object(
          GetInstanceObject()->module_object(), isolate_);
      int position = GetTopPosition(module_object);
307
      Handle<FixedArray> breakpoints;
308
      if (WasmModuleObject::CheckBreakPoints(isolate_, module_object, position)
309
              .ToHandle(&breakpoints)) {
310 311 312
        // We hit one or several breakpoints. Clear stepping, notify the
        // listeners and return.
        ClearStepping();
313
        isolate_->debug()->OnDebugBreak(breakpoints);
314 315
        return;
      }
316 317
    }

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    // We did not hit a breakpoint, so maybe this pause is related to stepping.
    bool hit_step = false;
    switch (next_step_action_) {
      case StepNone:
        break;
      case StepIn:
        hit_step = true;
        break;
      case StepOut:
        hit_step = thread->GetFrameCount() < last_step_stack_depth_;
        break;
      case StepNext: {
        hit_step = thread->GetFrameCount() == last_step_stack_depth_;
        break;
      }
      default:
        UNREACHABLE();
335
    }
336 337
    if (!hit_step) return;
    ClearStepping();
338
    isolate_->debug()->OnDebugBreak(isolate_->factory()->empty_fixed_array());
339 340
  }

341
  int GetTopPosition(Handle<WasmModuleObject> module_object) {
342 343 344 345
    DCHECK_EQ(1, interpreter()->GetThreadCount());
    WasmInterpreter::Thread* thread = interpreter()->GetThread(0);
    DCHECK_LT(0, thread->GetFrameCount());

346
    auto frame = thread->GetFrame(thread->GetFrameCount() - 1);
347
    return module_object->GetFunctionOffset(frame->function()->func_index) +
348
           frame->pc();
349 350 351 352 353 354
  }

  std::vector<std::pair<uint32_t, int>> GetInterpretedStack(
      Address frame_pointer) {
    DCHECK_EQ(1, interpreter()->GetThreadCount());
    WasmInterpreter::Thread* thread = interpreter()->GetThread(0);
355 356 357 358 359 360 361

    std::pair<uint32_t, uint32_t> frame_range =
        GetActivationFrameRange(thread, frame_pointer);

    std::vector<std::pair<uint32_t, int>> stack;
    stack.reserve(frame_range.second - frame_range.first);
    for (uint32_t fp = frame_range.first; fp < frame_range.second; ++fp) {
362 363
      auto frame = thread->GetFrame(fp);
      stack.emplace_back(frame->function()->func_index, frame->pc());
364 365 366 367
    }
    return stack;
  }

368 369
  WasmInterpreter::FramePtr GetInterpretedFrame(Address frame_pointer,
                                                int idx) {
370 371
    DCHECK_EQ(1, interpreter()->GetThreadCount());
    WasmInterpreter::Thread* thread = interpreter()->GetThread(0);
372 373 374 375 376 377

    std::pair<uint32_t, uint32_t> frame_range =
        GetActivationFrameRange(thread, frame_pointer);
    DCHECK_LE(0, idx);
    DCHECK_GT(frame_range.second - frame_range.first, idx);

378
    return thread->GetFrame(frame_range.first + idx);
379
  }
380

381
  void Unwind(Address frame_pointer) {
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    // Find the current activation.
    DCHECK_EQ(1, activations_.count(frame_pointer));
    // Activations must be properly stacked:
    DCHECK_EQ(activations_.size() - 1, activations_[frame_pointer]);
    uint32_t activation_id = static_cast<uint32_t>(activations_.size() - 1);

    // Unwind the frames of the current activation if not already unwound.
    WasmInterpreter::Thread* thread = interpreter()->GetThread(0);
    if (static_cast<uint32_t>(thread->GetFrameCount()) >
        thread->ActivationFrameBase(activation_id)) {
      using ExceptionResult = WasmInterpreter::Thread::ExceptionHandlingResult;
      ExceptionResult result = thread->HandleException(isolate_);
      // TODO(wasm): Handle exceptions caught in wasm land.
      CHECK_EQ(ExceptionResult::UNWOUND, result);
    }

    FinishActivation(frame_pointer, activation_id);
399 400
  }

401 402 403 404
  uint64_t NumInterpretedCalls() {
    DCHECK_EQ(1, interpreter()->GetThreadCount());
    return interpreter()->GetThread(0)->NumInterpretedCalls();
  }
405

406
  Handle<JSObject> GetGlobalScopeObject(InterpretedFrame* frame,
407
                                        Handle<WasmDebugInfo> debug_info) {
408
    Isolate* isolate = isolate_;
409
    Handle<WasmInstanceObject> instance(debug_info->wasm_instance(), isolate);
410

411
    // TODO(clemensh): Add globals to the global scope.
412 413
    Handle<JSObject> global_scope_object =
        isolate_->factory()->NewJSObjectWithNullProto();
414
    if (instance->has_memory_object()) {
415 416
      Handle<String> name = isolate_->factory()->InternalizeOneByteString(
          STATIC_CHAR_VECTOR("memory"));
417 418
      Handle<JSArrayBuffer> memory_buffer(
          instance->memory_object()->array_buffer(), isolate_);
419 420 421 422 423 424
      uint32_t byte_length;
      CHECK(memory_buffer->byte_length()->ToUint32(&byte_length));
      Handle<JSTypedArray> uint8_array = isolate_->factory()->NewJSTypedArray(
          kExternalUint8Array, memory_buffer, 0, byte_length);
      JSObject::SetOwnPropertyIgnoreAttributes(global_scope_object, name,
                                               uint8_array, NONE)
425
          .Assert();
426
    }
427 428 429
    return global_scope_object;
  }

430
  Handle<JSObject> GetLocalScopeObject(InterpretedFrame* frame,
431
                                       Handle<WasmDebugInfo> debug_info) {
432
    Isolate* isolate = isolate_;
433 434 435 436 437 438 439

    Handle<JSObject> local_scope_object =
        isolate_->factory()->NewJSObjectWithNullProto();
    // Fill parameters and locals.
    int num_params = frame->GetParameterCount();
    int num_locals = frame->GetLocalCount();
    DCHECK_LE(num_params, num_locals);
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    if (num_locals > 0) {
      Handle<JSObject> locals_obj =
          isolate_->factory()->NewJSObjectWithNullProto();
      Handle<String> locals_name =
          isolate_->factory()->InternalizeOneByteString(
              STATIC_CHAR_VECTOR("locals"));
      JSObject::SetOwnPropertyIgnoreAttributes(local_scope_object, locals_name,
                                               locals_obj, NONE)
          .Assert();
      for (int i = 0; i < num_locals; ++i) {
        MaybeHandle<String> name =
            GetLocalName(isolate, debug_info, frame->function()->func_index, i);
        if (name.is_null()) {
          // Parameters should come before locals in alphabetical ordering, so
          // we name them "args" here.
          const char* label = i < num_params ? "arg#%d" : "local#%d";
          name = PrintFToOneByteString<true>(isolate_, label, i);
        }
458 459
        WasmValue value = frame->GetLocalValue(i);
        Handle<Object> value_obj = WasmValueToValueObject(isolate_, value);
460 461 462 463
        JSObject::SetOwnPropertyIgnoreAttributes(
            locals_obj, name.ToHandleChecked(), value_obj, NONE)
            .Assert();
      }
464 465 466 467 468 469 470 471 472
    }

    // Fill stack values.
    int stack_count = frame->GetStackHeight();
    // Use an object without prototype instead of an Array, for nicer displaying
    // in DevTools. For Arrays, the length field and prototype is displayed,
    // which does not make too much sense here.
    Handle<JSObject> stack_obj =
        isolate_->factory()->NewJSObjectWithNullProto();
473 474 475 476 477
    Handle<String> stack_name = isolate_->factory()->InternalizeOneByteString(
        STATIC_CHAR_VECTOR("stack"));
    JSObject::SetOwnPropertyIgnoreAttributes(local_scope_object, stack_name,
                                             stack_obj, NONE)
        .Assert();
478
    for (int i = 0; i < stack_count; ++i) {
479 480
      WasmValue value = frame->GetStackValue(i);
      Handle<Object> value_obj = WasmValueToValueObject(isolate_, value);
481 482
      JSObject::SetOwnElementIgnoreAttributes(
          stack_obj, static_cast<uint32_t>(i), value_obj, NONE)
483
          .Assert();
484
    }
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    return local_scope_object;
  }

  Handle<JSArray> GetScopeDetails(Address frame_pointer, int frame_index,
                                  Handle<WasmDebugInfo> debug_info) {
    auto frame = GetInterpretedFrame(frame_pointer, frame_index);

    Handle<FixedArray> global_scope =
        isolate_->factory()->NewFixedArray(ScopeIterator::kScopeDetailsSize);
    global_scope->set(ScopeIterator::kScopeDetailsTypeIndex,
                      Smi::FromInt(ScopeIterator::ScopeTypeGlobal));
    Handle<JSObject> global_scope_object =
        GetGlobalScopeObject(frame.get(), debug_info);
    global_scope->set(ScopeIterator::kScopeDetailsObjectIndex,
                      *global_scope_object);

    Handle<FixedArray> local_scope =
        isolate_->factory()->NewFixedArray(ScopeIterator::kScopeDetailsSize);
    local_scope->set(ScopeIterator::kScopeDetailsTypeIndex,
                     Smi::FromInt(ScopeIterator::ScopeTypeLocal));
    Handle<JSObject> local_scope_object =
        GetLocalScopeObject(frame.get(), debug_info);
    local_scope->set(ScopeIterator::kScopeDetailsObjectIndex,
                     *local_scope_object);
509 510 511 512 513 514 515 516 517 518

    Handle<JSArray> global_jsarr =
        isolate_->factory()->NewJSArrayWithElements(global_scope);
    Handle<JSArray> local_jsarr =
        isolate_->factory()->NewJSArrayWithElements(local_scope);
    Handle<FixedArray> all_scopes = isolate_->factory()->NewFixedArray(2);
    all_scopes->set(0, *global_jsarr);
    all_scopes->set(1, *local_jsarr);
    return isolate_->factory()->NewJSArrayWithElements(all_scopes);
  }
519 520
};

521 522 523 524 525 526 527
}  // namespace

}  // namespace wasm

namespace {

wasm::InterpreterHandle* GetOrCreateInterpreterHandle(
528
    Isolate* isolate, Handle<WasmDebugInfo> debug_info) {
529
  Handle<Object> handle(debug_info->interpreter_handle(), isolate);
530
  if (handle->IsUndefined(isolate)) {
531 532 533 534 535 536
    // Use the maximum stack size to estimate the maximum size of the
    // interpreter. The interpreter keeps its own stack internally, and the size
    // of the stack should dominate the overall size of the interpreter. We
    // multiply by '2' to account for the growing strategy for the backing store
    // of the stack.
    size_t interpreter_size = FLAG_stack_size * KB * 2;
537 538
    handle = Managed<wasm::InterpreterHandle>::Allocate(
        isolate, interpreter_size, isolate, *debug_info);
539
    debug_info->set_interpreter_handle(*handle);
540 541
  }

542
  return Handle<Managed<wasm::InterpreterHandle>>::cast(handle)->raw();
543 544
}

545
wasm::InterpreterHandle* GetInterpreterHandle(WasmDebugInfo* debug_info) {
546
  Object* handle_obj = debug_info->interpreter_handle();
547
  DCHECK(!handle_obj->IsUndefined());
548
  return Managed<wasm::InterpreterHandle>::cast(handle_obj)->raw();
549 550
}

551
wasm::InterpreterHandle* GetInterpreterHandleOrNull(WasmDebugInfo* debug_info) {
552
  Object* handle_obj = debug_info->interpreter_handle();
553
  if (handle_obj->IsUndefined()) return nullptr;
554
  return Managed<wasm::InterpreterHandle>::cast(handle_obj)->raw();
555 556
}

557
Handle<FixedArray> GetOrCreateInterpretedFunctions(
558
    Isolate* isolate, Handle<WasmDebugInfo> debug_info) {
559
  Handle<Object> obj(debug_info->interpreted_functions(), isolate);
560 561
  if (!obj->IsUndefined(isolate)) return Handle<FixedArray>::cast(obj);

562
  int num_functions = debug_info->wasm_instance()
563 564
                          ->module_object()
                          ->native_module()
565
                          ->num_functions();
566
  Handle<FixedArray> new_arr = isolate->factory()->NewFixedArray(num_functions);
567
  debug_info->set_interpreted_functions(*new_arr);
568 569 570 571 572
  return new_arr;
}

}  // namespace

573
Handle<WasmDebugInfo> WasmDebugInfo::New(Handle<WasmInstanceObject> instance) {
574 575
  DCHECK(!instance->has_debug_info());
  Factory* factory = instance->GetIsolate()->factory();
576 577 578
  Handle<WasmDebugInfo> debug_info = Handle<WasmDebugInfo>::cast(
      factory->NewStruct(WASM_DEBUG_INFO_TYPE, TENURED));
  debug_info->set_wasm_instance(*instance);
579 580 581 582
  instance->set_debug_info(*debug_info);
  return debug_info;
}

583
wasm::WasmInterpreter* WasmDebugInfo::SetupForTesting(
584
    Handle<WasmInstanceObject> instance_obj) {
585 586
  Handle<WasmDebugInfo> debug_info = WasmDebugInfo::New(instance_obj);
  Isolate* isolate = instance_obj->GetIsolate();
587 588 589 590 591
  // Use the maximum stack size to estimate the maximum size of the interpreter.
  // The interpreter keeps its own stack internally, and the size of the stack
  // should dominate the overall size of the interpreter. We multiply by '2' to
  // account for the growing strategy for the backing store of the stack.
  size_t interpreter_size = FLAG_stack_size * KB * 2;
592 593
  auto interp_handle = Managed<wasm::InterpreterHandle>::Allocate(
      isolate, interpreter_size, isolate, *debug_info);
594
  debug_info->set_interpreter_handle(*interp_handle);
595
  auto ret = interp_handle->raw()->interpreter();
596 597
  ret->SetCallIndirectTestMode();
  return ret;
598 599
}

600 601
void WasmDebugInfo::SetBreakpoint(Handle<WasmDebugInfo> debug_info,
                                  int func_index, int offset) {
602
  Isolate* isolate = debug_info->GetIsolate();
603
  auto* handle = GetOrCreateInterpreterHandle(isolate, debug_info);
604
  RedirectToInterpreter(debug_info, Vector<int>(&func_index, 1));
605
  const wasm::WasmFunction* func = &handle->module()->functions[func_index];
606 607 608 609
  handle->interpreter()->SetBreakpoint(func, offset, true);
}

void WasmDebugInfo::RedirectToInterpreter(Handle<WasmDebugInfo> debug_info,
610
                                          Vector<int> func_indexes) {
611 612 613
  Isolate* isolate = debug_info->GetIsolate();
  // Ensure that the interpreter is instantiated.
  GetOrCreateInterpreterHandle(isolate, debug_info);
614 615
  Handle<FixedArray> interpreted_functions =
      GetOrCreateInterpretedFunctions(isolate, debug_info);
616
  Handle<WasmInstanceObject> instance(debug_info->wasm_instance(), isolate);
617
  wasm::NativeModule* native_module =
618
      instance->module_object()->native_module();
619
  const wasm::WasmModule* module = instance->module();
620

621 622 623 624 625
  // We may modify js wrappers, as well as wasm functions. Hence the 2
  // modification scopes.
  CodeSpaceMemoryModificationScope modification_scope(isolate->heap());
  wasm::NativeModuleModificationScope native_module_modification_scope(
      native_module);
626

627 628
  for (int func_index : func_indexes) {
    DCHECK_LE(0, func_index);
629
    DCHECK_GT(module->functions.size(), func_index);
630 631
    if (!interpreted_functions->get(func_index)->IsUndefined(isolate)) continue;

632
    MaybeHandle<Code> new_code = compiler::CompileWasmInterpreterEntry(
633
        isolate, func_index, module->functions[func_index].sig);
634 635
    const wasm::WasmCode* wasm_new_code = native_module->AddInterpreterEntry(
        new_code.ToHandleChecked(), func_index);
636
    Handle<Foreign> foreign_holder = isolate->factory()->NewForeign(
637
        wasm_new_code->instruction_start(), TENURED);
638 639
    interpreted_functions->set(func_index, *foreign_holder);
  }
640 641
}

642 643 644 645
void WasmDebugInfo::PrepareStep(StepAction step_action) {
  GetInterpreterHandle(this)->PrepareStep(step_action);
}

646 647 648 649
// static
bool WasmDebugInfo::RunInterpreter(Isolate* isolate,
                                   Handle<WasmDebugInfo> debug_info,
                                   Address frame_pointer, int func_index,
650
                                   Address arg_buffer) {
651
  DCHECK_LE(0, func_index);
652 653 654 655
  auto* handle = GetOrCreateInterpreterHandle(isolate, debug_info);
  Handle<WasmInstanceObject> instance(debug_info->wasm_instance(), isolate);
  return handle->Execute(instance, frame_pointer,
                         static_cast<uint32_t>(func_index), arg_buffer);
656 657 658 659 660 661 662
}

std::vector<std::pair<uint32_t, int>> WasmDebugInfo::GetInterpretedStack(
    Address frame_pointer) {
  return GetInterpreterHandle(this)->GetInterpretedStack(frame_pointer);
}

663
wasm::WasmInterpreter::FramePtr WasmDebugInfo::GetInterpretedFrame(
664 665
    Address frame_pointer, int idx) {
  return GetInterpreterHandle(this)->GetInterpretedFrame(frame_pointer, idx);
666
}
667

668 669 670 671
void WasmDebugInfo::Unwind(Address frame_pointer) {
  return GetInterpreterHandle(this)->Unwind(frame_pointer);
}

672
uint64_t WasmDebugInfo::NumInterpretedCalls() {
673
  auto* handle = GetInterpreterHandleOrNull(this);
674 675
  return handle ? handle->NumInterpretedCalls() : 0;
}
676

677
// static
678 679
Handle<JSObject> WasmDebugInfo::GetScopeDetails(
    Handle<WasmDebugInfo> debug_info, Address frame_pointer, int frame_index) {
680
  auto* interp_handle = GetInterpreterHandle(*debug_info);
681
  return interp_handle->GetScopeDetails(frame_pointer, frame_index, debug_info);
682
}
683 684 685 686

// static
Handle<JSObject> WasmDebugInfo::GetGlobalScopeObject(
    Handle<WasmDebugInfo> debug_info, Address frame_pointer, int frame_index) {
687
  auto* interp_handle = GetInterpreterHandle(*debug_info);
688 689 690 691 692 693 694
  auto frame = interp_handle->GetInterpretedFrame(frame_pointer, frame_index);
  return interp_handle->GetGlobalScopeObject(frame.get(), debug_info);
}

// static
Handle<JSObject> WasmDebugInfo::GetLocalScopeObject(
    Handle<WasmDebugInfo> debug_info, Address frame_pointer, int frame_index) {
695
  auto* interp_handle = GetInterpreterHandle(*debug_info);
696 697 698
  auto frame = interp_handle->GetInterpretedFrame(frame_pointer, frame_index);
  return interp_handle->GetLocalScopeObject(frame.get(), debug_info);
}
699 700 701

// static
Handle<JSFunction> WasmDebugInfo::GetCWasmEntry(
702
    Handle<WasmDebugInfo> debug_info, wasm::FunctionSig* sig) {
703 704 705 706 707 708
  Isolate* isolate = debug_info->GetIsolate();
  DCHECK_EQ(debug_info->has_c_wasm_entries(),
            debug_info->has_c_wasm_entry_map());
  if (!debug_info->has_c_wasm_entries()) {
    auto entries = isolate->factory()->NewFixedArray(4, TENURED);
    debug_info->set_c_wasm_entries(*entries);
709 710
    size_t map_size = 0;  // size estimate not so important here.
    auto managed_map = Managed<wasm::SignatureMap>::Allocate(isolate, map_size);
711 712 713
    debug_info->set_c_wasm_entry_map(*managed_map);
  }
  Handle<FixedArray> entries(debug_info->c_wasm_entries(), isolate);
714
  wasm::SignatureMap* map = debug_info->c_wasm_entry_map()->raw();
715
  int32_t index = map->Find(*sig);
716
  if (index == -1) {
717
    index = static_cast<int32_t>(map->FindOrInsert(*sig));
718 719 720 721 722 723
    if (index == entries->length()) {
      entries = isolate->factory()->CopyFixedArrayAndGrow(
          entries, entries->length(), TENURED);
      debug_info->set_c_wasm_entries(*entries);
    }
    DCHECK(entries->get(index)->IsUndefined(isolate));
724 725
    Handle<Code> new_entry_code =
        compiler::CompileCWasmEntry(isolate, sig).ToHandleChecked();
726 727 728 729 730
    Handle<WasmExportedFunctionData> function_data =
        Handle<WasmExportedFunctionData>::cast(isolate->factory()->NewStruct(
            WASM_EXPORTED_FUNCTION_DATA_TYPE, TENURED));
    function_data->set_wrapper_code(*new_entry_code);
    function_data->set_instance(debug_info->wasm_instance());
731
    function_data->set_jump_table_offset(-1);
732
    function_data->set_function_index(-1);
733 734
    Handle<String> name = isolate->factory()->InternalizeOneByteString(
        STATIC_CHAR_VECTOR("c-wasm-entry"));
735
    NewFunctionArgs args = NewFunctionArgs::ForWasm(
736
        name, function_data, isolate->sloppy_function_map());
737
    Handle<JSFunction> new_entry = isolate->factory()->NewFunction(args);
738
    new_entry->set_context(debug_info->wasm_instance()->native_context());
739 740
    new_entry->shared()->set_internal_formal_parameter_count(
        compiler::CWasmEntryParameters::kNumParameters);
741 742
    entries->set(index, *new_entry);
  }
743
  return handle(JSFunction::cast(entries->get(index)), isolate);
744
}
745 746 747

}  // namespace internal
}  // namespace v8