Coverage Report

Created: 2026-12-01 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasm3/source/m3_env.h
Line
Count
Source
1
//
2
//  m3_env.h
3
//
4
//  Created by Steven Massey on 4/19/19.
5
//  Copyright © 2019 Steven Massey. All rights reserved.
6
//
7
8
#ifndef m3_env_h
9
#define m3_env_h
10
11
#include "wasm3.h"
12
#include "m3_code.h"
13
#include "m3_compile.h"
14
15
d_m3BeginExternC
16
17
typedef struct ValCtx ValCtx;   // the validator's scratch, defined in m3_validate.c
18
19
20
//---------------------------------------------------------------------------------------------------------------------------------
21
22
// Page counts are u64 because a memory64 type may declare up to 2^48 pages.
23
// Nothing near that can be backed, but the module still has to parse and
24
// validate; it is instantiation that fails.
25
typedef struct M3MemoryInfo {
26
    u64  initPages;
27
    u64  maxPages;
28
    u32  pageSize;
29
    bool hasMax;         // a declared maximum of 0 is not the same as none
30
    bool isMemory64;     // addressed by i64 rather than i32
31
    bool isShared;       // the threads proposal: a maximum is required
32
} M3MemoryInfo;
33
34
35
// One linear memory. Memories belong to the module that declares them, not to
36
// the runtime: two modules loaded into the same runtime each get their own, and
37
// the interpreter reaches the one it is currently running against through the
38
// _mem pseudo-register (see M3MemoryHeader).
39
//
40
// Every entry is individually allocated so that a slot may later be pointed at
41
// a memory another module owns - growing one has to be visible through every
42
// name it has. 'owner' says which module allocated it, and so which module
43
// frees it.
44
typedef struct M3Memory {
45
    M3MemoryHeader*  mallocated;
46
47
    u64              numPages;
48
    u64              maxPages;
49
    u64              initPages;
50
    u32              pageSize;
51
    bool             hasMax;         // see M3MemoryInfo
52
    bool             isMemory64;     // addressed by i64 rather than i32
53
    bool             isShared;       // see M3MemoryInfo
54
55
    struct M3Module* owner;          // the module that allocated it
56
    M3ImportInfo     import;         // when declared as an import
57
    bool             imported;
58
59
#if d_m3GuardedMemory
60
    // The slot of the guarded arena this memory's bytes live in, and so what
61
    // 'mallocated' points into rather than the heap - see Guard_TakeSlot
62
    void* guardSlot;
63
#endif
64
} M3Memory;
65
66
typedef M3Memory* IM3Memory;
67
68
// The value type a memory's addresses, page counts and lengths are expressed
69
// in. Every instruction naming the memory takes and returns that type.
70
static inline
71
m3type_t Memory_AddrType (const M3Memory* i_memory)
72
36.2k
{
73
36.2k
    return i_memory->isMemory64 ? c_m3Type_i64 : c_m3Type_i32;
74
36.2k
}
Unexecuted instantiation: fuzzer.c:Memory_AddrType
Unexecuted instantiation: m3_core.c:Memory_AddrType
Unexecuted instantiation: m3_env.c:Memory_AddrType
Unexecuted instantiation: m3_function.c:Memory_AddrType
Unexecuted instantiation: m3_info.c:Memory_AddrType
Unexecuted instantiation: m3_module.c:Memory_AddrType
Unexecuted instantiation: m3_parse.c:Memory_AddrType
Unexecuted instantiation: m3_bind.c:Memory_AddrType
Unexecuted instantiation: m3_code.c:Memory_AddrType
m3_compile.c:Memory_AddrType
Line
Count
Source
72
4.92k
{
73
4.92k
    return i_memory->isMemory64 ? c_m3Type_i64 : c_m3Type_i32;
74
4.92k
}
m3_validate.c:Memory_AddrType
Line
Count
Source
72
31.3k
{
73
31.3k
    return i_memory->isMemory64 ? c_m3Type_i64 : c_m3Type_i32;
74
31.3k
}
75
76
77
// A module that declares no custom page size means the default one. The parser
78
// leaves that as zero, and InitMemory only fills it in when it allocates, so a
79
// memory has to be asked rather than read directly until then.
80
static inline
81
u32 Memory_PageSize (const M3Memory* i_memory)
82
8.09k
{
83
8.09k
    return i_memory->pageSize ? i_memory->pageSize : d_m3DefaultMemPageSize;
84
8.09k
}
Unexecuted instantiation: fuzzer.c:Memory_PageSize
Unexecuted instantiation: m3_core.c:Memory_PageSize
m3_env.c:Memory_PageSize
Line
Count
Source
82
8.09k
{
83
8.09k
    return i_memory->pageSize ? i_memory->pageSize : d_m3DefaultMemPageSize;
84
8.09k
}
Unexecuted instantiation: m3_function.c:Memory_PageSize
Unexecuted instantiation: m3_info.c:Memory_PageSize
Unexecuted instantiation: m3_module.c:Memory_PageSize
Unexecuted instantiation: m3_parse.c:Memory_PageSize
Unexecuted instantiation: m3_bind.c:Memory_PageSize
Unexecuted instantiation: m3_code.c:Memory_PageSize
Unexecuted instantiation: m3_compile.c:Memory_PageSize
Unexecuted instantiation: m3_validate.c:Memory_PageSize
85
86
87
//---------------------------------------------------------------------------------------------------------------------------------
88
89
// A table type as the module declared it. Sizes stay u32 - a table64 may name
90
// far more entries than that, but d_m3MaxSaneTableSize refuses anything near
91
// the limit long before it matters.
92
typedef struct M3TableInfo {
93
    m3type_t elemType;
94
    u32      initSize;
95
    u32      maxSize;
96
    bool     hasMax;         // a declared maximum of 0 is not the same as none
97
    bool     isTable64;      // indexed by i64 rather than i32
98
} M3TableInfo;
99
100
101
// A table's elements are opaque pointer-sized references: IM3Function for a
102
// funcref table, a host handle for an externref one. NULL is the null reference.
103
typedef struct M3Table {
104
    void**           elements;
105
    u32              size;
106
    u32              maxSize;            // 0 when the module declared no maximum
107
    m3type_t         type;
108
109
    // Every slot starts out holding this, rather than null. A table whose
110
    // element type is not nullable has to say what to fill itself with.
111
    bytes_t          initExpr;
112
    u32              initExprSize;
113
114
    u32              initSize;       // the declared minimum
115
    bool             hasMax;         // a declared maximum of 0 is not the same as none
116
    bool             isTable64;      // indexed by i64 rather than i32
117
118
    struct M3Module* owner;          // the module that allocated it
119
    M3ImportInfo     import;         // when declared as an import
120
    bool             imported;
121
} M3Table;
122
123
typedef M3Table* IM3Table;
124
125
// The value type a table's indexes and sizes are expressed in - table64 is the
126
// same choice as memory64, made per table.
127
static inline
128
m3type_t Table_AddrType (const M3Table* i_table)
129
5.02k
{
130
5.02k
    return i_table->isTable64 ? c_m3Type_i64 : c_m3Type_i32;
131
5.02k
}
Unexecuted instantiation: fuzzer.c:Table_AddrType
Unexecuted instantiation: m3_core.c:Table_AddrType
Unexecuted instantiation: m3_env.c:Table_AddrType
Unexecuted instantiation: m3_function.c:Table_AddrType
Unexecuted instantiation: m3_info.c:Table_AddrType
Unexecuted instantiation: m3_module.c:Table_AddrType
Unexecuted instantiation: m3_parse.c:Table_AddrType
Unexecuted instantiation: m3_bind.c:Table_AddrType
Unexecuted instantiation: m3_code.c:Table_AddrType
m3_compile.c:Table_AddrType
Line
Count
Source
129
2.60k
{
130
2.60k
    return i_table->isTable64 ? c_m3Type_i64 : c_m3Type_i32;
131
2.60k
}
m3_validate.c:Table_AddrType
Line
Count
Source
129
2.42k
{
130
2.42k
    return i_table->isTable64 ? c_m3Type_i64 : c_m3Type_i32;
131
2.42k
}
132
133
// Element segment modes, from the low two bits of the segment's flags
134
typedef enum {
135
    c_m3Elem_active      = 0,        // table 0
136
    c_m3Elem_passive     = 1,
137
    c_m3Elem_activeIdx   = 2,        // explicit table index
138
    c_m3Elem_declarative = 3
139
} M3ElementMode;
140
141
typedef struct M3ElementSegment {
142
    bytes_t  initExpr;       // active segments only: the offset
143
    bytes_t  elements;       // funcidx list, or const exprs when isExpr
144
    void**   resolved;       // passive segments only, for table.init
145
146
    u32      initExprSize;
147
    u32      numElements;
148
    u32      tableIndex;
149
150
    m3type_t type;
151
    u8       mode;
152
    bool     isExpr;
153
    bool     dropped;
154
} M3ElementSegment;
155
156
typedef struct M3DataSegment {
157
    const u8* initExpr;           // wasm code
158
    const u8* data;
159
160
    u32       initExprSize;
161
    u32       memoryRegion;
162
    u32       size;
163
164
    bool      isPassive;
165
    bool      dropped;            // active segments are dropped once instantiated
166
} M3DataSegment;
167
168
//---------------------------------------------------------------------------------------------------------------------------------
169
170
typedef struct M3Global {
171
    M3ImportInfo     import;
172
173
    // An import linked to another module's export: the global that actually
174
    // holds the value. Reads and writes go there, so a mutable global stays one
175
    // cell seen under two names. NULL for anything else, including an import a
176
    // host supplied a value for through m3_LinkGlobal.
177
    struct M3Global* resolved;
178
179
    union {
180
        i32 i32Value;
181
        i64 i64Value;
182
#if d_m3HasFloat
183
        f64 f64Value;
184
        f32 f32Value;
185
#endif
186
        void* refValue;
187
    };
188
189
    bytes_t  initExpr;       // wasm code
190
    u32      initExprSize;
191
    m3type_t type;
192
    bool     imported;
193
    bool     isMutable;
194
} M3Global;
195
196
197
//---------------------------------------------------------------------------------------------------------------------------------
198
199
#if d_m3HasExceptionHandling || d_m3HasStackSwitching
200
201
// An exception / control tag, as the tag section declares it. Tags are compared by
202
// identity, and this struct's address is that identity.
203
typedef struct M3Tag {
204
    M3ImportInfo  import;
205
    IM3FuncType   type;           // params are the payload; results are empty for EH, can be non-empty for stack switching
206
    struct M3Tag* resolved;
207
    bool          imported;
208
} M3Tag;
209
210
// A tag m3_NewTag made. It belongs to the runtime rather than to a module, and
211
// is linked in front of the runtime's others rather than kept in an array, which
212
// would move the tags - and with them their identities - whenever it grew.
213
typedef struct M3HostTag {
214
    struct M3HostTag* next;
215
    M3Tag             tag;
216
} M3HostTag;
217
218
#endif // d_m3HasExceptionHandling || d_m3HasStackSwitching
219
220
221
#if d_m3HasExceptionHandling
222
223
// A thrown exception: the tag that identifies it plus the payload the throw
224
// site popped off the stack, one u64 per value (32-bit values are stored
225
// zero-extended, floats as their bit pattern).
226
//
227
// Exception objects belong to the runtime, not to the code that caught them.
228
//
229
// One caught by a clause that does not reify it - catch or catch_all rather
230
// than their _ref forms - is unreachable the moment its payload has been copied
231
// out, and is released there. Anything else stays on the runtime's list until
232
// the outermost m3_Call() returns, which is the last moment an exnref can still
233
// be reached from the Wasm stack. An exnref parked in a global or a table
234
// outlives that and is left dangling - wasm3 has no collector to say otherwise.
235
typedef struct M3Exception {
236
    struct M3Exception* next;           // the runtime's allocation list,
237
    struct M3Exception* prev;           //   doubly linked so one can leave early
238
    IM3Tag              tag;
239
    u32                 numArgs;
240
    bool                reified;        // an exnref to this has been handed out
241
    u64                 args[];
242
} M3Exception;
243
244
245
M3Exception* NewException (IM3Runtime io_runtime, IM3Tag i_tag, u32 i_numArgs);
246
void         FreeException (IM3Runtime io_runtime, M3Exception* i_exception);
247
void         FreeExceptions (IM3Runtime io_runtime);
248
249
#endif // d_m3HasExceptionHandling
250
251
252
#if d_m3HasStackSwitching
253
254
// A native frame the interpreter had claimed at the moment a continuation
255
// suspended, recorded so that resuming can build the same frame again.
256
//
257
// Nothing pushes these during ordinary execution. They are written on the way
258
// out: a suspend travels up the native stack as m3Err_continuationSuspended,
259
// and each operation that was holding a frame recognises the marker on its way
260
// past and appends the record describing itself - innermost first, which is
261
// simply the order the unwind visits them in. Resuming walks the array back
262
// down, rebuilding one native frame per entry, and lands on the suspension
263
// point at the bottom.
264
//
265
// Every operation that keeps a native frame needs an entry here, because each
266
// one owns a return protocol that only exists while its frame is standing:
267
// op_Call and friends resume the caller, op_Loop reads the continue sentinel,
268
// op_TryTable catches a pending exception.
269
typedef enum M3FrameKind {
270
    frame_call,          // op_Call / op_CallRef / op_CallIndirect
271
    frame_loop,          // op_Loop
272
#  if d_m3HasExceptionHandling
273
    frame_try,           // op_TryTable
274
#  endif
275
#  if d_m3EntryKeepsFrame
276
    frame_entry,         // op_Entry, in builds where it keeps a frame
277
#  endif
278
    frame_resume,        // op_Resume, when the suspend is not its to answer
279
} M3FrameKind;
280
281
typedef struct M3Frame {
282
    u8        kind;      // M3FrameKind
283
    pc_t      pc;        // call: the return address | loop: the loop id, which is
284
                         // also its body | try: the clause table | entry: unused
285
    m3stack_t sp;
286
    IM3Memory memory;    // _mem is re-derived from this rather than stored:
287
                         // growing linear memory moves the header, so only the
288
                         // M3Memory stays valid across a suspend
289
290
    union {
291
        // op_Call resumes the caller with the registers its own native frame was
292
        // holding, so those belong to the frame, not to the suspension point
293
        struct {
294
            IM3Function function;
295
            m3reg_t     r0;
296
#  if d_m3HasFloat
297
            f64 fp0;
298
#  endif
299
        } call;
300
#  if d_m3HasExceptionHandling
301
        struct {
302
            u32  numClauses;
303
            bool handlersLive;   // false once op_PopHandlers has retired the region
304
        } try_;
305
#  endif
306
#  if d_m3EntryKeepsFrame
307
        struct {
308
            IM3Function function;
309
        } entry;
310
#  endif
311
        // A resume that the suspend travelled straight through, because the
312
        // tag was not one its handlers named. The continuation it was running
313
        // is part of what got captured, so everything needed to set it going
314
        // again under the same handlers is kept here.
315
        struct {
316
            struct M3Continuation* cont;
317
            pc_t                   handlersPC;
318
            u32                    numHandlers;
319
            pc_t                   resultsPC;
320
            u32                    numResults;
321
        } resume;
322
    };
323
} M3Frame;
324
325
// Which of the three resume forms an op_Resume was emitted for
326
enum {
327
    d_m3ResumeNormal = 0,
328
    d_m3ResumeThrow,
329
    d_m3ResumeThrowRef,
330
};
331
332
typedef enum M3ContinuationState {
333
    cont_allocated = 0,
334
    cont_running,
335
    cont_suspended,
336
    cont_returned,
337
    cont_consumed
338
} M3ContinuationState;
339
340
typedef struct M3ResumeHandler {
341
    u8     kind;        // 0: (on $t $h), 1: (on $t switch)
342
    IM3Tag tag;
343
    pc_t   stubPC;
344
} M3ResumeHandler;
345
346
typedef struct M3Continuation {
347
    struct M3Continuation* next;           // linked list in runtime for cleanup
348
    IM3FuncType            type;            // continuation type (cont $ft)
349
    IM3Function            entryFunction;   // target function
350
    M3ContinuationState    state;
351
352
    m3slot_t*              valStack;        // allocated value stack buffer
353
    u32                    numStackSlots;
354
    m3stack_t              sp;              // current value stack pointer
355
356
    M3Frame*               frames;          // native frames recorded by the last suspend
357
    u32                    framesCap;       // entries allocated
358
    u32                    numFrames;       // entries in use, innermost first
359
360
    pc_t                   pc;              // resume instruction pointer
361
    u8                     suspendPoint;    // M3SafePointKind: what left pc where it is
362
    m3reg_t                r0;              // saved accumulator
363
#  if d_m3HasFloat
364
    f64 fp0;
365
#  endif
366
367
    // Bound args count (for cont.bind)
368
    u32 boundArgsCount;
369
370
#  if d_m3HasExceptionHandling
371
    // resume_throw: raised at the suspension point instead of carrying on from
372
    // it, so the try regions inside the continuation get their turn first
373
    M3Exception* resumeThrow;
374
#  endif
375
376
    // Where the values go when this continuation is next given some: the slots
377
    // its own suspend or switch is waiting on.
378
    u32                    numSuspendResults;
379
    i32                    suspendResultOffsets[d_m3MaxContinuationPayload];
380
    u32                    suspendResultIs64[d_m3MaxContinuationPayload];
381
382
    // Active handler table from enclosing resume:
383
    u32                    numHandlers;
384
    pc_t                   handlersPC;
385
    struct M3Continuation* parent;         // resumer continuation
386
} M3Continuation, *IM3Continuation;
387
388
M3Result        Continuation_AcquireStack (IM3Runtime runtime, IM3Continuation cont);
389
void            Continuation_RecycleStack (IM3Runtime runtime, IM3Continuation cont);
390
IM3Continuation Continuation_New (IM3Runtime i_runtime, IM3FuncType i_type, IM3Function i_function);
391
IM3Continuation Continuation_ForkSuspended (IM3Runtime i_runtime, IM3Continuation i_cont);
392
void            Continuation_ReleaseAll (IM3Runtime io_runtime);
393
394
// Appends one frame to the suspending continuation. Returns the marker the
395
// caller should keep unwinding with: the suspend marker when the frame was
396
// recorded, or a trap when it could not be - a continuation that cannot record
397
// its frames cannot be resumed, so the suspend has to become a trap instead.
398
m3ret_t         Continuation_RecordFrame (IM3Runtime i_runtime, const M3Frame* i_frame);
399
400
// Points runtime->stack, where the host's next call puts its arguments, above
401
// whatever a suspended root continuation holds - or back at the bottom when
402
// there is none.
403
void            Runtime_PlaceCallStack (IM3Runtime io_runtime);
404
405
#endif // d_m3HasStackSwitching
406
407
408
#if d_m3HasSnapshots
409
typedef struct M3EmbeddedSnapshot {
410
    cstr_t                     name;
411
    bytes_t                    data;
412
    u32                        size;
413
    struct M3EmbeddedSnapshot* next;
414
} M3EmbeddedSnapshot;
415
#endif
416
417
418
//---------------------------------------------------------------------------------------------------------------------------------
419
420
// One entry of the export section. Export names belong to the module rather than
421
// to what they name: one entity can be exported under any number of names, and an
422
// import re-exported under a name of the module's own, whose slot linking points
423
// at another module's entity. Every lookup by name goes through these, and
424
// resolves the index against the module's index space at the time it is asked.
425
typedef struct M3Export {
426
    cstr_t name;
427
    u32    nameLength;   // the name may hold a NUL, which ends the C string early
428
    u32    index;        // into the index space 'kind' names
429
    u8     kind;         // d_externalKind_*
430
} M3Export;
431
432
typedef struct M3Module {
433
    struct M3Runtime*     runtime;
434
    struct M3Environment* environment;
435
436
    bytes_t               wasmStart;
437
    bytes_t               wasmEnd;
438
439
    cstr_t                name;
440
441
    u32                   numFuncTypes;
442
    IM3FuncType*          funcTypes;              // array of pointers to list of FuncTypes
443
444
    u32                   numFuncImports;
445
    u32                   numFunctions;
446
    u32                   allFunctions;           // allocated functions count
447
    M3Function*           functions;
448
449
    i32                   startFunction;
450
451
    u32                   numDataSegments;
452
    M3DataSegment*        dataSegments;
453
454
    u32                   dataCount;          // from the data count section
455
    bool                  hasDataCount;
456
457
    // Bitset of the functions ref.func may name: those exported, or referenced
458
    // by an element segment or a global initializer. One bit per function.
459
    u8*                   declaredFuncs;
460
461
    //u32                     importedGlobals;
462
    u32                   numGlobals;
463
    M3Global*             globals;
464
465
#if d_m3HasExceptionHandling || d_m3HasStackSwitching
466
    u32    numTags;
467
    M3Tag* tags;
468
#endif
469
470
    u32               numElementSegments;
471
    M3ElementSegment* elementSegments;
472
    bytes_t           elementSectionEnd;
473
474
    // The module's table index space, imported entries first. Entries are
475
    // borrowed pointers, individually allocated so a slot can be pointed at a
476
    // table another module owns - see M3Table.owner, and M3Module.memories,
477
    // which works the same way.
478
    IM3Table*         tables;
479
    u32               numTables;
480
481
    // The module's memory index space: imported entries first, then declared
482
    // ones, exactly as the Wasm index space orders them. Entries are borrowed
483
    // pointers - see M3Memory.owner.
484
    IM3Memory*        memories;
485
    u32               numMemories;
486
487
    // The interpreter always carries a valid memory header in _mem - the
488
    // stack-limit check, the backtrace recorder and the call ops all reach the
489
    // runtime through it. A module that declares no memory still needs one, so
490
    // it gets this zero-length stand-in rather than a NULL _mem.
491
    M3Memory          emptyMemory;
492
493
    // memories[0], or emptyMemory when there are none. Resolved once by
494
    // InitMemory - the index space is fixed by then and linking has already
495
    // repointed whatever it was going to - so the call ops can read it straight
496
    // instead of branching. NULL until the module is loaded.
497
    IM3Memory         memory0;
498
499
    M3Export*         exports;
500
    u32               numExports;
501
502
#if d_m3HasSnapshots
503
    struct M3EmbeddedSnapshot* snapshots;
504
505
    // A snapshot restores into a module none of whose code has run - start
506
    // function included - and a restore that fails part way leaves one that
507
    // can no longer run at all: its store is neither the snapshot's nor its own.
508
    bool                       hasRun;
509
    bool                       isUnusable;
510
#endif
511
512
    struct M3Module* next;
513
} M3Module;
514
515
M3Result Module_AddMemory (IM3Module io_module, IM3Memory* o_memory, const M3MemoryInfo* i_info, bool i_isImported);
516
517
// Memory 0 of a module - the one the interpreter's _mem register tracks while
518
// that module's code is running. Never NULL once the module has been loaded.
519
static inline
520
IM3Memory Module_Memory0 (IM3Module i_module)
521
0
{
522
0
    return i_module->memory0;
523
0
}
Unexecuted instantiation: fuzzer.c:Module_Memory0
Unexecuted instantiation: m3_core.c:Module_Memory0
Unexecuted instantiation: m3_env.c:Module_Memory0
Unexecuted instantiation: m3_function.c:Module_Memory0
Unexecuted instantiation: m3_info.c:Module_Memory0
Unexecuted instantiation: m3_module.c:Module_Memory0
Unexecuted instantiation: m3_parse.c:Module_Memory0
Unexecuted instantiation: m3_bind.c:Module_Memory0
Unexecuted instantiation: m3_code.c:Module_Memory0
Unexecuted instantiation: m3_compile.c:Module_Memory0
Unexecuted instantiation: m3_validate.c:Module_Memory0
524
525
static inline
526
M3MemoryHeader* Module_MemoryHeader (IM3Module i_module)
527
29.7k
{
528
29.7k
    return i_module->memory0->mallocated;
529
29.7k
}
Unexecuted instantiation: fuzzer.c:Module_MemoryHeader
Unexecuted instantiation: m3_core.c:Module_MemoryHeader
m3_env.c:Module_MemoryHeader
Line
Count
Source
527
29.6k
{
528
29.6k
    return i_module->memory0->mallocated;
529
29.6k
}
Unexecuted instantiation: m3_function.c:Module_MemoryHeader
Unexecuted instantiation: m3_info.c:Module_MemoryHeader
Unexecuted instantiation: m3_module.c:Module_MemoryHeader
Unexecuted instantiation: m3_parse.c:Module_MemoryHeader
Unexecuted instantiation: m3_bind.c:Module_MemoryHeader
Unexecuted instantiation: m3_code.c:Module_MemoryHeader
m3_compile.c:Module_MemoryHeader
Line
Count
Source
527
89
{
528
89
    return i_module->memory0->mallocated;
529
89
}
Unexecuted instantiation: m3_validate.c:Module_MemoryHeader
530
531
M3Result Module_AddGlobal (IM3Module io_module, IM3Global* o_global, m3type_t i_type, bool i_mutable, bool i_isImported);
532
M3Result Module_AddTable (IM3Module io_module, IM3Table* o_table, const M3TableInfo* i_info, bool i_isImported);
533
#if d_m3HasExceptionHandling || d_m3HasStackSwitching
534
M3Result Module_AddTag (IM3Module io_module, IM3Tag* o_tag, IM3FuncType i_type, bool i_isImported);
535
#endif
536
#if d_m3HasStackSwitching
537
IM3FuncType Module_ContTypeOfRef (IM3Module i_module, m3type_t i_refType);
538
#endif
539
M3Result    Module_DeclareFunction (IM3Module io_module, u32 i_index);
540
bool        Module_IsFunctionDeclared (IM3Module i_module, u32 i_index);
541
542
M3Result    Module_PreallocFunctions (IM3Module io_module, u32 i_totalFunctions);
543
M3Result    Module_AddFunction (IM3Module io_module, u32 i_typeIndex, IM3ImportInfo i_importInfo /* can be null */);
544
IM3Function Module_GetFunction (IM3Module i_module, u32 i_functionIndex);
545
bool        Module_HasLinkedHostImport (IM3Module i_module, cstr_t i_importModule);
546
547
void        Module_GenerateNames (IM3Module i_module);
548
549
void        FreeImportInfo (M3ImportInfo* i_info);
550
551
//---------------------------------------------------------------------------------------------------------------------------------
552
553
typedef struct M3Environment {
554
    //    struct M3Runtime *      runtimes;
555
556
    IM3FuncType      funcTypes;                          // linked list of unique M3FuncType structs that can be compared using pointer-equivalence
557
558
    IM3FuncType      retFuncTypes[c_m3Type_count];      // these 'point' to elements in the linked list above.
559
                                                                // the number of elements must match the basic types as per M3ValueType
560
    u16              numFuncTypes;                       // hands out M3FuncType.canonicalIndex
561
    M3CodePage*      pagesReleased;
562
563
    M3SectionHandler customSectionHandler;
564
} M3Environment;
565
566
void     Environment_Release (IM3Environment i_environment);
567
568
// takes ownership of io_funcType and returns a pointer to the persistent version (could be same or different)
569
M3Result Environment_AddFuncType (IM3Environment i_environment, IM3FuncType* io_funcType);
570
M3Result Environment_ReserveFuncTypes (IM3Environment i_environment, u32 i_count, u16* o_firstIndex);
571
void     Environment_AdoptFuncType (IM3Environment i_environment, IM3FuncType i_funcType, u16 i_canonicalIndex);
572
573
#if d_m3HasTypedRefs
574
M3Result ParseHeapType (IM3Module i_module, m3type_t* o_heapBits, bytes_t* io_bytes, cbytes_t i_end);
575
#endif
576
M3Result ParseValueType (IM3Module i_module, m3type_t* o_type, bytes_t* io_bytes, cbytes_t i_end);
577
578
//---------------------------------------------------------------------------------------------------------------------------------
579
580
581
typedef struct M3Runtime {
582
    M3Compilation  compilation;
583
584
    IM3Environment environment;
585
586
    M3CodePage*    pagesOpen;      // linked list of code pages with writable space on them
587
    M3CodePage*    pagesFull;      // linked list of at-capacity pages
588
589
    u32            numCodePages;
590
    u32            numActiveCodePages;
591
592
    IM3Module      modules;        // linked list of imported modules
593
594
    void*          stack;
595
    void*          originStack;
596
    u32            stackSize;
597
    u32            numStackSlots;
598
    void*          stackLimit;     // native C-stack low-water mark; Wasm calls trap past it (NULL = unset)
599
    IM3Function    lastCalled;     // last function that successfully executed
600
    IM3Function    entered;        // entry point of the outermost call in flight, or of the last one, trapped or not
601
    u32            callNesting;    // RunCodeChecked() recursion depth
602
603
    void*          userdata;
604
605
    u32            memoryLimit;
606
    u64            memoryBytesLimit;
607
    u64            memoryBytesUsed;
608
    u64            tableElementsLimit;
609
    u64            tableElementsUsed;
610
611
#if d_m3DeterministicProfile
612
    // What the host answers about time and entropy out of, rather than out of the
613
    // machine it happens to be running on - see m3_deterministic.h, which is what
614
    // reads and moves them. Both are per-runtime, so two runtimes replay
615
    // independently and a fresh runtime replays the same way as the last one.
616
    u64 virtualTimeNs;
617
    u64 randomState;
618
#endif
619
620
#if d_m3EnableValidation
621
    bool    skipValidation; // m3_SetValidation: compile function bodies without type checking them first
622
    ValCtx* validator;      // created on first use
623
#endif
624
625
#if d_m3EnableStrace >= 2
626
    u32 callDepth;
627
#endif
628
629
#if d_m3HasGasMetering
630
    // Both counts are in gas units (see M3_GAS_UNITS_PER_GAS). gasRemaining goes
631
    // negative by the cost of the segment that ran out, which is what makes the
632
    // gas used come out slightly over the limit, and is deliberate: a segment
633
    // is paid for in full before any of it runs.
634
    i64 gasLimit;
635
    i64 gasRemaining;
636
#endif
637
638
#if d_m3HasExceptionHandling
639
    u32          tryDepth;           // number of try regions whose body is executing
640
    M3Exception* pendingException;   // the exception currently unwinding, if any
641
    M3Exception* exceptions;         // the ones it still holds
642
    M3Exception* uncaughtException;  // a copy of what ended the last call, off the list
643
#endif
644
#if d_m3HasExceptionHandling || d_m3HasStackSwitching
645
    M3HostTag* hostTags;
646
#endif
647
648
    // Set by the embedder and by the host's interrupt handler, so they are here
649
    // whether or not the interpreter was built able to act on them. Only the
650
    // suspendable operations read suspendRequested, and those exist only with
651
    // stack switching, so without it m3_RequestSuspend is simply never answered.
652
    bool          isSuspendable;
653
    volatile bool suspendRequested;
654
655
#if d_m3HasStackSwitching
656
    // Set while m3_ResumeRuntime replays a paused invocation: a back edge or a
657
    // function entry it paused at goes on past its check, so a pause already
658
    // requested takes effect at the next one instead of on the spot again
659
    bool            resumePastCheck;
660
661
    u32             continuationsLimit;
662
    u32             continuationsAllocated;
663
    m3slot_t**      valStackPool;
664
    u32             valStackPoolCap;
665
    u32             valStackPoolCount;
666
    IM3Continuation activeContinuation;
667
    IM3Continuation suspendedContinuation;
668
    IM3Continuation continuations;
669
    IM3Continuation rootContinuation;
670
671
    // The suspend on its way out, if there is one. Only ever one at a time -
672
    // it travels up the native stack and is answered before anything else can
673
    // start - so this belongs to the runtime rather than to any continuation.
674
    IM3Tag          suspendTag;
675
    IM3Continuation suspendHandlerCont;     // whose resume named the tag
676
    pc_t            suspendStubPC;          // the handler it is headed for
677
    IM3Continuation switchTarget;           // the peer to run instead, for a switch
678
    u64             suspendPayload[d_m3MaxContinuationPayload];
679
    u32             suspendPayloadIs64[d_m3MaxContinuationPayload];
680
    u32             numSuspendPayload;
681
#endif
682
683
#if d_m3HasSnapshots
684
    M3SnapshotHooks snapshotHooks;
685
#endif
686
687
    M3ErrorInfo error;
688
#if d_m3VerboseErrorMessages
689
    char error_message[256]; // the actual buffer. M3ErrorInfo can point to this
690
#endif
691
692
#if d_m3RecordBacktraces
693
    M3BacktraceInfo backtrace;
694
#endif
695
696
    u32 newCodePageSequence;
697
} M3Runtime;
698
699
// Establish the native C-stack limit for a top-level invocation. The outermost
700
// call records a low-water mark at most d_m3MaxNativeStack bytes into the stack -
701
// less, where the thread's stack was measured and is smaller than that. Nested
702
// re-entrant calls (e.g. an imported function calling back into Wasm) keep the
703
// original mark. op_Call/op_CallIndirect trap once execution crosses it.
704
//
705
// The stack pointer is read here rather than inside m3_NativeStackLimit so that
706
// the mark measures the caller's frame, the same one d_m3CheckNativeStack tests
707
// against later.
708
#if d_m3MaxNativeStack > 0
709
#  define d_m3StackLimitEnter(RT)                                               \
710
29.6k
        void * _m3SavedStackLimit = (RT)->stackLimit;                           \
711
29.6k
        if (not (RT)->stackLimit)                                               \
712
29.6k
            (RT)->stackLimit = m3_NativeStackLimit(m3_NativeStackPtr(), (d_m3MaxNativeStack));
713
29.6k
#  define d_m3StackLimitLeave(RT)  (RT)->stackLimit = _m3SavedStackLimit;
714
#else
715
#  define d_m3StackLimitEnter(RT)
716
#  define d_m3StackLimitLeave(RT)
717
#endif
718
719
void     InitRuntime (IM3Runtime io_runtime, u32 i_stackSizeInBytes);
720
void     Runtime_Release (IM3Runtime io_runtime);
721
722
M3Result ResizeMemory (IM3Runtime io_runtime, IM3Memory io_memory, u64 i_numPages);
723
724
// Give back whatever is behind io_memory->mallocated, which is the heap or a slot of
725
// the guarded arena depending on the build. Leaves the M3Memory itself alone.
726
void     FreeMemoryBlock (IM3Memory io_memory);
727
728
typedef void* (*ModuleVisitor)(IM3Module i_module, void* i_info);
729
void*       ForEachModule (IM3Runtime i_runtime, ModuleVisitor i_visitor, void* i_info);
730
731
void*       v_FindFunction (IM3Module i_module, void* i_info);
732
733
IM3CodePage AcquireCodePage (IM3Runtime io_runtime);
734
IM3CodePage AcquireCodePageWithCapacity (IM3Runtime io_runtime, u32 i_lineCount);
735
void        ReleaseCodePage (IM3Runtime io_runtime, IM3CodePage i_codePage);
736
737
#if d_m3HasStackSwitching
738
static inline
739
bool Continuation_CanAcquireStack (IM3Runtime runtime)
740
0
{
741
0
    return not runtime->continuationsLimit or
742
0
           runtime->continuationsAllocated < runtime->continuationsLimit;
743
0
}
Unexecuted instantiation: fuzzer.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_core.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_env.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_function.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_info.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_module.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_parse.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_bind.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_code.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_compile.c:Continuation_CanAcquireStack
Unexecuted instantiation: m3_validate.c:Continuation_CanAcquireStack
744
#endif
745
746
d_m3EndExternC
747
748
#endif // m3_env_h