Coverage Report

Created: 2026-08-13 06:09

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: Copyright The WasmEdge Authors
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
2.50k
Expect<void> Loader::loadSegment(AST::TableSegment &TabSeg) {
11
  // Check whether the first byte is the reftype in table type.
12
2.50k
  EXPECTED_TRY(uint8_t CheckByte, FMgr.peekByte().map_error([this](auto E) {
13
2.48k
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Table);
14
2.48k
  }));
15
16
2.48k
  if (CheckByte == 0x40U) {
17
    // Table segment case is for FunctionReferences proposal.
18
247
    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
247
    FMgr.readByte();
24
25
    // Check the second byte.
26
247
    EXPECTED_TRY(uint8_t B, FMgr.readByte().map_error([this](auto E) {
27
243
      return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Table);
28
243
    }));
29
243
    if (B != 0x00U) {
30
11
      return logLoadError(ErrCode::Value::MalformedTable, FMgr.getLastOffset(),
31
11
                          ASTNodeAttr::Seg_Table);
32
11
    }
33
34
    // Read the table type.
35
232
    EXPECTED_TRY(loadType(TabSeg.getTableType()).map_error([](auto E) {
36
225
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
37
225
      return E;
38
225
    }));
39
40
    // Read the expression.
41
225
    EXPECTED_TRY(loadExpression(TabSeg.getExpr()).map_error([](auto E) {
42
225
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
43
225
      return E;
44
225
    }));
45
2.23k
  } else {
46
    // The table type case.
47
2.23k
    EXPECTED_TRY(loadType(TabSeg.getTableType()).map_error([](auto E) {
48
2.23k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
49
2.23k
      return E;
50
2.23k
    }));
51
2.23k
  }
52
53
2.29k
  return {};
54
2.48k
}
55
56
// Load binary of GlobalSegment node. See "include/loader/loader.h".
57
2.59k
Expect<void> Loader::loadSegment(AST::GlobalSegment &GlobSeg) {
58
2.59k
  return Expect<void>{}
59
2.59k
      .and_then([this, &GlobSeg]() {
60
        // Read global type node.
61
2.59k
        return loadType(GlobSeg.getGlobalType());
62
2.59k
      })
63
2.59k
      .and_then([this, &GlobSeg]() {
64
        // Read the expression.
65
2.48k
        return loadExpression(GlobSeg.getExpr());
66
2.48k
      })
67
2.59k
      .map_error([](auto E) {
68
1.21k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Global));
69
1.21k
        return E;
70
1.21k
      });
71
2.59k
}
72
73
// Load binary of ElementSegment node. See "include/loader/loader.h".
74
15.0k
Expect<void> Loader::loadSegment(AST::ElementSegment &ElemSeg) {
75
15.0k
  auto ReportError = [this](auto E) {
76
154
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Element);
77
154
  };
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
15.0k
  uint32_t Check = 0;
102
15.0k
  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
15.0k
  } else {
110
15.0k
    EXPECTED_TRY(Check, FMgr.readU32().map_error(ReportError));
111
15.0k
  }
112
113
  // Check the prefix byte.
114
15.0k
  switch (Check) {
115
7.27k
  case 0x00:
116
9.98k
  case 0x02:
117
12.3k
  case 0x04:
118
12.6k
  case 0x06:
119
12.6k
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Active);
120
12.6k
    break;
121
122
1.16k
  case 0x01:
123
1.37k
  case 0x05:
124
1.37k
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Passive);
125
1.37k
    break;
126
127
760
  case 0x03:
128
948
  case 0x07:
129
948
    ElemSeg.setMode(AST::ElementSegment::ElemMode::Declarative);
130
948
    break;
131
132
78
  default:
133
    // TODO: Correct the error code once there's spec test.
134
78
    return logLoadError(ErrCode::Value::IllegalGrammar, FMgr.getLastOffset(),
135
78
                        ASTNodeAttr::Seg_Element);
136
15.0k
  }
137
138
  // Read the table index.
139
14.9k
  ElemSeg.setIdx(0);
140
14.9k
  switch (Check) {
141
2.70k
  case 0x02:
142
3.00k
  case 0x06:
143
3.00k
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
144
2.99k
      ElemSeg.setIdx(Idx);
145
2.99k
    }));
146
2.99k
    break;
147
148
11.9k
  default:
149
11.9k
    break;
150
14.9k
  }
151
152
  // Read the expression.
153
14.9k
  switch (Check) {
154
7.27k
  case 0x00:
155
9.97k
  case 0x02:
156
12.3k
  case 0x04:
157
12.6k
  case 0x06:
158
12.6k
    EXPECTED_TRY(loadExpression(ElemSeg.getExpr()).map_error([](auto E) {
159
9.76k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
160
9.76k
      return E;
161
9.76k
    }));
162
9.76k
    break;
163
164
9.76k
  default:
165
2.32k
    break;
166
14.9k
  }
167
168
  // Read element kind and init function indices.
169
12.0k
  switch (Check) {
170
1.16k
  case 0x01:
171
3.76k
  case 0x02:
172
4.52k
  case 0x03:
173
4.52k
    EXPECTED_TRY(FMgr.readByte()
174
4.48k
                     .and_then([&](auto B) -> Expect<void> {
175
4.48k
                       if (B != 0x00U) {
176
4.48k
                         return Unexpect(ErrCode::Value::ExpectedZeroByte);
177
4.48k
                       };
178
4.48k
                       return {};
179
4.48k
                     })
180
4.48k
                     .map_error(ReportError));
181
4.48k
    [[fallthrough]];
182
183
9.38k
  case 0x00: {
184
9.38k
    EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
185
31.4k
    for (uint32_t I = 0; I < VecCnt; ++I) {
186
      // For each element in vec(funcidx), make expr(ref.func idx end).
187
22.1k
      ElemSeg.getInitExprs().emplace_back();
188
22.1k
      AST::Instruction RefFunc(OpCode::Ref__func);
189
22.1k
      AST::Instruction End(OpCode::End);
190
22.1k
      EXPECTED_TRY(loadInstruction(RefFunc).map_error([](auto E) {
191
22.1k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
192
22.1k
        return E;
193
22.1k
      }));
194
22.1k
      ElemSeg.getInitExprs().back().getInstrs().emplace_back(
195
22.1k
          std::move(RefFunc));
196
22.1k
      ElemSeg.getInitExprs().back().getInstrs().emplace_back(std::move(End));
197
22.1k
    }
198
9.27k
    break;
199
9.31k
  }
200
9.27k
  default:
201
2.66k
    break;
202
12.0k
  }
203
204
  // Set the default reference type.
205
11.9k
  if (Check == 0x04) {
206
2.01k
    ElemSeg.setRefType(TypeCode::FuncRef);
207
9.92k
  } else {
208
9.92k
    ElemSeg.setRefType(ValType(TypeCode::Ref, TypeCode::FuncRef));
209
9.92k
  }
210
211
  // Read the reference type and init expressions.
212
11.9k
  switch (Check) {
213
217
  case 0x05:
214
468
  case 0x06:
215
656
  case 0x07: {
216
    // The AST node information is handled.
217
656
    EXPECTED_TRY(auto Type, loadRefType(ASTNodeAttr::Seg_Element));
218
645
    ElemSeg.setRefType(Type);
219
645
    [[fallthrough]];
220
645
  }
221
2.65k
  case 0x04: {
222
2.65k
    return loadVec<AST::ElementSegment>(
223
6.85k
        ElemSeg.getInitExprs(), [this](AST::Expression &Expr) -> Expect<void> {
224
6.85k
          return loadExpression(Expr);
225
6.85k
        });
226
645
  }
227
228
9.27k
  default:
229
9.27k
    break;
230
11.9k
  }
231
232
9.27k
  return {};
233
11.9k
}
234
235
// Load binary of CodeSegment node. See "include/loader/loader.h".
236
21.1k
Expect<void> Loader::loadSegment(AST::CodeSegment &CodeSeg) {
237
21.1k
  auto ReportError = [this](auto E) {
238
96
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Code);
239
96
  };
240
241
  // Read the code segment size.
242
21.1k
  EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto S) {
243
21.1k
    CodeSeg.setSegSize(S);
244
21.1k
  }));
245
21.1k
  auto ExprSizeBound = FMgr.getOffset() + CodeSeg.getSegSize();
246
247
  // Read the vector of local variable counts and types.
248
21.1k
  EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
249
21.1k
  CodeSeg.getLocals().clear();
250
21.1k
  CodeSeg.getLocals().reserve(VecCnt);
251
21.1k
  uint32_t TotalLocalCnt = 0;
252
29.7k
  for (uint32_t I = 0; I < VecCnt; ++I) {
253
8.80k
    EXPECTED_TRY(uint32_t LocalCnt, FMgr.readU32().map_error(ReportError));
254
    // Total local variables should not exceed 2^32. Capped at 2^26.
255
8.75k
    if (UINT32_C(67108864) - TotalLocalCnt < LocalCnt) {
256
17
      return logLoadError(ErrCode::Value::TooManyLocals, FMgr.getLastOffset(),
257
17
                          ASTNodeAttr::Seg_Code);
258
17
    }
259
8.74k
    TotalLocalCnt += LocalCnt;
260
    // Read the value type.
261
    // The AST node information is handled.
262
8.74k
    EXPECTED_TRY(ValType LocalType, loadValType(ASTNodeAttr::Seg_Code));
263
8.64k
    CodeSeg.getLocals().push_back(std::make_pair(LocalCnt, LocalType));
264
8.64k
  }
265
266
20.9k
  if (Conf.getRuntimeConfigure().getRunMode() == RunMode::AOT &&
267
0
      WASMType != InputType::WASM) {
268
    // In AOT run mode with an AOT artifact, skip parsing the function body.
269
0
    FMgr.seek(ExprSizeBound);
270
20.9k
  } else {
271
    // Read function body with expected expression size.
272
20.9k
    EXPECTED_TRY(
273
20.9k
        loadExpression(CodeSeg.getExpr(), ExprSizeBound).map_error([](auto E) {
274
20.9k
          spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Code));
275
20.9k
          return E;
276
20.9k
        }));
277
20.9k
  }
278
279
19.3k
  return {};
280
20.9k
}
281
282
// Load binary of DataSegment node. See "include/loader/loader.h".
283
7.68k
Expect<void> Loader::loadSegment(AST::DataSegment &DataSeg) {
284
7.68k
  auto ReportError = [this](auto E) {
285
100
    return logLoadError(E, FMgr.getLastOffset(), ASTNodeAttr::Seg_Data);
286
100
  };
287
7.68k
  DataSeg.setMode(AST::DataSegment::DataMode::Passive);
288
7.68k
  DataSeg.setIdx(0);
289
290
  // Data segment binary format:
291
  // ----------------------------------------
292
  //  Mode | MemoryIdx | OffExpr | vec(byte)
293
  // ------|-----------|---------|-----------
294
  //    0  |           |    v    |     v
295
  //    1  |           |         |     v
296
  //    2  |     v     |    v    |     v
297
  // ----------------------------------------
298
  // Mode: data initial integer, u32
299
  // MemoryIdx: target memory index, u32
300
  // OffExpr: init offset expression, expr
301
  // vec(byte): init data, vec(u8)
302
303
  // Read the checking byte.
304
7.68k
  EXPECTED_TRY(uint32_t Check, FMgr.readU32().map_error(ReportError));
305
  // Check > 0 cases are for BulkMemoryOperations or ReferenceTypes proposal.
306
7.66k
  if (Check > 0 && !Conf.hasProposal(Proposal::BulkMemoryOperations) &&
307
0
      !Conf.hasProposal(Proposal::ReferenceTypes)) {
308
0
    return logNeedProposal(ErrCode::Value::ExpectedZeroByte,
309
0
                           Proposal::BulkMemoryOperations, FMgr.getLastOffset(),
310
0
                           ASTNodeAttr::Seg_Data);
311
0
  }
312
313
7.66k
  switch (Check) {
314
1.22k
  case 0x02: // 0x02 memidx expr vec(byte) , Active
315
    // Read target memory index.
316
1.22k
    EXPECTED_TRY(FMgr.readU32().map_error(ReportError).map([&](auto Idx) {
317
1.22k
      DataSeg.setIdx(Idx);
318
1.22k
    }));
319
1.22k
    [[fallthrough]];
320
321
4.76k
  case 0x00: // 0x00 expr vec(byte) , Active
322
    // Read the offset expression.
323
4.76k
    EXPECTED_TRY(loadExpression(DataSeg.getExpr()).map_error([](auto E) {
324
2.62k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Data));
325
2.62k
      return E;
326
2.62k
    }));
327
2.62k
    DataSeg.setMode(AST::DataSegment::DataMode::Active);
328
2.62k
    [[fallthrough]];
329
330
5.44k
  case 0x01: // 0x01 vec(byte) , Passive
331
5.44k
  {
332
    // Read initialization data.
333
5.44k
    EXPECTED_TRY(uint32_t VecCnt, loadVecCnt().map_error(ReportError));
334
5.37k
    EXPECTED_TRY(FMgr.readBytes(VecCnt).map_error(ReportError).map([&](auto V) {
335
5.36k
      DataSeg.getData() = std::move(V);
336
5.36k
    }));
337
5.36k
    break;
338
5.37k
  }
339
5.36k
  default:
340
    // TODO: Correct the error code once there's spec test.
341
87
    return logLoadError(ErrCode::Value::IllegalGrammar, FMgr.getLastOffset(),
342
87
                        ASTNodeAttr::Seg_Data);
343
7.66k
  }
344
5.36k
  return {};
345
7.66k
}
346
347
} // namespace Loader
348
} // namespace WasmEdge