Coverage Report

Created: 2025-11-24 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/WasmEdge/lib/loader/ast/segment.cpp
Line
Count
Source
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
1.06k
Expect<void> Loader::loadSegment(AST::TableSegment &TabSeg) {
11
  // Check the first byte is the reftype in table type or not.
12
1.06k
  EXPECTED_TRY(uint8_t CheckByte, FMgr.peekByte().map_error([this](auto E) {
13
1.05k
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Table);
14
1.05k
  }));
15
16
1.05k
  if (CheckByte == 0x40U) {
17
    // Table segment case is for FunctionReferences proposal.
18
51
    if (!Conf.hasProposal(Proposal::FunctionReferences)) {
19
0
      return logNeedProposal(ErrCode::Value::MalformedTable,
20
0
                             Proposal::FunctionReferences, FMgr.getLastOffset(),
21
0
                             ASTNodeAttr::Seg_Table);
22
0
    }
23
51
    FMgr.readByte();
24
25
    // Check the second byte.
26
51
    EXPECTED_TRY(uint8_t B, FMgr.readByte().map_error([this](auto E) {
27
50
      return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Table);
28
50
    }));
29
50
    if (B != 0x00U) {
30
5
      return logLoadError(ErrCode::Value::MalformedTable, FMgr.getLastOffset(),
31
5
                          ASTNodeAttr::Seg_Table);
32
5
    }
33
34
    // Read the table type.
35
45
    EXPECTED_TRY(loadType(TabSeg.getTableType()).map_error([](auto E) {
36
43
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
37
43
      return E;
38
43
    }));
39
40
    // Read the expression.
41
43
    EXPECTED_TRY(loadExpression(TabSeg.getExpr()).map_error([](auto E) {
42
43
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
43
43
      return E;
44
43
    }));
45
1.00k
  } else {
46
    // The table type case.
47
1.00k
    EXPECTED_TRY(loadType(TabSeg.getTableType()).map_error([](auto E) {
48
1.00k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
49
1.00k
      return E;
50
1.00k
    }));
51
1.00k
  }
52
53
1.00k
  return {};
54
1.05k
}
55
56
// Load binary of GlobalSegment node. See "include/loader/loader.h".
57
913
Expect<void> Loader::loadSegment(AST::GlobalSegment &GlobSeg) {
58
913
  return Expect<void>{}
59
913
      .and_then([this, &GlobSeg]() {
60
        // Read global type node.
61
913
        return loadType(GlobSeg.getGlobalType());
62
913
      })
63
913
      .and_then([this, &GlobSeg]() {
64
        // Read the expression.
65
886
        return loadExpression(GlobSeg.getExpr());
66
886
      })
67
913
      .map_error([](auto E) {
68
298
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Global));
69
298
        return E;
70
298
      });
71
913
}
72
73
// Load binary of ElementSegment node. See "include/loader/loader.h".
74
5.95k
Expect<void> Loader::loadSegment(AST::ElementSegment &ElemSeg) {
75
5.95k
  auto ReportError = [this](auto E) {
76
64
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Element);
77
64
  };
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
5.95k
  uint32_t Check = 0;
102
5.95k
  if (unlikely(!Conf.hasProposal(Proposal::BulkMemoryOperations) &&
103
0
               !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
5.95k
  } else {
110
5.95k
    EXPECTED_TRY(Check, FMgr.readU32().map_error(ReportError));
111
5.93k
  }
112
113
  // Check the prefix byte.
114
5.93k
  switch (Check) {
115
2.66k
  case 0x00:
116
3.61k
  case 0x02:
117
4.74k
  case 0x04:
118
4.88k
  case 0x06:
119
4.88k
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Active);
120
4.88k
    break;
121
122
574
  case 0x01:
123
662
  case 0x05:
124
662
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Passive);
125
662
    break;
126
127
234
  case 0x03:
128
355
  case 0x07:
129
355
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Declarative);
130
355
    break;
131
132
38
  default:
133
    // TODO: Correctness the error code once there's spec test.
134
38
    return logLoadError(ErrCode::Value::IllegalGrammar, FMgr.getLastOffset(),
135
38
                        ASTNodeAttr::Seg_Element);
136
5.93k
  }
137
138
  // Read the table index.
139
5.90k
  ElemSeg.setIdx(0);
140
5.90k
  switch (Check) {
141
949
  case 0x02:
142
1.08k
  case 0x06:
143
1.08k
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
144
1.08k
      ElemSeg.setIdx(Idx);
145
1.08k
    }));
146
1.08k
    break;
147
148
4.81k
  default:
149
4.81k
    break;
150
5.90k
  }
151
152
  // Read the expression.
153
5.89k
  switch (Check) {
154
2.66k
  case 0x00:
155
3.61k
  case 0x02:
156
4.74k
  case 0x04:
157
4.87k
  case 0x06:
158
4.87k
    EXPECTED_TRY(loadExpression(ElemSeg.getExpr()).map_error([](auto E) {
159
4.04k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
160
4.04k
      return E;
161
4.04k
    }));
162
4.04k
    break;
163
164
4.04k
  default:
165
1.01k
    break;
166
5.89k
  }
167
168
  // Read element kind and init function indices.
169
5.06k
  switch (Check) {
170
574
  case 0x01:
171
1.50k
  case 0x02:
172
1.73k
  case 0x03:
173
1.73k
    EXPECTED_TRY(FMgr.readByte()
174
1.72k
                     .and_then([&](auto B) -> Expect<void> {
175
1.72k
                       if (B != 0x00U) {
176
1.72k
                         return Unexpect(ErrCode::Value::ExpectedZeroByte);
177
1.72k
                       };
178
1.72k
                       return {};
179
1.72k
                     })
180
1.72k
                     .map_error(ReportError));
181
1.72k
    [[fallthrough]];
182
183
3.83k
  case 0x00: {
184
3.83k
    EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
185
11.1k
    for (uint32_t I = 0; I < VecCnt; ++I) {
186
      // For each element in vec(funcidx), make expr(ref.func idx end).
187
7.31k
      ElemSeg.getInitExprs().emplace_back();
188
7.31k
      AST::Instruction RefFunc(OpCode::Ref__func);
189
7.31k
      AST::Instruction End(OpCode::End);
190
7.31k
      EXPECTED_TRY(loadInstruction(RefFunc).map_error([](auto E) {
191
7.30k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
192
7.30k
        return E;
193
7.30k
      }));
194
7.30k
      ElemSeg.getInitExprs().back().getInstrs().emplace_back(
195
7.30k
          std::move(RefFunc));
196
7.30k
      ElemSeg.getInitExprs().back().getInstrs().emplace_back(std::move(End));
197
7.30k
    }
198
3.79k
    break;
199
3.80k
  }
200
3.79k
  default:
201
1.20k
    break;
202
5.06k
  }
203
204
  // Set the default reference type.
205
5.00k
  if (Check == 0x04) {
206
900
    ElemSeg.setRefType(TypeCode::FuncRef);
207
4.10k
  } else {
208
4.10k
    ElemSeg.setRefType(ValType(TypeCode::Ref, TypeCode::FuncRef));
209
4.10k
  }
210
211
  // Read the reference type and init expressions.
212
5.00k
  switch (Check) {
213
88
  case 0x05:
214
188
  case 0x06:
215
309
  case 0x07: {
216
    // The AST node information is handled.
217
309
    EXPECTED_TRY(auto Type, loadRefType(ASTNodeAttr::Seg_Element));
218
305
    ElemSeg.setRefType(Type);
219
305
    [[fallthrough]];
220
305
  }
221
1.20k
  case 0x04: {
222
1.20k
    return loadVec<AST::ElementSegment>(
223
2.86k
        ElemSeg.getInitExprs(), [this](AST::Expression &Expr) -> Expect<void> {
224
2.86k
          return loadExpression(Expr);
225
2.86k
        });
226
305
  }
227
228
3.79k
  default:
229
3.79k
    break;
230
5.00k
  }
231
232
3.79k
  return {};
233
5.00k
}
234
235
// Load binary of CodeSegment node. See "include/loader/loader.h".
236
19.4k
Expect<void> Loader::loadSegment(AST::CodeSegment &CodeSeg) {
237
19.4k
  auto ReportError = [this](auto E) {
238
32
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Code);
239
32
  };
240
241
  // Read the code segment size.
242
19.4k
  EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto S) {
243
19.4k
    CodeSeg.setSegSize(S);
244
19.4k
  }));
245
19.4k
  auto ExprSizeBound = FMgr.getOffset() + CodeSeg.getSegSize();
246
247
  // Read the vector of local variable counts and types.
248
19.4k
  EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
249
19.3k
  CodeSeg.getLocals().clear();
250
19.3k
  CodeSeg.getLocals().reserve(VecCnt);
251
19.3k
  uint32_t TotalLocalCnt = 0;
252
22.9k
  for (uint32_t I = 0; I < VecCnt; ++I) {
253
3.64k
    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
3.63k
    if (UINT32_C(67108864) - TotalLocalCnt < LocalCnt) {
256
8
      return logLoadError(ErrCode::Value::TooManyLocals, FMgr.getLastOffset(),
257
8
                          ASTNodeAttr::Seg_Code);
258
8
    }
259
3.62k
    TotalLocalCnt += LocalCnt;
260
    // Read the value type.
261
    // The AST node information is handled.
262
3.62k
    EXPECTED_TRY(ValType LocalType, loadValType(ASTNodeAttr::Seg_Code));
263
3.59k
    CodeSeg.getLocals().push_back(std::make_pair(LocalCnt, LocalType));
264
3.59k
  }
265
266
19.3k
  if (!Conf.getRuntimeConfigure().isForceInterpreter() &&
267
0
      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
19.3k
  } else {
272
    // Read function body with expected expression size.
273
19.3k
    EXPECTED_TRY(
274
19.3k
        loadExpression(CodeSeg.getExpr(), ExprSizeBound).map_error([](auto E) {
275
19.3k
          spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Code));
276
19.3k
          return E;
277
19.3k
        }));
278
19.3k
  }
279
280
18.3k
  return {};
281
19.3k
}
282
283
// Load binary of DataSegment node. See "include/loader/loader.h".
284
3.81k
Expect<void> Loader::loadSegment(AST::DataSegment &DataSeg) {
285
3.81k
  auto ReportError = [this](auto E) {
286
26
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Data);
287
26
  };
288
3.81k
  DataSeg.setMode(AST::DataSegment::DataMode::Passive);
289
3.81k
  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
3.81k
  EXPECTED_TRY(uint32_t Check, FMgr.readU32().map_error(ReportError));
306
  // Check > 0 cases are for BulkMemoryOperations or ReferenceTypes proposal.
307
3.80k
  if (Check > 0 && !Conf.hasProposal(Proposal::BulkMemoryOperations) &&
308
0
      !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
3.80k
  switch (Check) {
315
545
  case 0x02: // 0x02 memidx expr vec(byte) , Active
316
    // Read target memory index.
317
545
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
318
543
      DataSeg.setIdx(Idx);
319
543
    }));
320
543
    [[fallthrough]];
321
322
2.59k
  case 0x00: // 0x00 expr vec(byte) , Active
323
    // Read the offset expression.
324
2.59k
    EXPECTED_TRY(loadExpression(DataSeg.getExpr()).map_error([](auto E) {
325
1.30k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Data));
326
1.30k
      return E;
327
1.30k
    }));
328
1.30k
    DataSeg.setMode(AST::DataSegment::DataMode::Active);
329
1.30k
    [[fallthrough]];
330
331
2.48k
  case 0x01: // 0x01 vec(byte) , Passive
332
2.48k
  {
333
    // Read initialization data.
334
2.48k
    EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
335
2.47k
    EXPECTED_TRY(FMgr.readBytes(VecCnt).map_error(ReportError).map([&](auto V) {
336
2.46k
      DataSeg.getData() = std::move(V);
337
2.46k
    }));
338
2.46k
    break;
339
2.47k
  }
340
2.46k
  default:
341
    // TODO: Correctness the error code once there's spec test.
342
29
    return logLoadError(ErrCode::Value::IllegalGrammar, FMgr.getLastOffset(),
343
29
                        ASTNodeAttr::Seg_Data);
344
3.80k
  }
345
2.46k
  return {};
346
3.80k
}
347
348
} // namespace Loader
349
} // namespace WasmEdge