summaryrefslogtreecommitdiff
path: root/deps/v8/src/wasm/wasm-interpreter.h
blob: 4eb0675aba805d50a544f70e724cbf08d12427dd (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
// 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.

#ifndef V8_WASM_WASM_INTERPRETER_H_
#define V8_WASM_WASM_INTERPRETER_H_

#include <memory>

#include "src/wasm/wasm-opcodes.h"
#include "src/wasm/wasm-value.h"
#include "src/zone/zone-containers.h"

namespace v8 {

namespace internal {
class WasmInstanceObject;

namespace wasm {

// Forward declarations.
struct ModuleWireBytes;
struct WasmFunction;
struct WasmModule;
class WasmInterpreterInternals;

using pc_t = size_t;
using sp_t = size_t;
using pcdiff_t = int32_t;
using spdiff_t = uint32_t;

constexpr pc_t kInvalidPc = 0x80000000;

struct ControlTransferEntry {
  // Distance from the instruction to the label to jump to (forward, but can be
  // negative).
  pcdiff_t pc_diff;
  // Delta by which to decrease the stack height.
  spdiff_t sp_diff;
  // Arity of the block we jump to.
  uint32_t target_arity;
};

using ControlTransferMap = ZoneMap<pc_t, ControlTransferEntry>;

// Representation of frames within the interpreter.
//
// Layout of a frame:
// -----------------
// stack slot #N  ‾\.
// ...             |  stack entries: GetStackHeight(); GetStackValue()
// stack slot #0  _/·
// local #L       ‾\.
// ...             |  locals: GetLocalCount(); GetLocalValue()
// local #P+1      |
// param #P        |   ‾\.
// ...             |    | parameters: GetParameterCount(); GetLocalValue()
// param #0       _/·  _/·
// -----------------
//
class V8_EXPORT_PRIVATE InterpretedFrame {
 public:
  const WasmFunction* function() const;
  int pc() const;

  int GetParameterCount() const;
  int GetLocalCount() const;
  int GetStackHeight() const;
  WasmValue GetLocalValue(int index) const;
  WasmValue GetStackValue(int index) const;

 private:
  friend class WasmInterpreter;
  // Don't instante InterpretedFrames; they will be allocated as
  // InterpretedFrameImpl in the interpreter implementation.
  InterpretedFrame() = delete;
  DISALLOW_COPY_AND_ASSIGN(InterpretedFrame);
};

// Deleter struct to delete the underlying InterpretedFrameImpl without
// violating language specifications.
struct V8_EXPORT_PRIVATE InterpretedFrameDeleter {
  void operator()(InterpretedFrame* ptr);
};

// An interpreter capable of executing WebAssembly.
class V8_EXPORT_PRIVATE WasmInterpreter {
 public:
  // State machine for a Thread:
  //    +----------------------------------------------------------+
  //    |                    +--------Run()/Step()---------+       |
  //    V                    V                             |       |
  // STOPPED ---Run()-->  RUNNING  ------Pause()-----+-> PAUSED <--+
  //    ^                 | | | |                   /              |
  //    +--- Exception ---+ | | +--- Breakpoint ---+       RaiseException() <--+
  //                        | |                                                |
  //                        | +---------- Trap --------------> TRAPPED --------+
  //                        +----------- Finish -------------> FINISHED
  enum State { STOPPED, RUNNING, PAUSED, FINISHED, TRAPPED };

  // Tells a thread to pause after certain instructions.
  enum BreakFlag : uint8_t {
    None = 0,
    AfterReturn = 1 << 0,
    AfterCall = 1 << 1
  };

  using FramePtr = std::unique_ptr<InterpretedFrame, InterpretedFrameDeleter>;

  // Representation of a thread in the interpreter.
  class V8_EXPORT_PRIVATE Thread {
    // Don't instante Threads; they will be allocated as ThreadImpl in the
    // interpreter implementation.
    Thread() = delete;

   public:
    enum ExceptionHandlingResult { HANDLED, UNWOUND };

    // Execution control.
    State state();
    void InitFrame(const WasmFunction* function, WasmValue* args);
    // Pass -1 as num_steps to run till completion, pause or breakpoint.
    State Run(int num_steps = -1);
    State Step() { return Run(1); }
    void Pause();
    void Reset();

    // Raise an exception in the current activation and unwind the stack
    // accordingly. Return whether the exception was handled inside wasm:
    //  - HANDLED: Activation at handler position and in {PAUSED} state.
    //  - UNWOUND: Frames unwound, exception pending, and in {STOPPED} state.
    ExceptionHandlingResult RaiseException(Isolate*, Handle<Object> exception);

    // Stack inspection and modification.
    pc_t GetBreakpointPc();
    // TODO(clemensb): Make this uint32_t.
    int GetFrameCount();
    // The InterpretedFrame is only valid as long as the Thread is paused.
    FramePtr GetFrame(int index);
    WasmValue GetReturnValue(int index = 0);
    TrapReason GetTrapReason();

    uint32_t GetGlobalCount();
    WasmValue GetGlobalValue(uint32_t index);

    // Returns true if the thread executed an instruction which may produce
    // nondeterministic results, e.g. float div, float sqrt, and float mul,
    // where the sign bit of a NaN is nondeterministic.
    bool PossibleNondeterminism();

    // Returns the number of calls / function frames executed on this thread.
    uint64_t NumInterpretedCalls();

    // Thread-specific breakpoints.
    // TODO(wasm): Implement this once we support multiple threads.
    // bool SetBreakpoint(const WasmFunction* function, int pc, bool enabled);
    // bool GetBreakpoint(const WasmFunction* function, int pc);

    void AddBreakFlags(uint8_t flags);
    void ClearBreakFlags();

    // Each thread can have multiple activations, each represented by a portion
    // of the stack frames of this thread. StartActivation returns the id
    // (counting from 0 up) of the started activation.
    // Activations must be properly stacked, i.e. if FinishActivation is called,
    // the given id must the the latest activation on the stack.
    uint32_t NumActivations();
    uint32_t StartActivation();
    void FinishActivation(uint32_t activation_id);
    // Return the frame base of the given activation, i.e. the number of frames
    // when this activation was started.
    uint32_t ActivationFrameBase(uint32_t activation_id);
  };

  MOVE_ONLY_NO_DEFAULT_CONSTRUCTOR(WasmInterpreter);

  WasmInterpreter(Isolate* isolate, const WasmModule* module,
                  const ModuleWireBytes& wire_bytes,
                  Handle<WasmInstanceObject> instance);

  ~WasmInterpreter();

  //==========================================================================
  // Execution controls.
  //==========================================================================
  void Run();
  void Pause();

  // Set a breakpoint at {pc} in {function} to be {enabled}. Returns the
  // previous state of the breakpoint at {pc}.
  bool SetBreakpoint(const WasmFunction* function, pc_t pc, bool enabled);

  // Gets the current state of the breakpoint at {function}.
  bool GetBreakpoint(const WasmFunction* function, pc_t pc);

  // Enable or disable tracing for {function}. Return the previous state.
  bool SetTracing(const WasmFunction* function, bool enabled);

  //==========================================================================
  // Thread iteration and inspection.
  //==========================================================================
  int GetThreadCount();
  Thread* GetThread(int id);

  //==========================================================================
  // Testing functionality.
  //==========================================================================
  // Manually adds a function to this interpreter. The func_index of the
  // function must match the current number of functions.
  void AddFunctionForTesting(const WasmFunction* function);
  // Manually adds code to the interpreter for the given function.
  void SetFunctionCodeForTesting(const WasmFunction* function,
                                 const byte* start, const byte* end);

  // Computes the control transfers for the given bytecode. Used internally in
  // the interpreter, but exposed for testing.
  static ControlTransferMap ComputeControlTransfersForTesting(
      Zone* zone, const WasmModule* module, const byte* start, const byte* end);

 private:
  Zone zone_;
  std::unique_ptr<WasmInterpreterInternals> internals_;
};

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

#endif  // V8_WASM_WASM_INTERPRETER_H_