Coverage Report

Created: 2025-07-11 06:21

/src/WasmEdge/lib/validator/validator.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 "validator/validator.h"
5
6
#include "ast/section.h"
7
#include "common/errinfo.h"
8
#include "common/hash.h"
9
10
#include <cstdint>
11
#include <numeric>
12
#include <set>
13
#include <string>
14
#include <unordered_set>
15
#include <variant>
16
#include <vector>
17
18
using namespace std::literals;
19
20
namespace WasmEdge {
21
namespace Validator {
22
23
namespace {
24
static constexpr uint32_t MaxSubtypeDepth = 63;
25
26
Expect<void> calculateSubtypeDepthRecursiveHelper(
27
    uint32_t Index, uint32_t Depth, std::set<uint32_t> &VisitedSet,
28
0
    const FormChecker &Checker, uint32_t TypeIdx) {
29
0
  if (VisitedSet.count(Index)) {
30
0
    spdlog::error(ErrCode::Value::InvalidSubType);
31
0
    spdlog::error("    Cycle detected in subtype hierarchy for type {}."sv,
32
0
                  Index);
33
0
    return Unexpect(ErrCode::Value::InvalidSubType);
34
0
  }
35
36
0
  if (Depth >= MaxSubtypeDepth) {
37
0
    spdlog::error(ErrCode::Value::InvalidSubType);
38
0
    spdlog::error(
39
0
        "    subtype depth for Type section's {}th signature exceeded "
40
0
        "the limits of {}"sv,
41
0
        TypeIdx, MaxSubtypeDepth);
42
0
    return Unexpect(ErrCode::Value::InvalidSubType);
43
0
  }
44
45
0
  VisitedSet.insert(Index);
46
0
  const auto &TypeVec = Checker.getTypes();
47
48
0
  const auto &Type = *TypeVec[Index];
49
50
0
  for (const auto SuperIdx : Type.getSuperTypeIndices()) {
51
0
    if (auto Res = calculateSubtypeDepthRecursiveHelper(
52
0
            SuperIdx, Depth + 1, VisitedSet, Checker, TypeIdx);
53
0
        !Res) {
54
0
      spdlog::error("    When checking super type index {}."sv, SuperIdx);
55
0
      return Unexpect(Res.error());
56
0
    }
57
0
  }
58
59
0
  return {};
60
0
}
61
Expect<void> calculateSubtypeDepth(uint32_t TypeIdx,
62
0
                                   const FormChecker &Checker) {
63
0
  std::set<uint32_t> VisitedNodes;
64
65
0
  return calculateSubtypeDepthRecursiveHelper(TypeIdx, 0, VisitedNodes, Checker,
66
0
                                              TypeIdx);
67
0
}
68
} // namespace
69
70
// Validate Module. See "include/validator/validator.h".
71
3.79k
Expect<void> Validator::validate(const AST::Module &Mod) {
72
  // https://webassembly.github.io/spec/core/valid/modules.html
73
3.79k
  Checker.reset(true);
74
75
  // Validate and register type section.
76
77
3.79k
  EXPECTED_TRY(validate(Mod.getTypeSection()).map_error([](auto E) {
78
3.79k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Type));
79
3.79k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
80
3.79k
    return E;
81
3.79k
  }));
82
83
  // Validate and register import section into FormChecker.
84
3.79k
  EXPECTED_TRY(validate(Mod.getImportSection()).map_error([](auto E) {
85
3.78k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Import));
86
3.78k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
87
3.78k
    return E;
88
3.78k
  }));
89
90
  // Validate function section and register functions into FormChecker.
91
3.78k
  EXPECTED_TRY(validate(Mod.getFunctionSection()).map_error([](auto E) {
92
3.77k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Function));
93
3.77k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
94
3.77k
    return E;
95
3.77k
  }));
96
97
  // Validate table section and register tables into FormChecker.
98
3.77k
  EXPECTED_TRY(validate(Mod.getTableSection()).map_error([](auto E) {
99
3.77k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Table));
100
3.77k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
101
3.77k
    return E;
102
3.77k
  }));
103
104
  // Validate memory section and register memories into FormChecker.
105
3.77k
  EXPECTED_TRY(validate(Mod.getMemorySection()).map_error([](auto E) {
106
3.74k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Memory));
107
3.74k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
108
3.74k
    return E;
109
3.74k
  }));
110
111
  // Validate global section and register globals into FormChecker.
112
3.74k
  EXPECTED_TRY(validate(Mod.getGlobalSection()).map_error([](auto E) {
113
3.68k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Global));
114
3.68k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
115
3.68k
    return E;
116
3.68k
  }));
117
118
  // Validate tag section and register tags into FormChecker.
119
3.68k
  EXPECTED_TRY(validate(Mod.getTagSection()).map_error([](auto E) {
120
3.68k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Tag));
121
3.68k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
122
3.68k
    return E;
123
3.68k
  }));
124
125
  // Validate export section.
126
3.68k
  EXPECTED_TRY(validate(Mod.getExportSection()).map_error([](auto E) {
127
3.61k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Export));
128
3.61k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
129
3.61k
    return E;
130
3.61k
  }));
131
132
  // Validate start section.
133
3.61k
  EXPECTED_TRY(validate(Mod.getStartSection()).map_error([](auto E) {
134
3.60k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Start));
135
3.60k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
136
3.60k
    return E;
137
3.60k
  }));
138
139
  // Validate element section which initialize tables.
140
3.60k
  EXPECTED_TRY(validate(Mod.getElementSection()).map_error([](auto E) {
141
3.56k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Element));
142
3.56k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
143
3.56k
    return E;
144
3.56k
  }));
145
146
  // Validate data section which initialize memories.
147
3.56k
  EXPECTED_TRY(validate(Mod.getDataSection()).map_error([](auto E) {
148
3.53k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Data));
149
3.53k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
150
3.53k
    return E;
151
3.53k
  }));
152
153
  // Validate code section and expressions.
154
3.53k
  EXPECTED_TRY(validate(Mod.getCodeSection()).map_error([](auto E) {
155
2.19k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Sec_Code));
156
2.19k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
157
2.19k
    return E;
158
2.19k
  }));
159
160
  // Multiple tables is for the ReferenceTypes proposal.
161
2.19k
  if (Checker.getTables().size() > 1 &&
162
2.19k
      !Conf.hasProposal(Proposal::ReferenceTypes)) {
163
0
    spdlog::error(ErrCode::Value::MultiTables);
164
0
    spdlog::error(ErrInfo::InfoProposal(Proposal::ReferenceTypes));
165
0
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
166
0
    return Unexpect(ErrCode::Value::MultiTables);
167
0
  }
168
169
  // Multiple memories is for the MultiMemories proposal.
170
2.19k
  if (Checker.getMemories() > 1 && !Conf.hasProposal(Proposal::MultiMemories)) {
171
37
    spdlog::error(ErrCode::Value::MultiMemories);
172
37
    spdlog::error(ErrInfo::InfoProposal(Proposal::MultiMemories));
173
37
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Module));
174
37
    return Unexpect(ErrCode::Value::MultiMemories);
175
37
  }
176
177
  // Set the validated flag.
178
2.15k
  const_cast<AST::Module &>(Mod).setIsValidated();
179
2.15k
  return {};
180
2.19k
}
181
182
// Validate Sub type. See "include/validator/validator.h".
183
6.25k
Expect<void> Validator::validate(const AST::SubType &Type) {
184
6.25k
  const auto &TypeVec = Checker.getTypes();
185
6.25k
  const auto &CompType = Type.getCompositeType();
186
187
  // Check the validation of the composite type.
188
6.25k
  if (CompType.isFunc()) {
189
6.25k
    const auto &FType = CompType.getFuncType();
190
6.25k
    for (auto &PType : FType.getParamTypes()) {
191
5.79k
      EXPECTED_TRY(Checker.validate(PType).map_error([](auto E) {
192
5.79k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Function));
193
5.79k
        return E;
194
5.79k
      }));
195
5.79k
    }
196
6.25k
    if (unlikely(!Conf.hasProposal(Proposal::MultiValue)) &&
197
6.25k
        FType.getReturnTypes().size() > 1) {
198
0
      spdlog::error(ErrCode::Value::InvalidResultArity);
199
0
      spdlog::error(ErrInfo::InfoProposal(Proposal::MultiValue));
200
0
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Function));
201
0
      return Unexpect(ErrCode::Value::InvalidResultArity);
202
0
    }
203
6.25k
    for (auto &RType : FType.getReturnTypes()) {
204
4.69k
      EXPECTED_TRY(Checker.validate(RType).map_error([](auto E) {
205
4.69k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Function));
206
4.69k
        return E;
207
4.69k
      }));
208
4.69k
    }
209
6.25k
  } else {
210
0
    const auto &FTypes = CompType.getFieldTypes();
211
0
    for (auto &FieldType : FTypes) {
212
0
      EXPECTED_TRY(Checker.validate(FieldType.getStorageType()));
213
0
    }
214
0
  }
215
216
  // In current version, the length of type index vector will be <= 1.
217
6.25k
  if (Type.getSuperTypeIndices().size() > 1) {
218
0
    spdlog::error(ErrCode::Value::InvalidSubType);
219
0
    spdlog::error("    Accepts only one super type currently."sv);
220
0
    return Unexpect(ErrCode::Value::InvalidSubType);
221
0
  }
222
223
6.25k
  for (const auto &Index : Type.getSuperTypeIndices()) {
224
0
    if (unlikely(Index >= TypeVec.size())) {
225
0
      spdlog::error(ErrCode::Value::InvalidSubType);
226
0
      spdlog::error(
227
0
          ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::DefinedType, Index,
228
0
                                   static_cast<uint32_t>(TypeVec.size())));
229
0
      return Unexpect(ErrCode::Value::InvalidSubType);
230
0
    }
231
232
0
    if (auto Res = calculateSubtypeDepth(Index, Checker); !Res) {
233
0
      spdlog::error("    When checking subtype hierarchy of super type {}."sv,
234
0
                    Index);
235
0
      return Unexpect(Res.error());
236
0
    }
237
238
0
    if (TypeVec[Index]->isFinal()) {
239
0
      spdlog::error(ErrCode::Value::InvalidSubType);
240
0
      spdlog::error("    Super type should not be final."sv);
241
0
      return Unexpect(ErrCode::Value::InvalidSubType);
242
0
    }
243
0
    auto &SuperType = TypeVec[Index]->getCompositeType();
244
0
    if (!AST::TypeMatcher::matchType(Checker.getTypes(), SuperType, CompType)) {
245
0
      spdlog::error(ErrCode::Value::InvalidSubType);
246
0
      spdlog::error("    Super type not matched."sv);
247
0
      return Unexpect(ErrCode::Value::InvalidSubType);
248
0
    }
249
0
  }
250
6.25k
  return {};
251
6.25k
}
252
253
// Validate Limit type. See "include/validator/validator.h".
254
1.77k
Expect<void> Validator::validate(const AST::Limit &Lim) {
255
1.77k
  if (Lim.hasMax() && Lim.getMin() > Lim.getMax()) {
256
14
    spdlog::error(ErrCode::Value::InvalidLimit);
257
14
    spdlog::error(ErrInfo::InfoLimit(Lim.hasMax(), Lim.getMin(), Lim.getMax()));
258
14
    return Unexpect(ErrCode::Value::InvalidLimit);
259
14
  }
260
1.76k
  if (Lim.isShared() && unlikely(!Lim.hasMax())) {
261
0
    spdlog::error(ErrCode::Value::SharedMemoryNoMax);
262
0
    return Unexpect(ErrCode::Value::SharedMemoryNoMax);
263
0
  }
264
1.76k
  return {};
265
1.76k
}
266
267
// Validate Table type. See "include/validator/validator.h".
268
338
Expect<void> Validator::validate(const AST::TableType &Tab) {
269
  // Validate value type.
270
338
  EXPECTED_TRY(Checker.validate(Tab.getRefType()));
271
  // Validate table limits.
272
338
  return validate(Tab.getLimit()).map_error([](auto E) {
273
3
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Limit));
274
3
    return E;
275
3
  });
276
338
}
277
278
// Validate Memory type. See "include/validator/validator.h".
279
1.43k
Expect<void> Validator::validate(const AST::MemoryType &Mem) {
280
  // Validate memory limits.
281
1.43k
  const auto &Lim = Mem.getLimit();
282
1.43k
  EXPECTED_TRY(validate(Lim).map_error([](auto E) {
283
1.42k
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Limit));
284
1.42k
    return E;
285
1.42k
  }));
286
1.42k
  if (Lim.getMin() > LIMIT_MEMORYTYPE ||
287
1.42k
      (Lim.hasMax() && Lim.getMax() > LIMIT_MEMORYTYPE)) {
288
23
    spdlog::error(ErrCode::Value::InvalidMemPages);
289
23
    spdlog::error(ErrInfo::InfoLimit(Lim.hasMax(), Lim.getMin(), Lim.getMax()));
290
23
    return Unexpect(ErrCode::Value::InvalidMemPages);
291
23
  }
292
1.40k
  return {};
293
1.42k
}
294
295
// Validate Global type. See "include/validator/validator.h".
296
243
Expect<void> Validator::validate(const AST::GlobalType &Glob) {
297
  // Validate value type.
298
243
  return Checker.validate(Glob.getValType());
299
243
}
300
301
// Validate Table segment. See "include/validator/validator.h".
302
303
Expect<void> Validator::validate(const AST::TableSegment &TabSeg) {
303
303
  if (TabSeg.getExpr().getInstrs().size() > 0) {
304
    // Check ref initialization is a const expression.
305
0
    EXPECTED_TRY(
306
0
        validateConstExpr(TabSeg.getExpr().getInstrs(),
307
0
                          {ValType(TabSeg.getTableType().getRefType())})
308
0
            .map_error([](auto E) {
309
0
              spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Expression));
310
0
              return E;
311
0
            }));
312
303
  } else {
313
    // No init expression. Check the reference type is nullable.
314
303
    if (!TabSeg.getTableType().getRefType().isNullableRefType()) {
315
0
      spdlog::error(ErrCode::Value::TypeCheckFailed);
316
0
      spdlog::error(ErrInfo::InfoMismatch(
317
0
          ValType(TypeCode::RefNull,
318
0
                  TabSeg.getTableType().getRefType().getHeapTypeCode(),
319
0
                  TabSeg.getTableType().getRefType().getTypeIndex()),
320
0
          TabSeg.getTableType().getRefType()));
321
0
      return Unexpect(ErrCode::Value::TypeCheckFailed);
322
0
    }
323
303
  }
324
  // Validate table type.
325
303
  return validate(TabSeg.getTableType()).map_error([](auto E) {
326
2
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Table));
327
2
    return E;
328
2
  });
329
303
}
330
331
// Validate Global segment. See "include/validator/validator.h".
332
255
Expect<void> Validator::validate(const AST::GlobalSegment &GlobSeg) {
333
  // Check global initialization is a const expression.
334
255
  EXPECTED_TRY(validateConstExpr(GlobSeg.getExpr().getInstrs(),
335
192
                                 {GlobSeg.getGlobalType().getValType()})
336
192
                   .map_error([](auto E) {
337
192
                     spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Expression));
338
192
                     return E;
339
192
                   }));
340
  // Validate global type.
341
192
  return validate(GlobSeg.getGlobalType()).map_error([](auto E) {
342
0
    spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Global));
343
0
    return E;
344
0
  });
345
255
}
346
347
// Validate Element segment. See "include/validator/validator.h".
348
566
Expect<void> Validator::validate(const AST::ElementSegment &ElemSeg) {
349
  // Check initialization expressions are const expressions.
350
1.16k
  for (auto &Expr : ElemSeg.getInitExprs()) {
351
1.16k
    EXPECTED_TRY(
352
1.16k
        validateConstExpr(Expr.getInstrs(), {ValType(ElemSeg.getRefType())})
353
1.16k
            .map_error([](auto E) {
354
1.16k
              spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Expression));
355
1.16k
              return E;
356
1.16k
            }));
357
1.16k
  }
358
359
  // The reference type should be valid.
360
542
  EXPECTED_TRY(Checker.validate(ElemSeg.getRefType()));
361
362
  // Passive and declarative cases are valid with the valid reference type.
363
542
  if (ElemSeg.getMode() == AST::ElementSegment::ElemMode::Active) {
364
    // Check table index and reference type in context.
365
296
    const auto &TableVec = Checker.getTables();
366
296
    if (ElemSeg.getIdx() >= TableVec.size()) {
367
11
      spdlog::error(ErrCode::Value::InvalidTableIdx);
368
11
      spdlog::error(ErrInfo::InfoForbidIndex(
369
11
          ErrInfo::IndexCategory::Table, ElemSeg.getIdx(),
370
11
          static_cast<uint32_t>(TableVec.size())));
371
11
      return Unexpect(ErrCode::Value::InvalidTableIdx);
372
11
    }
373
    // TODO: Use AST::TypeMatcher::matchType() to match types instead.
374
    // For the element segments, the RefType may not record the strict type
375
    // index, and should check the init exprs for the real type index to do type
376
    // matching. But for the table type, the type index is recorded into the
377
    // heap type. So it will fail here to do strict type matching. Therefore,
378
    // only check the FuncRef and ExternRef and the nullable here.
379
285
    if (TableVec[ElemSeg.getIdx()].isFuncRefType() !=
380
285
            ElemSeg.getRefType().isFuncRefType() ||
381
285
        (!TableVec[ElemSeg.getIdx()].isNullableRefType() &&
382
283
         ElemSeg.getRefType().isNullableRefType())) {
383
      // Reference type not matched.
384
2
      spdlog::error(ErrCode::Value::TypeCheckFailed);
385
2
      spdlog::error(ErrInfo::InfoMismatch(TableVec[ElemSeg.getIdx()],
386
2
                                          ElemSeg.getRefType()));
387
2
      return Unexpect(ErrCode::Value::TypeCheckFailed);
388
2
    }
389
    // Check table initialization is a const expression.
390
283
    return validateConstExpr(ElemSeg.getExpr().getInstrs(),
391
283
                             {ValType(TypeCode::I32)})
392
283
        .map_error([](auto E) {
393
5
          spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Expression));
394
5
          return E;
395
5
        });
396
285
  }
397
246
  return {};
398
542
}
399
400
// Validate Code segment. See "include/validator/validator.h".
401
Expect<void> Validator::validate(const AST::CodeSegment &CodeSeg,
402
13.4k
                                 const uint32_t TypeIdx) {
403
  // Due to the validation of the function section, the type of index bust be a
404
  // function type.
405
13.4k
  const auto &FuncType =
406
13.4k
      Checker.getTypes()[TypeIdx]->getCompositeType().getFuncType();
407
  // Reset stack in FormChecker.
408
13.4k
  Checker.reset();
409
  // Add parameters into this frame.
410
13.4k
  for (auto &Type : FuncType.getParamTypes()) {
411
    // Local passed as function parameters should be initialized.
412
11.3k
    Checker.addLocal(Type, true);
413
11.3k
  }
414
  // Add locals into this frame.
415
13.4k
  for (auto Val : CodeSeg.getLocals()) {
416
8.49M
    for (uint32_t Cnt = 0; Cnt < Val.first; ++Cnt) {
417
      // The local value type should be valid.
418
8.48M
      EXPECTED_TRY(Checker.validate(Val.second));
419
8.48M
      Checker.addLocal(Val.second, false);
420
8.48M
    }
421
1.90k
  }
422
  // Validate function body expression.
423
13.4k
  return Checker
424
13.4k
      .validate(CodeSeg.getExpr().getInstrs(), FuncType.getReturnTypes())
425
13.4k
      .map_error([](auto E) {
426
1.34k
        spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Expression));
427
1.34k
        return E;
428
1.34k
      });
429
13.4k
}
430
431
// Validate Data segment. See "include/validator/validator.h".
432
387
Expect<void> Validator::validate(const AST::DataSegment &DataSeg) {
433
387
  switch (DataSeg.getMode()) {
434
218
  case AST::DataSegment::DataMode::Active: {
435
    // Check memory index in context.
436
218
    const auto &MemNum = Checker.getMemories();
437
218
    if (DataSeg.getIdx() >= MemNum) {
438
21
      spdlog::error(ErrCode::Value::InvalidMemoryIdx);
439
21
      spdlog::error(ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::Memory,
440
21
                                             DataSeg.getIdx(), MemNum));
441
21
      return Unexpect(ErrCode::Value::InvalidMemoryIdx);
442
21
    }
443
    // Check memory initialization is a const expression.
444
197
    return validateConstExpr(DataSeg.getExpr().getInstrs(),
445
197
                             {ValType(TypeCode::I32)})
446
197
        .map_error([](auto E) {
447
7
          spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Expression));
448
7
          return E;
449
7
        });
450
218
  }
451
169
  case AST::DataSegment::DataMode::Passive:
452
    // Passive case is always valid.
453
169
    return {};
454
0
  default:
455
0
    return {};
456
387
  }
457
387
}
458
459
// Validate Import description. See "include/validator/validator.h".
460
425
Expect<void> Validator::validate(const AST::ImportDesc &ImpDesc) {
461
425
  switch (ImpDesc.getExternalType()) {
462
  // External type and the external content are ensured to be matched in
463
  // loader phase.
464
308
  case ExternalType::Function: {
465
308
    const auto TId = ImpDesc.getExternalFuncTypeIdx();
466
    // Function type index must exist in context and be valid.
467
308
    if (TId >= Checker.getTypes().size()) {
468
4
      spdlog::error(ErrCode::Value::InvalidFuncTypeIdx);
469
4
      spdlog::error(ErrInfo::InfoForbidIndex(
470
4
          ErrInfo::IndexCategory::FunctionType, TId,
471
4
          static_cast<uint32_t>(Checker.getTypes().size())));
472
4
      return Unexpect(ErrCode::Value::InvalidFuncTypeIdx);
473
4
    }
474
304
    if (!Checker.getTypes()[TId]->getCompositeType().isFunc()) {
475
0
      spdlog::error(ErrCode::Value::InvalidFuncTypeIdx);
476
0
      spdlog::error("    Defined type index {} is not a function type."sv, TId);
477
0
      return Unexpect(ErrCode::Value::InvalidFuncTypeIdx);
478
0
    }
479
304
    Checker.addRef(static_cast<uint32_t>(Checker.getFunctions().size()));
480
304
    Checker.addFunc(TId, true);
481
304
    return {};
482
304
  }
483
35
  case ExternalType::Table: {
484
35
    const auto &TabType = ImpDesc.getExternalTableType();
485
    // Table type must be valid.
486
35
    EXPECTED_TRY(validate(TabType).map_error([](auto E) {
487
34
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Table));
488
34
      return E;
489
34
    }));
490
34
    Checker.addTable(TabType);
491
34
    return {};
492
35
  }
493
31
  case ExternalType::Memory: {
494
31
    const auto &MemType = ImpDesc.getExternalMemoryType();
495
    // Memory type must be valid.
496
31
    EXPECTED_TRY(validate(MemType).map_error([](auto E) {
497
28
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Memory));
498
28
      return E;
499
28
    }));
500
28
    Checker.addMemory(MemType);
501
28
    return {};
502
31
  }
503
0
  case ExternalType::Tag: {
504
0
    const auto &T = ImpDesc.getExternalTagType();
505
    // Tag type index must exist in context.
506
0
    auto TagTypeIdx = T.getTypeIdx();
507
0
    if (TagTypeIdx >= Checker.getTypes().size()) {
508
0
      spdlog::error(ErrCode::Value::InvalidTagIdx);
509
0
      spdlog::error(ErrInfo::InfoForbidIndex(
510
0
          ErrInfo::IndexCategory::TagType, TagTypeIdx,
511
0
          static_cast<uint32_t>(Checker.getTypes().size())));
512
0
      return Unexpect(ErrCode::Value::InvalidTagIdx);
513
0
    }
514
0
    Checker.addTag(TagTypeIdx);
515
0
    return {};
516
0
  }
517
51
  case ExternalType::Global: {
518
51
    const auto &GlobType = ImpDesc.getExternalGlobalType();
519
    // Global type must be valid.
520
51
    EXPECTED_TRY(validate(GlobType).map_error([](auto E) {
521
51
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Global));
522
51
      return E;
523
51
    }));
524
51
    Checker.addGlobal(GlobType, true);
525
51
    return {};
526
51
  }
527
0
  default:
528
0
    return {};
529
425
  }
530
425
}
531
532
// Validate Export description. See "include/validator/validator.h".
533
12.6k
Expect<void> Validator::validate(const AST::ExportDesc &ExpDesc) {
534
12.6k
  auto Id = ExpDesc.getExternalIndex();
535
12.6k
  switch (ExpDesc.getExternalType()) {
536
12.4k
  case ExternalType::Function:
537
12.4k
    if (Id >= Checker.getFunctions().size()) {
538
20
      spdlog::error(ErrCode::Value::InvalidFuncIdx);
539
20
      spdlog::error(ErrInfo::InfoForbidIndex(
540
20
          ErrInfo::IndexCategory::Function, Id,
541
20
          static_cast<uint32_t>(Checker.getFunctions().size())));
542
20
      return Unexpect(ErrCode::Value::InvalidFuncIdx);
543
20
    }
544
12.4k
    Checker.addRef(Id);
545
12.4k
    return {};
546
32
  case ExternalType::Table:
547
32
    if (Id >= Checker.getTables().size()) {
548
10
      spdlog::error(ErrCode::Value::InvalidTableIdx);
549
10
      spdlog::error(ErrInfo::InfoForbidIndex(
550
10
          ErrInfo::IndexCategory::Table, Id,
551
10
          static_cast<uint32_t>(Checker.getTables().size())));
552
10
      return Unexpect(ErrCode::Value::InvalidTableIdx);
553
10
    }
554
22
    return {};
555
117
  case ExternalType::Memory:
556
117
    if (Id >= Checker.getMemories()) {
557
17
      spdlog::error(ErrCode::Value::InvalidMemoryIdx);
558
17
      spdlog::error(ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::Memory, Id,
559
17
                                             Checker.getMemories()));
560
17
      return Unexpect(ErrCode::Value::InvalidMemoryIdx);
561
17
    }
562
100
    return {};
563
0
  case ExternalType::Tag:
564
0
    if (Id >= Checker.getTags().size()) {
565
0
      spdlog::error(ErrCode::Value::InvalidTagIdx);
566
0
      spdlog::error(ErrInfo::InfoForbidIndex(
567
0
          ErrInfo::IndexCategory::Tag, Id,
568
0
          static_cast<uint32_t>(Checker.getTags().size())));
569
0
      return Unexpect(ErrCode::Value::InvalidTagIdx);
570
0
    }
571
0
    return {};
572
33
  case ExternalType::Global:
573
33
    if (Id >= Checker.getGlobals().size()) {
574
7
      spdlog::error(ErrCode::Value::InvalidGlobalIdx);
575
7
      spdlog::error(ErrInfo::InfoForbidIndex(
576
7
          ErrInfo::IndexCategory::Global, Id,
577
7
          static_cast<uint32_t>(Checker.getGlobals().size())));
578
7
      return Unexpect(ErrCode::Value::InvalidGlobalIdx);
579
7
    }
580
26
    return {};
581
0
  default:
582
0
    return {};
583
12.6k
  }
584
12.6k
}
585
586
3.79k
Expect<void> Validator::validate(const AST::TypeSection &TypeSec) {
587
3.79k
  const auto STypeList = TypeSec.getContent();
588
3.79k
  uint32_t Idx = 0;
589
10.0k
  while (Idx < STypeList.size()) {
590
6.25k
    const auto &SType = STypeList[Idx];
591
6.25k
    if (SType.getRecursiveInfo().has_value()) {
592
      // Recursive type case. Add types first for referring recursively.
593
0
      uint32_t RecSize = SType.getRecursiveInfo()->RecTypeSize;
594
0
      for (uint32_t I = Idx; I < Idx + RecSize; I++) {
595
0
        Checker.addType(STypeList[I]);
596
0
      }
597
0
      for (uint32_t I = Idx; I < Idx + RecSize; I++) {
598
0
        EXPECTED_TRY(validate(STypeList[I]).map_error([](auto E) {
599
0
          spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Rec));
600
0
          return E;
601
0
        }));
602
0
      }
603
0
      Idx += RecSize;
604
6.25k
    } else {
605
      // SubType case.
606
6.25k
      if (Conf.hasProposal(Proposal::GC)) {
607
        // For the GC proposal, the subtype is seemed as a self-recursive type.
608
        // Add types first for referring recursively.
609
0
        Checker.addType(SType);
610
0
        EXPECTED_TRY(validate(*Checker.getTypes().back()));
611
6.25k
      } else {
612
        // Validating first.
613
6.25k
        EXPECTED_TRY(validate(SType));
614
6.25k
        Checker.addType(SType);
615
6.25k
      }
616
6.25k
      Idx++;
617
6.25k
    }
618
6.25k
  }
619
3.79k
  return {};
620
3.79k
}
621
622
// Validate Import section. See "include/validator/validator.h".
623
3.79k
Expect<void> Validator::validate(const AST::ImportSection &ImportSec) {
624
3.79k
  for (auto &ImportDesc : ImportSec.getContent()) {
625
425
    EXPECTED_TRY(validate(ImportDesc).map_error([](auto E) {
626
425
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Desc_Import));
627
425
      return E;
628
425
    }));
629
425
  }
630
3.78k
  return {};
631
3.79k
}
632
633
// Validate Function section. See "include/validator/validator.h".
634
3.78k
Expect<void> Validator::validate(const AST::FunctionSection &FuncSec) {
635
3.78k
  const auto &FuncVec = FuncSec.getContent();
636
3.78k
  const auto &TypeVec = Checker.getTypes();
637
638
  // Check if type id of function is valid in context.
639
18.5k
  for (auto &TId : FuncVec) {
640
18.5k
    if (TId >= TypeVec.size()) {
641
8
      spdlog::error(ErrCode::Value::InvalidFuncTypeIdx);
642
8
      spdlog::error(
643
8
          ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::FunctionType, TId,
644
8
                                   static_cast<uint32_t>(TypeVec.size())));
645
8
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Function));
646
8
      return Unexpect(ErrCode::Value::InvalidFuncTypeIdx);
647
8
    }
648
18.5k
    if (!TypeVec[TId]->getCompositeType().isFunc()) {
649
0
      spdlog::error(ErrCode::Value::InvalidFuncTypeIdx);
650
0
      spdlog::error("    Defined type index {} is not a function type."sv, TId);
651
0
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Function));
652
0
      return Unexpect(ErrCode::Value::InvalidFuncTypeIdx);
653
0
    }
654
18.5k
    Checker.addFunc(TId);
655
18.5k
  }
656
3.77k
  return {};
657
3.78k
}
658
659
// Validate Table section. See "include/validator/validator.h".
660
3.77k
Expect<void> Validator::validate(const AST::TableSection &TabSec) {
661
3.77k
  for (auto &Tab : TabSec.getContent()) {
662
303
    EXPECTED_TRY(validate(Tab).map_error([](auto E) {
663
301
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Table));
664
301
      return E;
665
301
    }));
666
301
    Checker.addTable(Tab.getTableType());
667
301
  }
668
3.77k
  return {};
669
3.77k
}
670
671
// Validate Memory section. See "include/validator/validator.h".
672
3.77k
Expect<void> Validator::validate(const AST::MemorySection &MemSec) {
673
3.77k
  for (auto &Mem : MemSec.getContent()) {
674
1.40k
    EXPECTED_TRY(validate(Mem).map_error([](auto E) {
675
1.37k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Type_Memory));
676
1.37k
      return E;
677
1.37k
    }));
678
1.37k
    Checker.addMemory(Mem);
679
1.37k
  }
680
3.74k
  return {};
681
3.77k
}
682
683
// Validate Global section. See "include/validator/validator.h".
684
3.74k
Expect<void> Validator::validate(const AST::GlobalSection &GlobSec) {
685
3.74k
  for (auto &GlobSeg : GlobSec.getContent()) {
686
255
    EXPECTED_TRY(validate(GlobSeg).map_error([](auto E) {
687
192
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Global));
688
192
      return E;
689
192
    }));
690
192
    Checker.addGlobal(GlobSeg.getGlobalType());
691
192
  }
692
3.68k
  return {};
693
3.74k
}
694
695
// Validate Element section. See "include/validator/validator.h".
696
3.60k
Expect<void> Validator::validate(const AST::ElementSection &ElemSec) {
697
3.60k
  for (auto &ElemSeg : ElemSec.getContent()) {
698
566
    EXPECTED_TRY(validate(ElemSeg).map_error([](auto E) {
699
524
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Element));
700
524
      return E;
701
524
    }));
702
524
    Checker.addElem(ElemSeg);
703
524
  }
704
3.56k
  return {};
705
3.60k
}
706
707
// Validate Code section. See "include/validator/validator.h".
708
3.53k
Expect<void> Validator::validate(const AST::CodeSection &CodeSec) {
709
3.53k
  const auto &CodeVec = CodeSec.getContent();
710
3.53k
  const auto &FuncVec = Checker.getFunctions();
711
712
  // Validate function body.
713
15.6k
  for (uint32_t Id = 0; Id < static_cast<uint32_t>(CodeVec.size()); ++Id) {
714
    // Added functions contains imported functions.
715
13.4k
    uint32_t TId = Id + static_cast<uint32_t>(Checker.getNumImportFuncs());
716
13.4k
    if (TId >= static_cast<uint32_t>(FuncVec.size())) {
717
0
      spdlog::error(ErrCode::Value::InvalidFuncIdx);
718
0
      spdlog::error(
719
0
          ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::Function, TId,
720
0
                                   static_cast<uint32_t>(FuncVec.size())));
721
0
      return Unexpect(ErrCode::Value::InvalidFuncIdx);
722
0
    }
723
13.4k
    EXPECTED_TRY(validate(CodeVec[Id], FuncVec[TId]).map_error([](auto E) {
724
13.4k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Code));
725
13.4k
      return E;
726
13.4k
    }));
727
13.4k
  }
728
2.19k
  return {};
729
3.53k
}
730
731
// Validate Data section. See "include/validator/validator.h".
732
3.56k
Expect<void> Validator::validate(const AST::DataSection &DataSec) {
733
3.56k
  for (auto &DataSeg : DataSec.getContent()) {
734
387
    EXPECTED_TRY(validate(DataSeg).map_error([](auto E) {
735
359
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Seg_Data));
736
359
      return E;
737
359
    }));
738
359
    Checker.addData(DataSeg);
739
359
  }
740
3.53k
  return {};
741
3.56k
}
742
743
// Validate Start section. See "include/validator/validator.h".
744
3.61k
Expect<void> Validator::validate(const AST::StartSection &StartSec) {
745
3.61k
  if (StartSec.getContent()) {
746
15
    auto FId = *StartSec.getContent();
747
15
    if (FId >= Checker.getFunctions().size()) {
748
10
      spdlog::error(ErrCode::Value::InvalidFuncIdx);
749
10
      spdlog::error(ErrInfo::InfoForbidIndex(
750
10
          ErrInfo::IndexCategory::Function, FId,
751
10
          static_cast<uint32_t>(Checker.getFunctions().size())));
752
10
      return Unexpect(ErrCode::Value::InvalidFuncIdx);
753
10
    }
754
5
    auto TId = Checker.getFunctions()[FId];
755
5
    assuming(TId < Checker.getTypes().size());
756
5
    if (!Checker.getTypes()[TId]->getCompositeType().isFunc()) {
757
0
      spdlog::error(ErrCode::Value::InvalidStartFunc);
758
0
      spdlog::error("    Defined type index {} is not a function type."sv, TId);
759
0
      return Unexpect(ErrCode::Value::InvalidStartFunc);
760
0
    }
761
5
    auto &Type = Checker.getTypes()[TId]->getCompositeType().getFuncType();
762
5
    if (Type.getParamTypes().size() != 0 || Type.getReturnTypes().size() != 0) {
763
      // Start function signature should be {}->{}
764
2
      spdlog::error(ErrCode::Value::InvalidStartFunc);
765
2
      spdlog::error(ErrInfo::InfoMismatch({}, {}, Type.getParamTypes(),
766
2
                                          Type.getReturnTypes()));
767
2
      return Unexpect(ErrCode::Value::InvalidStartFunc);
768
2
    }
769
5
  }
770
3.60k
  return {};
771
3.61k
}
772
773
// Validate Export section. See "include/validator/validator.h".
774
3.68k
Expect<void> Validator::validate(const AST::ExportSection &ExportSec) {
775
3.68k
  std::unordered_set<std::string_view, Hash::Hash> ExportNames;
776
12.6k
  for (auto &ExportDesc : ExportSec.getContent()) {
777
12.6k
    auto Result = ExportNames.emplace(ExportDesc.getExternalName());
778
12.6k
    if (!Result.second) {
779
      // Duplicated export name.
780
8
      spdlog::error(ErrCode::Value::DupExportName);
781
8
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Desc_Export));
782
8
      return Unexpect(ErrCode::Value::DupExportName);
783
8
    }
784
12.6k
    EXPECTED_TRY(validate(ExportDesc).map_error([](auto E) {
785
12.6k
      spdlog::error(ErrInfo::InfoAST(ASTNodeAttr::Desc_Export));
786
12.6k
      return E;
787
12.6k
    }));
788
12.6k
  }
789
3.61k
  return {};
790
3.68k
}
791
792
// Validate Tag section. See "include/validator/validator.h".
793
3.68k
Expect<void> Validator::validate(const AST::TagSection &TagSec) {
794
3.68k
  const auto &TagVec = TagSec.getContent();
795
3.68k
  const auto &TypeVec = Checker.getTypes();
796
797
  // Check if type id of tag is valid in context.
798
3.68k
  for (auto &TagType : TagVec) {
799
0
    auto TagTypeIdx = TagType.getTypeIdx();
800
0
    if (TagTypeIdx >= TypeVec.size()) {
801
0
      spdlog::error(ErrCode::Value::InvalidTagIdx);
802
0
      spdlog::error(
803
0
          ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::TagType, TagTypeIdx,
804
0
                                   static_cast<uint32_t>(TypeVec.size())));
805
0
      return Unexpect(ErrCode::Value::InvalidTagIdx);
806
0
    }
807
0
    auto &CompType = TypeVec[TagTypeIdx]->getCompositeType();
808
0
    if (!CompType.isFunc()) {
809
0
      spdlog::error(ErrCode::Value::InvalidTagIdx);
810
0
      spdlog::error("    Defined type index {} is not a function type."sv,
811
0
                    TagTypeIdx);
812
0
      return Unexpect(ErrCode::Value::InvalidTagIdx);
813
0
    }
814
0
    if (!CompType.getFuncType().getReturnTypes().empty()) {
815
0
      spdlog::error(ErrCode::Value::InvalidTagResultType);
816
0
      return Unexpect(ErrCode::Value::InvalidTagResultType);
817
0
    }
818
0
    Checker.addTag(TagTypeIdx);
819
0
  }
820
3.68k
  return {};
821
3.68k
}
822
823
// Validate constant expression. See "include/validator/validator.h".
824
Expect<void> Validator::validateConstExpr(AST::InstrView Instrs,
825
1.90k
                                          Span<const ValType> Returns) {
826
3.97k
  for (auto &Instr : Instrs) {
827
    // Only these instructions are accepted.
828
3.97k
    switch (Instr.getOpCode()) {
829
22
    case OpCode::Global__get: {
830
      // For initialization case, global indices must be imported globals.
831
22
      auto GlobIdx = Instr.getTargetIndex();
832
22
      uint32_t ValidGlobalSize = Checker.getNumImportGlobals();
833
22
      if (Conf.hasProposal(Proposal::FunctionReferences)) {
834
0
        ValidGlobalSize = static_cast<uint32_t>(Checker.getGlobals().size());
835
0
      }
836
22
      if (GlobIdx >= ValidGlobalSize) {
837
10
        spdlog::error(ErrCode::Value::InvalidGlobalIdx);
838
10
        spdlog::error(ErrInfo::InfoForbidIndex(ErrInfo::IndexCategory::Global,
839
10
                                               GlobIdx, ValidGlobalSize));
840
10
        spdlog::error(
841
10
            ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
842
10
        return Unexpect(ErrCode::Value::InvalidGlobalIdx);
843
10
      }
844
12
      if (Checker.getGlobals()[GlobIdx].second != ValMut::Const) {
845
1
        spdlog::error(ErrCode::Value::ConstExprRequired);
846
1
        spdlog::error(
847
1
            ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
848
1
        return Unexpect(ErrCode::Value::ConstExprRequired);
849
1
      }
850
11
      break;
851
12
    }
852
1.14k
    case OpCode::Ref__func: {
853
      // When in const expression, add the reference into context.
854
1.14k
      auto FuncIdx = Instr.getTargetIndex();
855
1.14k
      if (FuncIdx >= Checker.getFunctions().size()) {
856
        // Function index out of range.
857
22
        spdlog::error(ErrCode::Value::InvalidFuncIdx);
858
22
        spdlog::error(ErrInfo::InfoForbidIndex(
859
22
            ErrInfo::IndexCategory::Function, FuncIdx,
860
22
            static_cast<uint32_t>(Checker.getFunctions().size())));
861
22
        spdlog::error(
862
22
            ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
863
22
        return Unexpect(ErrCode::Value::InvalidFuncIdx);
864
22
      }
865
1.11k
      Checker.addRef(Instr.getTargetIndex());
866
1.11k
      break;
867
1.14k
    }
868
613
    case OpCode::I32__const:
869
730
    case OpCode::I64__const:
870
803
    case OpCode::F32__const:
871
841
    case OpCode::F64__const:
872
916
    case OpCode::Ref__null:
873
945
    case OpCode::V128__const:
874
2.77k
    case OpCode::End:
875
2.77k
    case OpCode::Struct__new:
876
2.77k
    case OpCode::Struct__new_default:
877
2.77k
    case OpCode::Array__new:
878
2.77k
    case OpCode::Array__new_default:
879
2.77k
    case OpCode::Array__new_fixed:
880
2.77k
    case OpCode::Any__convert_extern:
881
2.77k
    case OpCode::Extern__convert_any:
882
2.77k
    case OpCode::Ref__i31:
883
2.77k
      break;
884
885
    // For the Extended-const proposal, these instructions are accepted.
886
4
    case OpCode::I32__add:
887
5
    case OpCode::I32__sub:
888
6
    case OpCode::I32__mul:
889
9
    case OpCode::I64__add:
890
12
    case OpCode::I64__sub:
891
16
    case OpCode::I64__mul:
892
16
      if (Conf.hasProposal(Proposal::ExtendedConst)) {
893
0
        break;
894
0
      }
895
16
      spdlog::error(ErrCode::Value::ConstExprRequired);
896
16
      spdlog::error(ErrInfo::InfoProposal(Proposal::ExtendedConst));
897
16
      spdlog::error(
898
16
          ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
899
16
      return Unexpect(ErrCode::Value::ConstExprRequired);
900
901
21
    default:
902
21
      spdlog::error(ErrCode::Value::ConstExprRequired);
903
21
      spdlog::error(
904
21
          ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
905
21
      return Unexpect(ErrCode::Value::ConstExprRequired);
906
3.97k
    }
907
3.97k
  }
908
  // Validate expression with result types.
909
1.83k
  Checker.reset();
910
1.83k
  return Checker.validate(Instrs, Returns);
911
1.90k
}
912
913
} // namespace Validator
914
} // namespace WasmEdge