Coverage Report

Created: 2025-07-01 06:18

/src/WasmEdge/lib/driver/fuzzPO.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
#ifdef WASMEDGE_BUILD_FUZZING
5
#include "driver/fuzzPO.h"
6
#include "common/spdlog.h"
7
#include "common/version.h"
8
#include "po/argument_parser.h"
9
10
#include <algorithm>
11
#include <array>
12
#include <cstdio>
13
#include <type_traits>
14
#include <utility>
15
#include <vector>
16
17
namespace {
18
template <class Key, class Value, class Hash, class BinaryPredicate>
19
class SkipTable {
20
private:
21
  using UnsignedKey = std::make_unsigned_t<Key>;
22
  std::array<Value,
23
             static_cast<std::size_t>(std::numeric_limits<UnsignedKey>::max()) +
24
                 1u>
25
      Table;
26
27
public:
28
0
  SkipTable(std::size_t, Value Default, Hash, BinaryPredicate) {
29
0
    std::fill_n(Table.begin(), Table.size(), Default);
30
0
  }
31
32
0
  void insert(const Key &K, Value V) { Table[static_cast<UnsignedKey>(K)] = V; }
33
34
0
  const Value &at(const Key &K) const {
35
0
    return Table[static_cast<UnsignedKey>(K)];
36
0
  }
37
};
38
39
template <class RandomIt1,
40
          class Hash =
41
              std::hash<typename std::iterator_traits<RandomIt1>::value_type>,
42
          class BinaryPredicate = std::equal_to<>>
43
class BoyerMooreHorspoolSearcher {
44
private:
45
  using Key = typename std::iterator_traits<RandomIt1>::value_type;
46
  using Value = typename std::iterator_traits<RandomIt1>::difference_type;
47
  static_assert(std::is_integral_v<Key> && sizeof(Key) == 1 &&
48
                std::is_same_v<Hash, std::hash<Key>> &&
49
                std::is_same_v<BinaryPredicate, std::equal_to<>>);
50
  using SkipTableType = SkipTable<Key, Value, Hash, BinaryPredicate>;
51
52
public:
53
  BoyerMooreHorspoolSearcher(RandomIt1 First, RandomIt1 Last, Hash HF = Hash(),
54
                             BinaryPredicate Pred = BinaryPredicate())
55
0
      : Pattern(First), PatternLength(std::distance(First, Last)), Pred(Pred),
56
0
        Table(PatternLength, PatternLength, HF, Pred) {
57
0
    if (First != Last) {
58
0
      --Last;
59
0
      for (Value I = 0; First != Last; ++First, ++I) {
60
0
        Table.insert(*First, PatternLength - 1 - I);
61
0
      }
62
0
    }
63
0
  }
64
65
  template <class RandomIt2>
66
  std::pair<RandomIt2, RandomIt2> operator()(RandomIt2 First,
67
0
                                             RandomIt2 Last) const {
68
0
    static_assert(
69
0
        std::is_same_v<
70
0
            std::remove_cv_t<std::remove_reference_t<
71
0
                typename std::iterator_traits<RandomIt1>::value_type>>,
72
0
            std::remove_cv_t<std::remove_reference_t<
73
0
                typename std::iterator_traits<RandomIt2>::value_type>>>,
74
0
        "Corpus and Pattern iterators must point to the same type");
75
0
    if (First == Last) {
76
      // empty corpus
77
0
      return {Last, Last};
78
0
    }
79
0
    if (PatternLength == 0) {
80
      // empty pattern
81
0
      return {First, First};
82
0
    }
83
    // the pattern is larger than the corpus
84
0
    if (PatternLength > std::distance(First, Last)) {
85
0
      return {Last, Last};
86
0
    }
87
88
0
    RandomIt2 Curr = First;
89
0
    const RandomIt2 End = Last - PatternLength;
90
0
    while (Curr <= End) {
91
0
      Value J = PatternLength;
92
0
      while (Pred(Pattern[J - 1], Curr[J - 1])) {
93
0
        --J;
94
0
        if (J == 0) {
95
          // found
96
0
          return {Curr, Curr + PatternLength};
97
0
        }
98
0
      }
99
0
      const auto K = Curr[PatternLength - 1];
100
0
      const auto D = Table.at(K);
101
0
      Curr += D;
102
0
    }
103
0
    return {Last, Last};
104
0
  }
105
106
private:
107
  RandomIt1 Pattern;
108
  Value PatternLength;
109
  BinaryPredicate Pred;
110
  SkipTableType Table;
111
};
112
} // namespace
113
114
namespace WasmEdge {
115
namespace Driver {
116
117
0
int FuzzPO(const uint8_t *Data, size_t Size) noexcept {
118
0
  using namespace std::literals;
119
120
0
  std::ios::sync_with_stdio(false);
121
0
  spdlog::set_level(spdlog::level::info);
122
123
0
  PO::Option<std::string> SoName(PO::Description("Wasm or so file"sv),
124
0
                                 PO::MetaVar("WASM_OR_SO"sv));
125
0
  PO::List<std::string> Args(PO::Description("Execution arguments"sv),
126
0
                             PO::MetaVar("ARG"sv));
127
128
0
  PO::Option<PO::Toggle> Reactor(PO::Description(
129
0
      "Enable reactor mode. Reactor mode calls `_initialize` if exported."));
130
131
0
  PO::List<std::string> Dir(
132
0
      PO::Description(
133
0
          "Binding directories into WASI virtual filesystem. Each directories "
134
0
          "can specified as --dir `guest_path:host_path`, where `guest_path` "
135
0
          "specifies the path that will correspond to `host_path` for calls "
136
0
          "like `fopen` in the guest."sv),
137
0
      PO::MetaVar("PREOPEN_DIRS"sv));
138
139
0
  PO::List<std::string> Env(
140
0
      PO::Description(
141
0
          "Environ variables. Each variable can be specified as --env `NAME=VALUE`."sv),
142
0
      PO::MetaVar("ENVS"sv));
143
144
0
  PO::Option<PO::Toggle> PropMutGlobals(
145
0
      PO::Description("Disable Import/Export of mutable globals proposal"sv));
146
0
  PO::Option<PO::Toggle> PropNonTrapF2IConvs(PO::Description(
147
0
      "Disable Non-trapping float-to-int conversions proposal"sv));
148
0
  PO::Option<PO::Toggle> PropSignExtendOps(
149
0
      PO::Description("Disable Sign-extension operators proposal"sv));
150
0
  PO::Option<PO::Toggle> PropMultiValue(
151
0
      PO::Description("Disable Multi-value proposal"sv));
152
0
  PO::Option<PO::Toggle> PropBulkMemOps(
153
0
      PO::Description("Disable Bulk memory operations proposal"sv));
154
0
  PO::Option<PO::Toggle> PropRefTypes(
155
0
      PO::Description("Disable Reference types proposal"sv));
156
0
  PO::Option<PO::Toggle> PropSIMD(PO::Description("Disable SIMD proposal"sv));
157
0
  PO::Option<PO::Toggle> PropMultiMem(
158
0
      PO::Description("Enable Multiple memories proposal"sv));
159
0
  PO::Option<PO::Toggle> PropTailCall(
160
0
      PO::Description("Enable Tail-call proposal"sv));
161
0
  PO::Option<PO::Toggle> PropExtendConst(
162
0
      PO::Description("Enable Extended-const proposal"sv));
163
0
  PO::Option<PO::Toggle> PropThreads(
164
0
      PO::Description("Enable Threads proposal"sv));
165
0
  PO::Option<PO::Toggle> PropAll(PO::Description("Enable all features"sv));
166
167
0
  PO::Option<PO::Toggle> ConfEnableInstructionCounting(PO::Description(
168
0
      "Enable generating code for counting Wasm instructions executed."sv));
169
0
  PO::Option<PO::Toggle> ConfEnableGasMeasuring(PO::Description(
170
0
      "Enable generating code for counting gas burned during execution."sv));
171
0
  PO::Option<PO::Toggle> ConfEnableTimeMeasuring(PO::Description(
172
0
      "Enable generating code for counting time during execution."sv));
173
0
  PO::Option<PO::Toggle> ConfEnableAllStatistics(PO::Description(
174
0
      "Enable generating code for all statistics options include instruction counting, gas measuring, and execution time"sv));
175
176
0
  PO::Option<uint64_t> TimeLim(
177
0
      PO::Description(
178
0
          "Limitation of maximum time(in milliseconds) for execution, default value is 0 for no limitations"sv),
179
0
      PO::MetaVar("TIMEOUT"sv), PO::DefaultValue<uint64_t>(0));
180
181
0
  PO::List<int> GasLim(
182
0
      PO::Description(
183
0
          "Limitation of execution gas. Upper bound can be specified as --gas-limit `GAS_LIMIT`."sv),
184
0
      PO::MetaVar("GAS_LIMIT"sv));
185
186
0
  PO::List<int> MemLim(
187
0
      PO::Description(
188
0
          "Limitation of pages(as size of 64 KiB) in every memory instance. Upper bound can be specified as --memory-page-limit `PAGE_COUNT`."sv),
189
0
      PO::MetaVar("PAGE_COUNT"sv));
190
191
0
  PO::List<std::string> ForbiddenPlugins(
192
0
      PO::Description("List of plugins to ignore."sv), PO::MetaVar("NAMES"sv));
193
194
0
  auto Parser = PO::ArgumentParser();
195
0
  Parser.add_option(SoName)
196
0
      .add_option(Args)
197
0
      .add_option("reactor"sv, Reactor)
198
0
      .add_option("dir"sv, Dir)
199
0
      .add_option("env"sv, Env)
200
0
      .add_option("enable-instruction-count"sv, ConfEnableInstructionCounting)
201
0
      .add_option("enable-gas-measuring"sv, ConfEnableGasMeasuring)
202
0
      .add_option("enable-time-measuring"sv, ConfEnableTimeMeasuring)
203
0
      .add_option("enable-all-statistics"sv, ConfEnableAllStatistics)
204
0
      .add_option("disable-import-export-mut-globals"sv, PropMutGlobals)
205
0
      .add_option("disable-non-trap-float-to-int"sv, PropNonTrapF2IConvs)
206
0
      .add_option("disable-sign-extension-operators"sv, PropSignExtendOps)
207
0
      .add_option("disable-multi-value"sv, PropMultiValue)
208
0
      .add_option("disable-bulk-memory"sv, PropBulkMemOps)
209
0
      .add_option("disable-reference-types"sv, PropRefTypes)
210
0
      .add_option("disable-simd"sv, PropSIMD)
211
0
      .add_option("enable-multi-memory"sv, PropMultiMem)
212
0
      .add_option("enable-tail-call"sv, PropTailCall)
213
0
      .add_option("enable-extended-const"sv, PropExtendConst)
214
0
      .add_option("enable-threads"sv, PropThreads)
215
0
      .add_option("enable-all"sv, PropAll)
216
0
      .add_option("time-limit"sv, TimeLim)
217
0
      .add_option("gas-limit"sv, GasLim)
218
0
      .add_option("memory-page-limit"sv, MemLim)
219
0
      .add_option("forbidden-plugin"sv, ForbiddenPlugins);
220
221
0
  static constexpr const std::array<char, 4> Separator = {'\xde', '\xad',
222
0
                                                          '\xbe', '\xef'};
223
0
  static const BoyerMooreHorspoolSearcher Searcher(Separator.begin(),
224
0
                                                   Separator.end());
225
0
  Span<const char> RawArgs(reinterpret_cast<const char *>(Data), Size);
226
0
  std::vector<std::string> ArgvStr;
227
0
  std::vector<const char *> Argv;
228
0
  while (!RawArgs.empty()) {
229
0
    const auto It = std::search(RawArgs.begin(), RawArgs.end(), Searcher);
230
0
    ArgvStr.emplace_back(RawArgs.begin(), It);
231
0
    RawArgs = RawArgs.subspan(std::min<size_t>(
232
0
        std::distance(RawArgs.begin(), It) + 4, RawArgs.size()));
233
0
  }
234
0
  for (const auto &Arg : ArgvStr) {
235
0
    Argv.push_back(Arg.c_str());
236
0
  }
237
238
0
  std::unique_ptr<std::FILE, decltype(&std::fclose)> Out{
239
0
      std::fopen("/dev/null", "w"), std::fclose};
240
0
  if (!Parser.parse(Out.get(), Argv.size(), Argv.data())) {
241
0
    return EXIT_FAILURE;
242
0
  }
243
0
  if (Parser.isVersion()) {
244
0
    fmt::print(Out.get(), "{} version {}\n"sv, Argv.empty() ? "" : Argv[0],
245
0
               kVersionString);
246
0
    return EXIT_SUCCESS;
247
0
  }
248
249
0
  return EXIT_SUCCESS;
250
0
}
251
252
} // namespace Driver
253
} // namespace WasmEdge
254
#endif