microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
fuzz/fuzz_targets/qasm.rs
74lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | #![no_main] |
| 5 | |
| 6 | allocator::assign_global!(); |
| 7 | |
| 8 | #[cfg(feature = "do_fuzz")] |
| 9 | use libfuzzer_sys::fuzz_target; |
| 10 | |
| 11 | use qsc::{ |
| 12 | compile::compile_ast, |
| 13 | hir::PackageId, |
| 14 | qasm::{ |
| 15 | compile_to_qsharp_ast_with_config, io::InMemorySourceResolver, package_store_with_qasm, |
| 16 | CompilerConfig, OutputSemantics, ProgramType, QubitSemantics, |
| 17 | }, |
| 18 | target::Profile, |
| 19 | PackageStore, PackageType, |
| 20 | }; |
| 21 | |
| 22 | fn compile(data: &[u8]) { |
| 23 | if let Ok(fuzzed_code) = std::str::from_utf8(data) { |
| 24 | thread_local! { |
| 25 | static STORE_STD: (PackageId, PackageId, PackageStore) = { |
| 26 | package_store_with_qasm(Profile::Unrestricted.into()) |
| 27 | }; |
| 28 | } |
| 29 | STORE_STD.with(|(stdid, qasmid, store)| { |
| 30 | let mut resolver = InMemorySourceResolver::from_iter([]); |
| 31 | let config = CompilerConfig::new( |
| 32 | QubitSemantics::Qiskit, |
| 33 | OutputSemantics::OpenQasm, |
| 34 | ProgramType::File, |
| 35 | Some("Fuzz".into()), |
| 36 | None, |
| 37 | ); |
| 38 | |
| 39 | let unit = compile_to_qsharp_ast_with_config( |
| 40 | fuzzed_code, |
| 41 | "fuzz.qasm", |
| 42 | Some(&mut resolver), |
| 43 | config, |
| 44 | ); |
| 45 | let (sources, _, package, _) = unit.into_tuple(); |
| 46 | |
| 47 | let dependencies = vec![ |
| 48 | (PackageId::CORE, None), |
| 49 | (*stdid, None), |
| 50 | (*qasmid, Some("QasmStd".into())), |
| 51 | ]; |
| 52 | |
| 53 | let (mut _unit, _errors) = compile_ast( |
| 54 | store, |
| 55 | &dependencies, |
| 56 | package, |
| 57 | sources, |
| 58 | PackageType::Lib, |
| 59 | Profile::Unrestricted.into(), |
| 60 | ); |
| 61 | }); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | #[cfg(feature = "do_fuzz")] |
| 66 | fuzz_target!(|data: &[u8]| { |
| 67 | compile(data); |
| 68 | }); |
| 69 | |
| 70 | #[cfg(not(feature = "do_fuzz"))] |
| 71 | #[no_mangle] |
| 72 | pub extern "C" fn main() { |
| 73 | compile(&[]); |
| 74 | } |
| 75 | |