xref: /llvm-project/libc/fuzzing/stdio/printf_parser_fuzz.cpp (revision f6b724f1f9c8d8019b8a425b6fb52e1cf6fc0215)
1 //===-- printf_parser_fuzz.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// Fuzzing test for llvm-libc qsort implementation.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LIBC_COPT_MOCK_ARG_LIST
14 #error The printf Parser Fuzzer must be compiled with LIBC_COPT_MOCK_ARG_LIST, and the parser itself must also be compiled with that option when it's linked against the fuzzer.
15 #endif
16 
17 #include "src/__support/arg_list.h"
18 #include "src/stdio/printf_core/parser.h"
19 
20 #include <stdarg.h>
21 #include <stdint.h>
22 
23 using namespace __llvm_libc;
24 
25 // The design for the printf parser fuzzer is fairly simple. The parser uses a
26 // mock arg list that will never fail, and is passed a randomized string. The
27 // format sections it outputs are checked against a count of the number of '%'
28 // signs are in the original string. This is a fairly basic test, and the main
29 // intent is to run this under sanitizers, which will check for buffer overruns.
30 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
31   char *in_str = new char[size + 1];
32 
33   for (size_t i = 0; i < size; ++i)
34     in_str[i] = data[i];
35 
36   in_str[size] = '\0';
37 
38   auto mock_arg_list = internal::MockArgList();
39 
40   auto parser = printf_core::Parser(in_str, mock_arg_list);
41 
42   int str_percent_count = 0;
43 
44   for (size_t i = 0; i < size && in_str[i] != '\0'; ++i) {
45     if (in_str[i] == '%') {
46       ++str_percent_count;
47     }
48   }
49 
50   int section_percent_count = 0;
51 
52   for (printf_core::FormatSection cur_section = parser.get_next_section();
53        !cur_section.raw_string.empty();
54        cur_section = parser.get_next_section()) {
55     if (cur_section.has_conv) {
56       ++section_percent_count;
57       if (cur_section.conv_name == '%') {
58         ++section_percent_count;
59       }
60     } else if (cur_section.raw_string[0] == '%') {
61       // If the conversion would be undefined, it's instead raw, but it still
62       // starts with a %.
63       ++section_percent_count;
64     }
65   }
66 
67   if (str_percent_count != section_percent_count) {
68     __builtin_trap();
69   }
70 
71   delete[] in_str;
72   return 0;
73 }
74