Coverage Report

Created: 2026-12-01 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/processor_text_fuzzer.cc
Line
Count
Source
1
// Copyright 2026 Google LLC
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
// Fuzzer that loads a valid pre-built sentencepiece model (embedded in
16
// the binary as a byte array) and then fuzzes all encoding, decoding,
17
// normalization, and vocabulary operations with fuzz-derived text input.
18
// The embedded model is fixed; the fuzzer-controlled bytes drive the
19
// text, token-id and option arguments. Beyond the basic encode/decode
20
// paths, this harness also drives:
21
//   * SetEncodeExtraOptions / SetDecodeExtraOptions -> ParseExtraOptions and
22
//     ApplyExtraOptions (bos/eos/reverse/unk), for both the STL and the
23
//     SentencePieceText proto output types.
24
//   * The SentencePieceText / NBestSentencePieceText proto-returning overloads
25
//     -> PopulateSentencePieceText and the proto branch of ApplyExtraOptions.
26
//   * Decode() on an arbitrary id stream -> DecodeOptimized bounds,
27
//     byte-fallback and error handling.
28
//   * ParallelEncode -> ParallelEncodeInternal / GetChunkOfInput.
29
//   * SafeIdToPiece and the single-argument Normalize() overload.
30
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdio>
34
#include <cstdlib>
35
#include <memory>
36
#include <string>
37
#include <vector>
38
39
#include <fuzzer/FuzzedDataProvider.h>
40
#include "sentencepiece_processor.h"
41
// SentencePieceText / NBestSentencePieceText, so the proto-returning overloads
42
// (and the proto-templated ApplyExtraOptions branch) can be exercised.
43
#include "sentencepiece.pb.h"
44
45
// Generated at build time from a small unigram model.
46
#include "embedded_model.h"
47
48
using sentencepiece::NBestSentencePieceText;
49
using sentencepiece::SentencePieceProcessor;
50
using sentencepiece::SentencePieceText;
51
52
static std::unique_ptr<SentencePieceProcessor> g_processor;
53
54
2
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
55
2
  g_processor = std::make_unique<SentencePieceProcessor>();
56
57
  // Load the model from the embedded byte array
58
2
  std::string model_data(
59
2
      reinterpret_cast<const char *>(kEmbeddedModelData),
60
2
      kEmbeddedModelSize);
61
2
  auto status = g_processor->LoadFromSerializedProto(model_data);
62
2
  if (!status.ok()) {
63
0
    fprintf(stderr, "Failed to load embedded model: %s\n",
64
0
            status.ToString().c_str());
65
0
    abort();
66
0
  }
67
68
2
  return 0;
69
2
}
70
71
// Builds a syntactically valid extra-option string ("bos:eos:reverse:unk")
72
// from a bitmask, so ParseExtraOptions accepts it and the downstream
73
// ApplyExtraOptions cases are reached. The individual tokens are all valid for
74
// both the encode and decode option sets.
75
6.06k
static std::string BuildExtraOptions(uint8_t bits) {
76
6.06k
  static const char *kTokens[] = {"reverse", "bos", "eos", "unk"};
77
6.06k
  std::string out;
78
30.3k
  for (int i = 0; i < 4; ++i) {
79
24.2k
    if (bits & (1u << i)) {
80
9.33k
      if (!out.empty()) out.push_back(':');
81
9.33k
      out += kTokens[i];
82
9.33k
    }
83
24.2k
  }
84
6.06k
  return out;
85
6.06k
}
86
87
3.79k
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
88
3.79k
  if (!g_processor || size < 2)
89
1
    return 0;
90
91
3.79k
  FuzzedDataProvider fdp(data, size);
92
3.79k
  const uint8_t ops = fdp.ConsumeIntegral<uint8_t>();
93
3.79k
  const uint8_t eopt = fdp.ConsumeIntegral<uint8_t>();
94
3.79k
  const uint8_t dopt = fdp.ConsumeIntegral<uint8_t>();
95
3.79k
  const uint8_t ctrl = fdp.ConsumeIntegral<uint8_t>();
96
97
  // === Extra options ===
98
  // Set both encode and decode extra options on every input (possibly to the
99
  // empty string, which clears them) so the per-input behaviour stays
100
  // deterministic even though the processor object is reused across inputs.
101
  // The high bit routes a raw fuzzer-controlled token into the parser;
102
  // otherwise a structurally-valid option string is used.
103
3.79k
  if (eopt & 0x80) {
104
833
    const std::string raw = fdp.ConsumeBytesAsString(
105
833
        fdp.ConsumeIntegralInRange<size_t>(0, 8));
106
833
    g_processor->SetEncodeExtraOptions(raw);
107
2.96k
  } else {
108
2.96k
    g_processor->SetEncodeExtraOptions(BuildExtraOptions(eopt));
109
2.96k
  }
110
3.79k
  if (dopt & 0x80) {
111
702
    const std::string raw = fdp.ConsumeBytesAsString(
112
702
        fdp.ConsumeIntegralInRange<size_t>(0, 8));
113
702
    g_processor->SetDecodeExtraOptions(raw);
114
3.09k
  } else {
115
3.09k
    g_processor->SetDecodeExtraOptions(BuildExtraOptions(dopt));
116
3.09k
  }
117
118
  // An arbitrary token-id stream for Decode() fuzzing. These ids are
119
  // intentionally unconstrained (negative / out-of-range / byte ids) to
120
  // exercise DecodeOptimized's bounds and byte-fallback handling.
121
3.79k
  const size_t nids = fdp.ConsumeIntegralInRange<size_t>(0, 32);
122
3.79k
  std::vector<int> fuzz_ids;
123
3.79k
  fuzz_ids.reserve(nids);
124
22.0k
  for (size_t i = 0; i < nids; ++i) {
125
18.3k
    fuzz_ids.push_back(fdp.ConsumeIntegral<int>());
126
18.3k
  }
127
128
3.79k
  const std::string text = fdp.ConsumeRemainingBytesAsString();
129
130
  // === Core encoding operations ===
131
3.79k
  if (ops & 0x01) {
132
    // Encode to pieces (strings)
133
2.53k
    std::vector<std::string> pieces;
134
2.53k
    g_processor->Encode(text, &pieces);
135
136
    // Decode back from pieces
137
2.53k
    if (!pieces.empty()) {
138
2.42k
      std::string decoded;
139
2.42k
      g_processor->Decode(pieces, &decoded);
140
2.42k
    }
141
2.53k
  }
142
143
3.79k
  if (ops & 0x02) {
144
    // Encode to IDs
145
2.46k
    std::vector<int> ids;
146
2.46k
    g_processor->Encode(text, &ids);
147
148
    // Decode back from IDs
149
2.46k
    if (!ids.empty()) {
150
2.35k
      std::string decoded;
151
2.35k
      g_processor->Decode(ids, &decoded);
152
2.35k
    }
153
2.46k
  }
154
155
  // === Advanced encoding operations ===
156
3.79k
  if (ops & 0x04) {
157
    // NBest encoding - use small nbest to avoid being too slow
158
2.32k
    std::vector<std::vector<std::string>> nbest_pieces;
159
2.32k
    g_processor->NBestEncode(text, 3, &nbest_pieces);
160
161
    // NBest encode to IDs
162
2.32k
    std::vector<std::vector<int>> nbest_ids;
163
2.32k
    g_processor->NBestEncode(text, 3, &nbest_ids);
164
2.32k
  }
165
166
3.79k
  if (ops & 0x08) {
167
    // Sample encoding with various alpha values
168
2.29k
    std::vector<std::string> sampled;
169
2.29k
    g_processor->SampleEncode(text, -1, 0.5, &sampled);
170
171
2.29k
    std::vector<int> sampled_ids;
172
2.29k
    g_processor->SampleEncode(text, -1, 0.1, &sampled_ids);
173
2.29k
  }
174
175
3.79k
  if (ops & 0x10) {
176
    // Upstream removed the *AsSerializedProto family; the piece-returning
177
    // overloads reach the same encode paths. They are [[nodiscard]], so the
178
    // results are kept alive.
179
2.19k
    auto pieces = g_processor->EncodeAsPieces(text);
180
2.19k
    (void)pieces;
181
182
2.19k
    auto nb_pieces = g_processor->NBestEncodeAsPieces(text, 2);
183
2.19k
    (void)nb_pieces;
184
185
2.19k
    auto sample_pieces = g_processor->SampleEncodeAsPieces(text, -1, 0.5);
186
2.19k
    (void)sample_pieces;
187
2.19k
  }
188
189
  // === Normalization ===
190
3.79k
  if (ops & 0x20) {
191
2.50k
    std::string normalized;
192
2.50k
    g_processor->Normalize(text, &normalized);
193
194
    // Normalize with alignment info
195
2.50k
    std::string normalized2;
196
2.50k
    std::vector<size_t> norm_to_orig;
197
2.50k
    g_processor->Normalize(text, &normalized2, &norm_to_orig);
198
199
    // Single-argument convenience overload.
200
2.50k
    const std::string normalized3 = g_processor->Normalize(text);
201
2.50k
    (void)normalized3.size();
202
2.50k
  }
203
204
  // === Vocabulary operations ===
205
3.79k
  if (ops & 0x40) {
206
    // PieceToId with fuzz text
207
2.59k
    g_processor->PieceToId(text);
208
209
    // Try splitting text into substrings and looking them up
210
2.59k
    if (text.size() > 2) {
211
19.5k
      for (size_t i = 0; i < text.size() && i < 8; i++) {
212
17.2k
        std::string sub = text.substr(0, i + 1);
213
17.2k
        int id = g_processor->PieceToId(sub);
214
17.2k
        if (id >= 0 && id < g_processor->GetPieceSize()) {
215
17.2k
          g_processor->IdToPiece(id);
216
17.2k
          g_processor->GetScore(id);
217
17.2k
          g_processor->IsUnknown(id);
218
17.2k
          g_processor->IsControl(id);
219
17.2k
          g_processor->IsUnused(id);
220
17.2k
          g_processor->IsByte(id);
221
          // SafeIdToPiece on an in-range id.
222
17.2k
          std::string safe;
223
17.2k
          g_processor->SafeIdToPiece(id, &safe);
224
17.2k
        }
225
17.2k
      }
226
2.24k
    }
227
    // SafeIdToPiece on a fuzzer-chosen (possibly out-of-range) id.
228
2.59k
    if (!fuzz_ids.empty()) {
229
1.14k
      std::string safe;
230
1.14k
      g_processor->SafeIdToPiece(fuzz_ids[0], &safe);
231
1.14k
    }
232
2.59k
  }
233
234
3.79k
  if (ops & 0x80) {
235
2.07k
    if (text.size() > 0 && text.size() < 256) {
236
1.11k
      auto sampled_pieces = g_processor->SampleEncodeAsPieces(text, 8, 0.5);
237
1.11k
      (void)sampled_pieces;
238
1.11k
    }
239
2.07k
  }
240
241
  // === Decode of an arbitrary id stream ===
242
  // Feed arbitrary ids straight to Decode so DecodeOptimized's range checks,
243
  // byte-fallback reconstruction and the decode-extra-options copy path are
244
  // all exercised.
245
3.79k
  {
246
3.79k
    std::string decoded;
247
3.79k
    g_processor->Decode(fuzz_ids, &decoded);
248
3.79k
  }
249
250
  // === Proto-returning overloads ===
251
  // These drive PopulateSentencePieceText (piece surfaces, begin/end offsets,
252
  // byte handling) and the SentencePieceText branch of ApplyExtraOptions, which
253
  // the vector-returning overloads do not reach.
254
3.79k
  {
255
3.79k
    SentencePieceText spt;
256
3.79k
    if (g_processor->Encode(text, &spt).ok()) {
257
      // The proto Decode overloads take Span<const absl::string_view> or
258
      // Span<const int>; feed the ids back to reach Decode(..., spt) ->
259
      // ApplyExtraOptions<SentencePieceText> on the decode side.
260
3.79k
      std::vector<int> proto_ids;
261
3.79k
      proto_ids.reserve(spt.pieces_size());
262
61.4M
      for (const auto &sp : spt.pieces()) {
263
61.4M
        proto_ids.push_back(sp.id());
264
61.4M
      }
265
3.79k
      SentencePieceText dpt;
266
3.79k
      g_processor->Decode(proto_ids, &dpt);
267
3.79k
    }
268
269
3.79k
    NBestSentencePieceText nbest_spt;
270
3.79k
    g_processor->NBestEncode(text, 3, &nbest_spt);
271
272
3.79k
    SentencePieceText sample_spt;
273
3.79k
    g_processor->SampleEncode(text, -1, 0.3, &sample_spt);
274
3.79k
  }
275
276
  // === Parallel encode ===
277
  // Exercises ParallelEncodeInternal and GetChunkOfInput. Gated behind a bit so
278
  // the per-input ThreadPool construction does not dominate runtime, and kept
279
  // single-threaded for determinism.
280
3.79k
  if (ctrl & 0x01) {
281
2.00k
    const int chunk_len = fdp.remaining_bytes() == 0
282
2.00k
                              ? 4
283
2.00k
                              : static_cast<int>((ctrl >> 1) & 0x3f) + 1;
284
2.00k
    sentencepiece::ThreadPool pool(1);
285
2.00k
    std::vector<std::string> ppieces;
286
2.00k
    g_processor->ParallelEncode(text, chunk_len, pool, &ppieces);
287
2.00k
    std::vector<int> pids;
288
2.00k
    g_processor->ParallelEncode(text, chunk_len, pool, &pids);
289
2.00k
  }
290
291
  // Reset options to empty so a subsequent input that takes the "clear" branch
292
  // is not accidentally influenced by this input's state.
293
3.79k
  g_processor->SetEncodeExtraOptions("");
294
3.79k
  g_processor->SetDecodeExtraOptions("");
295
296
3.79k
  return 0;
297
3.79k
}