Coverage Report

Created: 2025-08-08 06:44

/src/WasmEdge/lib/loader/ast/segment.cpp
Line
Count
Source (jump to first uncovered line)
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: 2019-2024 Second State INC
3
4
#include "loader/loader.h"
5
6
namespace WasmEdge {
7
namespace Loader {
8
9
// Load binary of TableSegment node. See "include/loader/loader.h".
10
488
Expect<void> Loader::loadSegment(AST::TableSegment &TabSeg) {
11
  // Check the first byte is the reftype in table type or not.
12
488
  EXPECTED_TRY(uint8_t CheckByte, FMgr.peekByte().map_error([this](auto E) {
13
481
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Table);
14
481
  }));
15
16
481
  if (CheckByte == 0x40U) {
17
    // Table segment case is for FunctionReferences proposal.
18
2
    if (!Conf.hasProposal(Proposal::FunctionReferences)) {
19
2
      return logNeedProposal(ErrCode::Value::MalformedTable,
20
2
                             Proposal::FunctionReferences, FMgr.getLastOffset(),
21
2
                             ASTNodeAttr::Seg_Table);
22
2
    }
23
0
    FMgr.readByte();
24
25
    // Check the second byte.
26
0
    EXPECTED_TRY(uint8_t B, FMgr.readByte().map_error([this](auto E) {
27
0
      return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Table);
28
0
    }));
29
0
    if (B != 0x00U) {
30
0
      return logLoadError(ErrCode::Value::MalformedTable, FMgr.getLastOffset(),
31
0
                          ASTNodeAttr::Seg_Table);
32
0
    }
33
34
    // Read the table type.
35
0
    EXPECTED_TRY(loadType(TabSeg.getTableType()).map_error([](auto E) {
36
0
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
37
0
      return E;
38
0
    }));
39
40
    // Read the expression.
41
0
    EXPECTED_TRY(loadExpression(TabSeg.getExpr()).map_error([](auto E) {
42
0
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
43
0
      return E;
44
0
    }));
45
479
  } else {
46
    // The table type case.
47
479
    EXPECTED_TRY(loadType(TabSeg.getTableType()).map_error([](auto E) {
48
479
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
49
479
      return E;
50
479
    }));
51
479
  }
52
53
447
  return {};
54
481
}
55
56
// Load binary of GlobalSegment node. See "include/loader/loader.h".
57
707
Expect<void> Loader::loadSegment(AST::GlobalSegment &GlobSeg) {
58
707
  return Expect<void>{}
59
707
      .and_then([this, &GlobSeg]() {
60
        // Read global type node.
61
707
        return loadType(GlobSeg.getGlobalType());
62
707
      })
63
707
      .and_then([this, &GlobSeg]() {
64
        // Read the expression.
65
678
        return loadExpression(GlobSeg.getExpr());
66
678
      })
67
707
      .map_error([](auto E) {
68
276
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Global));
69
276
        return E;
70
276
      });
71
707
}
72
73
// Load binary of ElementSegment node. See "include/loader/loader.h".
74
7.96k
Expect<void> Loader::loadSegment(AST::ElementSegment &ElemSeg) {
75
7.96k
  auto ReportError = [this](auto E) {
76
70
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Element);
77
70
  };
78
79
  // Element segment binary format:
80
  // ---------------------------------------------------------------------------
81
  //  Mode | TableIdx | OffExpr | ElemKind | RefType | vec(FuncIdx) | vec(expr)
82
  // ------|----------|---------|----------|---------|--------------|-----------
83
  //    0  |          |    v    |          |         |       v      |
84
  //    1  |          |         |    v     |         |       v      |
85
  //    2  |    v     |    v    |    v     |         |       v      |
86
  //    3  |          |         |    v     |         |       v      |
87
  //    4  |          |    v    |          |         |              |     v
88
  //    5  |          |         |          |    v    |              |     v
89
  //    6  |    v     |    v    |          |    v    |              |     v
90
  //    7  |          |         |          |    v    |              |     v
91
  // ---------------------------------------------------------------------------
92
  // Mode: element initial integer, u32
93
  // TableIdx: target table index, u32
94
  // OffExpr: init offset expression, expr
95
  // ElemKind: byte 0x00, ref.func
96
  // RefType: reference type, RefType
97
  // vec(FuncIdx): function index vector, vec(u32)
98
  // vec(expr): reference init list, vec(expr)
99
100
  // Read the checking byte.
101
7.96k
  uint32_t Check = 0;
102
7.96k
  if (unlikely(!Conf.hasProposal(Proposal::BulkMemoryOperations) &&
103
7.96k
               !Conf.hasProposal(Proposal::ReferenceTypes))) {
104
    // Legacy for BulkMemoryOperations and ReferenceTypes proposals turned off.
105
    // Element segment binary format: TableIdx + OffExpr + vec(FuncIdx)
106
0
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
107
0
      ElemSeg.setIdx(Idx);
108
0
    }));
109
7.96k
  } else {
110
7.96k
    EXPECTED_TRY(Check, FMgr.readU32().map_error(ReportError));
111
7.95k
  }
112
113
  // Check the prefix byte.
114
7.95k
  switch (Check) {
115
3.28k
  case 0x00:
116
4.98k
  case 0x02:
117
6.61k
  case 0x04:
118
6.74k
  case 0x06:
119
6.74k
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Active);
120
6.74k
    break;
121
122
795
  case 0x01:
123
869
  case 0x05:
124
869
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Passive);
125
869
    break;
126
127
194
  case 0x03:
128
300
  case 0x07:
129
300
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Declarative);
130
300
    break;
131
132
33
  default:
133
    // TODO: Correctness the error code once there's spec test.
134
33
    return logLoadError(ErrCode::Value::IllegalGrammar, FMgr.getLastOffset(),
135
33
                        ASTNodeAttr::Seg_Element);
136
7.95k
  }
137
138
  // Read the table index.
139
7.91k
  ElemSeg.setIdx(0);
140
7.91k
  switch (Check) {
141
1.70k
  case 0x02:
142
1.83k
  case 0x06:
143
1.83k
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
144
1.83k
      ElemSeg.setIdx(Idx);
145
1.83k
    }));
146
1.83k
    break;
147
148
6.08k
  default:
149
6.08k
    break;
150
7.91k
  }
151
152
  // Read the expression.
153
7.91k
  switch (Check) {
154
3.28k
  case 0x00:
155
4.98k
  case 0x02:
156
6.61k
  case 0x04:
157
6.74k
  case 0x06:
158
6.74k
    EXPECTED_TRY(loadExpression(ElemSeg.getExpr()).map_error([](auto E) {
159
5.91k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
160
5.91k
      return E;
161
5.91k
    }));
162
5.91k
    break;
163
164
5.91k
  default:
165
1.16k
    break;
166
7.91k
  }
167
168
  // Read element kind and init function indices.
169
7.08k
  switch (Check) {
170
795
  case 0x01:
171
2.47k
  case 0x02:
172
2.67k
  case 0x03:
173
2.67k
    EXPECTED_TRY(FMgr.readByte()
174
2.65k
                     .and_then([&](auto B) -> Expect<void> {
175
2.65k
                       if (B != 0x00U) {
176
2.65k
                         return Unexpect(ErrCode::Value::ExpectedZeroByte);
177
2.65k
                       };
178
2.65k
                       return {};
179
2.65k
                     })
180
2.65k
                     .map_error(ReportError));
181
2.65k
    [[fallthrough]];
182
183
5.37k
  case 0x00: {
184
5.37k
    EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
185
13.9k
    for (uint32_t I = 0; I < VecCnt; ++I) {
186
      // For each element in vec(funcidx), make expr(ref.func idx end).
187
8.65k
      ElemSeg.getInitExprs().emplace_back();
188
8.65k
      AST::Instruction RefFunc(OpCode::Ref__func);
189
8.65k
      AST::Instruction End(OpCode::End);
190
8.65k
      EXPECTED_TRY(loadInstruction(RefFunc).map_error([](auto E) {
191
8.64k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
192
8.64k
        return E;
193
8.64k
      }));
194
8.64k
      ElemSeg.getInitExprs().back().getInstrs().emplace_back(
195
8.64k
          std::move(RefFunc));
196
8.64k
      ElemSeg.getInitExprs().back().getInstrs().emplace_back(std::move(End));
197
8.64k
    }
198
5.32k
    break;
199
5.33k
  }
200
5.32k
  default:
201
1.69k
    break;
202
7.08k
  }
203
204
  // Set the default reference type.
205
7.01k
  if (Check == 0x04) {
206
1.41k
    ElemSeg.setRefType(TypeCode::FuncRef);
207
5.60k
  } else {
208
5.60k
    ElemSeg.setRefType(ValType(TypeCode::Ref, TypeCode::FuncRef));
209
5.60k
  }
210
211
  // Read the reference type and init expressions.
212
7.01k
  switch (Check) {
213
74
  case 0x05:
214
171
  case 0x06:
215
277
  case 0x07: {
216
    // The AST node information is handled.
217
277
    EXPECTED_TRY(auto Type, loadRefType(ASTNodeAttr::Seg_Element));
218
270
    ElemSeg.setRefType(Type);
219
270
    [[fallthrough]];
220
270
  }
221
1.68k
  case 0x04: {
222
1.68k
    return loadVec<AST::ElementSegment>(
223
3.85k
        ElemSeg.getInitExprs(), [this](AST::Expression &Expr) -> Expect<void> {
224
3.85k
          return loadExpression(Expr);
225
3.85k
        });
226
270
  }
227
228
5.32k
  default:
229
5.32k
    break;
230
7.01k
  }
231
232
5.32k
  return {};
233
7.01k
}
234
235
// Load binary of CodeSegment node. See "include/loader/loader.h".
236
17.1k
Expect<void> Loader::loadSegment(AST::CodeSegment &CodeSeg) {
237
17.1k
  auto ReportError = [this](auto E) {
238
26
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Code);
239
26
  };
240
241
  // Read the code segment size.
242
17.1k
  EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto S) {
243
17.0k
    CodeSeg.setSegSize(S);
244
17.0k
  }));
245
17.0k
  auto ExprSizeBound = FMgr.getOffset() + CodeSeg.getSegSize();
246
247
  // Read the vector of local variable counts and types.
248
17.0k
  EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
249
17.0k
  CodeSeg.getLocals().clear();
250
17.0k
  CodeSeg.getLocals().reserve(VecCnt);
251
17.0k
  uint32_t TotalLocalCnt = 0;
252
19.4k
  for (uint32_t I = 0; I < VecCnt; ++I) {
253
2.39k
    EXPECTED_TRY(uint32_t LocalCnt, FMgr.readU32().map_error(ReportError));
254
    // Total local variables should not more than 2^32. Capped at 2^26.
255
2.39k
    if (UINT32_C(67108864) - TotalLocalCnt < LocalCnt) {
256
7
      return logLoadError(ErrCode::Value::TooManyLocals, FMgr.getLastOffset(),
257
7
                          ASTNodeAttr::Seg_Code);
258
7
    }
259
2.38k
    TotalLocalCnt += LocalCnt;
260
    // Read the value type.
261
    // The AST node information is handled.
262
2.38k
    EXPECTED_TRY(ValType LocalType, loadValType(ASTNodeAttr::Seg_Code));
263
2.35k
    CodeSeg.getLocals().push_back(std::make_pair(LocalCnt, LocalType));
264
2.35k
  }
265
266
17.0k
  if (!Conf.getRuntimeConfigure().isForceInterpreter() &&
267
17.0k
      WASMType != InputType::WASM) {
268
    // For the AOT mode and not force interpreter in configure, skip the
269
    // function body.
270
0
    FMgr.seek(ExprSizeBound);
271
17.0k
  } else {
272
    // Read function body with expected expression size.
273
17.0k
    EXPECTED_TRY(
274
17.0k
        loadExpression(CodeSeg.getExpr(), ExprSizeBound).map_error([](auto E) {
275
17.0k
          spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Code));
276
17.0k
          return E;
277
17.0k
        }));
278
17.0k
  }
279
280
16.3k
  return {};
281
17.0k
}
282
283
// Load binary of DataSegment node. See "include/loader/loader.h".
284
4.11k
Expect<void> Loader::loadSegment(AST::DataSegment &DataSeg) {
285
4.11k
  auto ReportError = [this](auto E) {
286
24
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Data);
287
24
  };
288
4.11k
  DataSeg.setMode(AST::DataSegment::DataMode::Passive);
289
4.11k
  DataSeg.setIdx(0);
290
291
  // Data segment binary format:
292
  // ----------------------------------------
293
  //  Mode | MemoryIdx | OffExpr | vec(byte)
294
  // ------|-----------|---------|-----------
295
  //    0  |           |    v    |     v
296
  //    1  |           |         |     v
297
  //    2  |     v     |    v    |     v
298
  // ----------------------------------------
299
  // Mode: data initial integer, u32
300
  // MemoryIdx: target memory index, u32
301
  // OffExpr: init offset expression, expr
302
  // vec(byte): init data, vec(u8)
303
304
  // Read the checking byte.
305
4.11k
  EXPECTED_TRY(uint32_t Check, FMgr.readU32().map_error(ReportError));
306
  // Check > 0 cases are for BulkMemoryOperations or ReferenceTypes proposal.
307
4.11k
  if (Check > 0 && !Conf.hasProposal(Proposal::BulkMemoryOperations) &&
308
4.11k
      !Conf.hasProposal(Proposal::ReferenceTypes)) {
309
0
    return logNeedProposal(ErrCode::Value::ExpectedZeroByte,
310
0
                           Proposal::BulkMemoryOperations, FMgr.getLastOffset(),
311
0
                           ASTNodeAttr::Seg_Data);
312
0
  }
313
314
4.11k
  switch (Check) {
315
823
  case 0x02: // 0x02 memidx expr vec(byte) , Active
316
    // Read target memory index.
317
823
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
318
822
      DataSeg.setIdx(Idx);
319
822
    }));
320
822
    [[fallthrough]];
321
322
2.93k
  case 0x00: // 0x00 expr vec(byte) , Active
323
    // Read the offset expression.
324
2.93k
    EXPECTED_TRY(loadExpression(DataSeg.getExpr()).map_error([](auto E) {
325
1.70k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Data));
326
1.70k
      return E;
327
1.70k
    }));
328
1.70k
    DataSeg.setMode(AST::DataSegment::DataMode::Active);
329
1.70k
    [[fallthrough]];
330
331
2.85k
  case 0x01: // 0x01 vec(byte) , Passive
332
2.85k
  {
333
    // Read initialization data.
334
2.85k
    EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
335
2.84k
    EXPECTED_TRY(FMgr.readBytes(VecCnt).map_error(ReportError).map([&](auto V) {
336
2.83k
      DataSeg.getData() = std::move(V);
337
2.83k
    }));
338
2.83k
    break;
339
2.84k
  }
340
2.83k
  default:
341
    // TODO: Correctness the error code once there's spec test.
342
28
    return logLoadError(ErrCode::Value::IllegalGrammar, FMgr.getLastOffset(),
343
28
                        ASTNodeAttr::Seg_Data);
344
4.11k
  }
345
2.83k
  return {};
346
4.11k
}
347
348
} // namespace Loader
349
} // namespace WasmEdge