1 //===-- llvm-as-fuzzer.cpp - Fuzzer for llvm-as using lib/Fuzzer ----------===//
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
7 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
29 static jmp_buf JmpBuf
;
33 void MyFatalErrorHandler(void *user_data
, const std::string
& 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).
41 static bool InstalledHandler
= false;
43 } // end of anonymous namespace
45 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data
, size_t Size
) {
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(Input
);
56 std::unique_ptr
<Module
> M
;
59 // If reached, we have returned with non-zero status, so exit.
62 // TODO(kschimpf) Write a main to do this initialization.
63 if (!InstalledHandler
) {
64 llvm::install_fatal_error_handler(::MyFatalErrorHandler
, nullptr);
65 InstalledHandler
= true;
68 M
= parseAssembly(MemBuf
->getMemBufferRef(), Err
, Context
);
73 verifyModule(*M
.get());