summaryrefslogtreecommitdiff
path: root/chromium/v8/src/wasm/wasm-debug-evaluate.cc
blob: a8c4cf2c40dbcd7896a988c4ce4d2994e41933f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Copyright 2020 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.

#include "src/wasm/wasm-debug-evaluate.h"

#include <algorithm>
#include <limits>

#include "src/api/api-inl.h"
#include "src/codegen/machine-type.h"
#include "src/compiler/wasm-compiler.h"
#include "src/execution/frames-inl.h"
#include "src/wasm/value-type.h"
#include "src/wasm/wasm-arguments.h"
#include "src/wasm/wasm-constants.h"
#include "src/wasm/wasm-debug.h"
#include "src/wasm/wasm-module.h"
#include "src/wasm/wasm-objects.h"
#include "src/wasm/wasm-result.h"
#include "src/wasm/wasm-value.h"

namespace v8 {
namespace internal {
namespace wasm {
namespace {

static Handle<String> V8String(Isolate* isolate, const char* str) {
  return isolate->factory()->NewStringFromAsciiChecked(str);
}

static bool CheckSignature(ValueType return_type,
                           std::initializer_list<ValueType> argument_types,
                           const FunctionSig* sig, ErrorThrower* thrower) {
  if (sig->return_count() != 1 && return_type != kWasmBottom) {
    thrower->CompileError("Invalid return type. Got none, expected %s",
                          return_type.type_name().c_str());
    return false;
  }

  if (sig->return_count() == 1) {
    if (sig->GetReturn(0) != return_type) {
      thrower->CompileError("Invalid return type. Got %s, expected %s",
                            sig->GetReturn(0).type_name().c_str(),
                            return_type.type_name().c_str());
      return false;
    }
  }

  if (sig->parameter_count() != argument_types.size()) {
    thrower->CompileError("Invalid number of arguments. Expected %zu, got %zu",
                          sig->parameter_count(), argument_types.size());
    return false;
  }
  size_t p = 0;
  for (ValueType argument_type : argument_types) {
    if (sig->GetParam(p) != argument_type) {
      thrower->CompileError(
          "Invalid argument type for argument %zu. Got %s, expected %s", p,
          sig->GetParam(p).type_name().c_str(),
          argument_type.type_name().c_str());
      return false;
    }
    ++p;
  }
  return true;
}

static bool CheckRangeOutOfBounds(uint32_t offset, uint32_t size,
                                  size_t allocation_size,
                                  wasm::ErrorThrower* thrower) {
  if (size > std::numeric_limits<uint32_t>::max() - offset) {
    thrower->RuntimeError("Overflowing memory range\n");
    return true;
  }
  if (offset + size > allocation_size) {
    thrower->RuntimeError("Illegal access to out-of-bounds memory");
    return true;
  }
  return false;
}

class DebugEvaluatorProxy {
 public:
  explicit DebugEvaluatorProxy(Isolate* isolate, StandardFrame* frame)
      : isolate_(isolate), frame_(frame) {}

  static void GetMemoryTrampoline(
      const v8::FunctionCallbackInfo<v8::Value>& args) {
    DebugEvaluatorProxy& proxy = GetProxy(args);

    uint32_t offset = proxy.GetArgAsUInt32(args, 0);
    uint32_t size = proxy.GetArgAsUInt32(args, 1);
    uint32_t result = proxy.GetArgAsUInt32(args, 2);

    proxy.GetMemory(offset, size, result);
  }

  // void __getMemory(uint32_t offset, uint32_t size, void* result);
  void GetMemory(uint32_t offset, uint32_t size, uint32_t result) {
    wasm::ScheduledErrorThrower thrower(isolate_, "debug evaluate proxy");
    // Check all overflows.
    if (CheckRangeOutOfBounds(offset, size, debuggee_->memory_size(),
                              &thrower) ||
        CheckRangeOutOfBounds(result, size, evaluator_->memory_size(),
                              &thrower)) {
      return;
    }

    std::memcpy(&evaluator_->memory_start()[result],
                &debuggee_->memory_start()[offset], size);
  }

  // void* __sbrk(intptr_t increment);
  uint32_t Sbrk(uint32_t increment) {
    if (increment > 0 && evaluator_->memory_size() <=
                             std::numeric_limits<uint32_t>::max() - increment) {
      Handle<WasmMemoryObject> memory(evaluator_->memory_object(), isolate_);
      uint32_t new_pages =
          (increment - 1 + wasm::kWasmPageSize) / wasm::kWasmPageSize;
      WasmMemoryObject::Grow(isolate_, memory, new_pages);
    }
    return static_cast<uint32_t>(evaluator_->memory_size());
  }

  static void SbrkTrampoline(const v8::FunctionCallbackInfo<v8::Value>& args) {
    auto& proxy = GetProxy(args);
    uint32_t size = proxy.GetArgAsUInt32(args, 0);

    uint32_t result = proxy.Sbrk(size);
    args.GetReturnValue().Set(result);
  }

  template <typename T>
  void write_result(const WasmValue& result, uint32_t result_offset) {
    wasm::ScheduledErrorThrower thrower(isolate_, "debug evaluate proxy");
    T val = result.to<T>();
    static_assert(static_cast<uint32_t>(sizeof(T)) == sizeof(T),
                  "Unexpected size");
    if (CheckRangeOutOfBounds(result_offset, sizeof(T),
                              evaluator_->memory_size(), &thrower)) {
      return;
    }
    memcpy(&evaluator_->memory_start()[result_offset], &val, sizeof(T));
  }

  // void __getLocal(uint32_t local,  void* result);
  void GetLocal(uint32_t local, uint32_t result_offset) {
    WasmValue result = LoadLocalValue(local);

    switch (result.type().kind()) {
      case ValueType::kI32:
        write_result<uint32_t>(result, result_offset);
        break;
      case ValueType::kI64:
        write_result<int64_t>(result, result_offset);
        break;
      case ValueType::kF32:
        write_result<float>(result, result_offset);
        break;
      case ValueType::kF64:
        write_result<double>(result, result_offset);
        break;
      default:
        UNIMPLEMENTED();
    }
  }

  static void GetLocalTrampoline(
      const v8::FunctionCallbackInfo<v8::Value>& args) {
    auto& proxy = GetProxy(args);
    uint32_t local = proxy.GetArgAsUInt32(args, 0);
    uint32_t result = proxy.GetArgAsUInt32(args, 1);

    proxy.GetLocal(local, result);
  }

  Handle<JSObject> CreateImports() {
    Handle<JSObject> imports_obj =
        isolate_->factory()->NewJSObject(isolate_->object_function());
    Handle<JSObject> import_module_obj =
        isolate_->factory()->NewJSObject(isolate_->object_function());
    Object::SetProperty(isolate_, imports_obj, V8String(isolate_, "env"),
                        import_module_obj)
        .Assert();

    AddImport(import_module_obj, "__getLocal",
              DebugEvaluatorProxy::GetLocalTrampoline);
    AddImport(import_module_obj, "__getMemory",
              DebugEvaluatorProxy::GetMemoryTrampoline);
    AddImport(import_module_obj, "__sbrk", DebugEvaluatorProxy::SbrkTrampoline);

    return imports_obj;
  }

  void SetInstances(Handle<WasmInstanceObject> evaluator,
                    Handle<WasmInstanceObject> debuggee) {
    evaluator_ = evaluator;
    debuggee_ = debuggee;
  }

 private:
  WasmValue LoadLocalValue(uint32_t local) {
    DCHECK(frame_->is_wasm());
    wasm::DebugInfo* debug_info =
        WasmFrame::cast(frame_)->native_module()->GetDebugInfo();
    return debug_info->GetLocalValue(local, frame_->pc(), frame_->fp(),
                                     frame_->callee_fp());
  }

  uint32_t GetArgAsUInt32(const v8::FunctionCallbackInfo<v8::Value>& args,
                          int index) {
    // No type/range checks needed on his because this is only called for {args}
    // where we have performed a signature check via {VerifyEvaluatorInterface}
    double number = Utils::OpenHandle(*args[index])->Number();
    return static_cast<uint32_t>(number);
  }

  static DebugEvaluatorProxy& GetProxy(
      const v8::FunctionCallbackInfo<v8::Value>& args) {
    return *reinterpret_cast<DebugEvaluatorProxy*>(
        args.Data().As<v8::External>()->Value());
  }

  template <typename CallableT>
  void AddImport(Handle<JSObject> import_module_obj, const char* function_name,
                 CallableT callback) {
    v8::Isolate* api_isolate = reinterpret_cast<v8::Isolate*>(isolate_);
    v8::Local<v8::Context> context = api_isolate->GetCurrentContext();
    std::string data;
    v8::Local<v8::Function> v8_function =
        v8::Function::New(context, callback,
                          v8::External::New(api_isolate, this))
            .ToLocalChecked();

    auto wrapped_function = Utils::OpenHandle(*v8_function);

    Object::SetProperty(isolate_, import_module_obj,
                        V8String(isolate_, function_name), wrapped_function)
        .Assert();
  }

  Isolate* isolate_;
  StandardFrame* frame_;
  Handle<WasmInstanceObject> evaluator_;
  Handle<WasmInstanceObject> debuggee_;
};

static bool VerifyEvaluatorInterface(const WasmModule* raw_module,
                                     const ModuleWireBytes& bytes,
                                     ErrorThrower* thrower) {
  for (const WasmImport imported : raw_module->import_table) {
    if (imported.kind != ImportExportKindCode::kExternalFunction) continue;
    const WasmFunction& F = raw_module->functions.at(imported.index);
    std::string module_name(bytes.start() + imported.module_name.offset(),
                            bytes.start() + imported.module_name.end_offset());
    std::string field_name(bytes.start() + imported.field_name.offset(),
                           bytes.start() + imported.field_name.end_offset());

    if (module_name == "env") {
      if (field_name == "__getMemory") {
        // void __getMemory(uint32_t offset, uint32_t size, void* result);
        if (CheckSignature(kWasmBottom, {kWasmI32, kWasmI32, kWasmI32}, F.sig,
                           thrower)) {
          continue;
        }
      } else if (field_name == "__getLocal") {
        // void __getLocal(uint32_t local,  void* result)
        if (CheckSignature(kWasmBottom, {kWasmI32, kWasmI32}, F.sig, thrower)) {
          continue;
        }
      } else if (field_name == "__debug") {
        // void __debug(uint32_t flag, uint32_t value)
        if (CheckSignature(kWasmBottom, {kWasmI32, kWasmI32}, F.sig, thrower)) {
          continue;
        }
      } else if (field_name == "__sbrk") {
        // uint32_t __sbrk(uint32_t increment)
        if (CheckSignature(kWasmI32, {kWasmI32}, F.sig, thrower)) {
          continue;
        }
      }
    }

    if (!thrower->error()) {
      thrower->LinkError("Unknown import \"%s\" \"%s\"", module_name.c_str(),
                         field_name.c_str());
    }

    return false;
  }
  for (const WasmExport& exported : raw_module->export_table) {
    if (exported.kind != ImportExportKindCode::kExternalFunction) continue;
    const WasmFunction& F = raw_module->functions.at(exported.index);
    std::string field_name(bytes.start() + exported.name.offset(),
                           bytes.start() + exported.name.end_offset());
    if (field_name == "wasm_format") {
      if (!CheckSignature(kWasmI32, {}, F.sig, thrower)) return false;
    }
  }
  return true;
}
}  // namespace

Maybe<std::string> DebugEvaluateImpl(
    Vector<const byte> snippet, Handle<WasmInstanceObject> debuggee_instance,
    StandardFrame* frame) {
  Isolate* isolate = debuggee_instance->GetIsolate();
  HandleScope handle_scope(isolate);
  WasmEngine* engine = isolate->wasm_engine();
  wasm::ErrorThrower thrower(isolate, "wasm debug evaluate");

  // Create module object.
  wasm::ModuleWireBytes bytes(snippet);
  wasm::WasmFeatures features = wasm::WasmFeatures::FromIsolate(isolate);
  Handle<WasmModuleObject> evaluator_module;
  if (!engine->SyncCompile(isolate, features, &thrower, bytes)
           .ToHandle(&evaluator_module)) {
    return Nothing<std::string>();
  }

  // Verify interface.
  const WasmModule* raw_module = evaluator_module->module();
  if (!VerifyEvaluatorInterface(raw_module, bytes, &thrower)) {
    return Nothing<std::string>();
  }

  // Set up imports.
  DebugEvaluatorProxy proxy(isolate, frame);
  Handle<JSObject> imports = proxy.CreateImports();

  // Instantiate Module.
  Handle<WasmInstanceObject> evaluator_instance;
  if (!engine->SyncInstantiate(isolate, &thrower, evaluator_module, imports, {})
           .ToHandle(&evaluator_instance)) {
    return Nothing<std::string>();
  }

  proxy.SetInstances(evaluator_instance, debuggee_instance);

  Handle<JSObject> exports_obj(evaluator_instance->exports_object(), isolate);
  Handle<Object> entry_point_obj;
  bool get_property_success =
      Object::GetProperty(isolate, exports_obj,
                          V8String(isolate, "wasm_format"))
          .ToHandle(&entry_point_obj);
  if (!get_property_success ||
      !WasmExportedFunction::IsWasmExportedFunction(*entry_point_obj)) {
    thrower.LinkError("Missing export: \"wasm_format\"");
    return Nothing<std::string>();
  }
  Handle<WasmExportedFunction> entry_point =
      Handle<WasmExportedFunction>::cast(entry_point_obj);

  // TODO(wasm): Cache this code.
  Handle<Code> wasm_entry =
      compiler::CompileCWasmEntry(isolate, entry_point->sig());

  CWasmArgumentsPacker packer(4 /* uint32_t return value, no parameters. */);
  Execution::CallWasm(isolate, wasm_entry, entry_point->GetWasmCallTarget(),
                      evaluator_instance, packer.argv());
  if (isolate->has_pending_exception()) return Nothing<std::string>();

  uint32_t offset = packer.Pop<uint32_t>();
  if (CheckRangeOutOfBounds(offset, 0, evaluator_instance->memory_size(),
                            &thrower)) {
    return Nothing<std::string>();
  }

  // Copy the zero-terminated string result but don't overflow.
  std::string result;
  byte* heap = evaluator_instance->memory_start() + offset;
  for (; offset < evaluator_instance->memory_size(); ++offset, ++heap) {
    if (*heap == 0) return Just(result);
    result.push_back(*heap);
  }

  thrower.RuntimeError("The evaluation returned an invalid result");
  return Nothing<std::string>();
}

MaybeHandle<String> DebugEvaluate(Vector<const byte> snippet,
                                  Handle<WasmInstanceObject> debuggee_instance,
                                  StandardFrame* frame) {
  Maybe<std::string> result =
      DebugEvaluateImpl(snippet, debuggee_instance, frame);
  if (result.IsNothing()) return {};
  std::string result_str = result.ToChecked();
  return V8String(debuggee_instance->GetIsolate(), result_str.c_str());
}

}  // namespace wasm
}  // namespace internal
}  // namespace v8