1 | //===-- llvm-as-fuzzer.cpp - Fuzzer for llvm-as using lib/Fuzzer ----------===// |
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 | // Build tool to fuzz the LLVM assembler (llvm-as) using |
10 | // lib/Fuzzer. The main reason for using this tool is that it is much |
11 | // faster than using afl-fuzz, since it is run in-process. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #include "llvm/ADT/StringRef.h" |
16 | #include "llvm/AsmParser/Parser.h" |
17 | #include "llvm/IR/LLVMContext.h" |
18 | #include "llvm/IR/Module.h" |
19 | #include "llvm/IR/Verifier.h" |
20 | #include "llvm/Support/ErrorHandling.h" |
21 | #include "llvm/Support/MemoryBuffer.h" |
22 | #include "llvm/Support/SourceMgr.h" |
23 | #include "llvm/Support/raw_ostream.h" |
24 | |
25 | #include <csetjmp> |
26 | |
27 | using namespace llvm; |
28 | |
29 | static jmp_buf JmpBuf; |
30 | |
31 | namespace { |
32 | |
33 | void MyFatalErrorHandler(void *user_data, const char *reason, |
34 | bool gen_crash_diag) { |
35 | // Don't bother printing reason, just return to the test function, |
36 | // since a fatal error represents a successful parse (i.e. it correctly |
37 | // terminated with an error message to the user). |
38 | longjmp(env: JmpBuf, val: 1); |
39 | } |
40 | |
41 | static bool InstalledHandler = false; |
42 | |
43 | } // end of anonymous namespace |
44 | |
45 | extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { |
46 | |
47 | // Allocate space for locals before setjmp so that memory can be collected |
48 | // if parse exits prematurely (via longjmp). |
49 | StringRef Input((const char *)Data, Size); |
50 | // Note: We need to create a buffer to add a null terminator to the |
51 | // end of the input string. The parser assumes that the string |
52 | // parsed is always null terminated. |
53 | std::unique_ptr<MemoryBuffer> MemBuf = MemoryBuffer::getMemBufferCopy(InputData: Input); |
54 | SMDiagnostic Err; |
55 | LLVMContext Context; |
56 | std::unique_ptr<Module> M; |
57 | |
58 | if (setjmp(JmpBuf)) |
59 | // If reached, we have returned with non-zero status, so exit. |
60 | return 0; |
61 | |
62 | // TODO(kschimpf) Write a main to do this initialization. |
63 | if (!InstalledHandler) { |
64 | llvm::install_fatal_error_handler(handler: ::MyFatalErrorHandler, user_data: nullptr); |
65 | InstalledHandler = true; |
66 | } |
67 | |
68 | M = parseAssembly(F: MemBuf->getMemBufferRef(), Err, Context); |
69 | |
70 | if (!M.get()) |
71 | return 0; |
72 | |
73 | if (verifyModule(M: *M.get(), OS: &errs())) |
74 | report_fatal_error(reason: "Broken module" ); |
75 | return 0; |
76 | } |
77 | |