diff --git a/Cargo.lock b/Cargo.lock index ae98437..352a023 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -188,7 +188,7 @@ version = "0.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "cexpr", "clang-sys", "itertools", @@ -220,9 +220,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.6.0" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" dependencies = [ "serde", ] @@ -412,7 +412,7 @@ name = "compiler" version = "0.1.0" dependencies = [ "bimap", - "bitflags 2.6.0", + "bitflags 2.8.0", "common", "config", "const_format", @@ -432,20 +432,20 @@ dependencies = [ [[package]] name = "config" -version = "0.14.1" +version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68578f196d2a33ff61b27fae256c3164f65e36382648e30666dde05b8cc9dfdf" +checksum = "e26695492a475c4a091cfda61446d5ba01aac2e1dfbcd27a12fdd11aa2e32596" dependencies = [ "async-trait", "convert_case", "json5", - "nom", "pathdiff", "ron", "rust-ini", "serde", "serde_json", "toml", + "winnow 0.7.0", "yaml-rust2", ] @@ -471,18 +471,18 @@ dependencies = [ [[package]] name = "const_format" -version = "0.2.33" +version = "0.2.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50c655d81ff1114fb0dcdea9225ea9f0cc712a6f8d189378e82bdf62a473a64b" +checksum = "126f97965c8ad46d6d9163268ff28432e8f6a1196a55578867832e3049df63dd" dependencies = [ "const_format_proc_macros", ] [[package]] name = "const_format_proc_macros" -version = "0.2.33" +version = "0.2.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eff1a44b93f47b1bac19a27932f5c591e43d1ba357ee4f61526c8a25603f0eb1" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" dependencies = [ "proc-macro2", "quote", @@ -553,7 +553,7 @@ version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "crossterm_winapi", "mio", "parking_lot", @@ -635,9 +635,9 @@ dependencies = [ [[package]] name = "delegate" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc2323e10c92e1cf4d86e11538512e6dc03ceb586842970b6332af3d4046a046" +checksum = "297806318ef30ad066b15792a8372858020ae3ca2e414ee6c2133b1eb9e9e945" dependencies = [ "proc-macro2", "quote", @@ -967,11 +967,11 @@ checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" [[package]] name = "inotify" -version = "0.10.2" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd168d97690d0b8c412d6b6c10360277f4d7ee495c5d0d5d5fe0854923255cc" +checksum = "f37dccff2791ab604f9babef0ba14fbe0be30bd368dc541e2b08d07c8aa908f3" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.8.0", "inotify-sys", "libc", ] @@ -999,15 +999,6 @@ dependencies = [ "syn", ] -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - [[package]] name = "is_terminal_polyfill" version = "1.70.1" @@ -1220,7 +1211,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "libc", "redox_syscall", ] @@ -1362,7 +1353,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "cfg-if", "cfg_aliases", "libc", @@ -1381,11 +1372,11 @@ dependencies = [ [[package]] name = "notify" -version = "7.0.0" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c533b4c39709f9ba5005d8002048266593c1cfaf3c5f0739d5b8ab0c6c504009" +checksum = "2fee8403b3d66ac7b26aee6e40a897d85dc5ce26f44da36b8b73e987cc52e943" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "filetime", "fsevent-sys", "inotify", @@ -1395,17 +1386,14 @@ dependencies = [ "mio", "notify-types", "walkdir", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "notify-types" -version = "1.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585d3cb5e12e01aed9e8a1f70d5c6b5e86fe2a6e48fc8cd0b3e0b8df6f6eb174" -dependencies = [ - "instant", -] +checksum = "5e0826a989adedc2a244799e823aece04662b66609d96af8dff7ac6df9a8925d" [[package]] name = "nu-ansi-term" @@ -1719,7 +1707,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "cassowary", "compact_str", "crossterm", @@ -1740,7 +1728,7 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", ] [[package]] @@ -1800,7 +1788,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" dependencies = [ "base64", - "bitflags 2.6.0", + "bitflags 2.8.0", "serde", "serde_derive", ] @@ -1857,12 +1845,13 @@ dependencies = [ [[package]] name = "rust-ini" -version = "0.20.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0698206bcb8882bf2a9ecb4c1e7785db57ff052297085a6efd4fe42302068a" +checksum = "4e310ef0e1b6eeb79169a1171daf9abcb87a2e17c03bee2c4bb100b55c75409f" dependencies = [ "cfg-if", "ordered-multimap", + "trim-in-place", ] [[package]] @@ -1883,7 +1872,7 @@ version = "0.38.42" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" dependencies = [ - "bitflags 2.6.0", + "bitflags 2.8.0", "errno", "libc", "linux-raw-sys", @@ -1940,18 +1929,18 @@ checksum = "478f121bb72bbf63c52c93011ea1791dca40140dfe13f8336c4c5ac952c33aa9" [[package]] name = "serde" -version = "1.0.215" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.215" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", @@ -2181,7 +2170,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "winnow", + "winnow 0.6.20", ] [[package]] @@ -2300,6 +2289,12 @@ dependencies = [ "cc", ] +[[package]] +name = "trim-in-place" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "343e926fc669bc8cde4fa3129ab681c63671bae288b1f1081ceee6d9d37904fc" + [[package]] name = "tuple_list" version = "0.1.3" @@ -2787,6 +2782,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e49d2d35d3fad69b39b94139037ecfb4f359f08958b9c11e7315ce770462419" +dependencies = [ + "memchr", +] + [[package]] name = "xxhash-rust" version = "0.8.13" @@ -2795,9 +2799,9 @@ checksum = "a08fd76779ae1883bbf1e46c2c46a75a0c4e37c445e68a24b01479d438f26ae6" [[package]] name = "yaml-rust2" -version = "0.8.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8902160c4e6f2fb145dbe9d6760a75e3c9522d8bf796ed7047c85919ac7115f8" +checksum = "2a1a1c0bc9823338a3bdf8c61f994f23ac004c6fa32c08cd152984499b445e8d" dependencies = [ "arraydeque", "encoding_rs", diff --git a/Cargo.toml b/Cargo.toml index 8538d5a..db518bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,10 +11,16 @@ members = [ "macros", "orchestrator", ] -exclude = ["runtime/shim", "integration/libafl/fuzzers/*", "samples/crates/", "scripts"] +exclude = [ + "runtime/shim", + "integration/libafl/fuzzers/*", + "samples/crates/", + "scripts", +] [workspace.package] license = "MIT OR Apache-2.0" +edition = "2021" [workspace.dependencies] # Unless we specify the package, it won't be renamed. @@ -25,14 +31,16 @@ runtime_noop = { path = "runtime/flavors/noop" } libafl_leaf = { path = "integration/libafl/lib" } clap = { version = "4.5", features = ["derive"] } -config = "0.14.1" -const_format = "0.2.33" -delegate = "0.13.1" +config = "0.15.7" +const_format = "0.2.34" +delegate = "0.13.2" derive_more = { version = "1.0.0", features = ["full"] } tracing = { version = "0.1", features = ["log"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] } -serde = { version = "1.0.215", features = ["derive"] } +serde = { version = "1.0", features = ["derive"] } -libafl = { git = "https://github.com/sfu-rsl/LibAFL", tag = "0.14.1", features = ["std"]} +libafl = { git = "https://github.com/sfu-rsl/LibAFL", tag = "0.14.1", features = [ + "std", +] } libafl_bolts = { git = "https://github.com/sfu-rsl/LibAFL", tag = "0.14.1" } -libafl_targets = { git = "https://github.com/sfu-rsl/LibAFL", tag = "0.14.1" } \ No newline at end of file +libafl_targets = { git = "https://github.com/sfu-rsl/LibAFL", tag = "0.14.1" } diff --git a/common/src/config.rs b/common/src/config.rs index 1b1f83a..458ee9d 100644 --- a/common/src/config.rs +++ b/common/src/config.rs @@ -1,8 +1,8 @@ use std::{env, format, string::ToString}; use config::{ - builder::DefaultState, Config, ConfigBuilder, ConfigError, Environment, File, FileFormat, - FileStoredFormat, + Config, ConfigBuilder, ConfigError, Environment, File, FileFormat, FileStoredFormat, + builder::DefaultState, }; use crate::{log_debug, log_warn}; diff --git a/common/src/pri/mod.rs b/common/src/pri/mod.rs index a7108e7..214a3d6 100644 --- a/common/src/pri/mod.rs +++ b/common/src/pri/mod.rs @@ -7,10 +7,10 @@ mod defs; #[cfg(not(core_build))] pub use defs::{ - macros::{self, list_func_decls, pass_func_names_to}, FfiPri, ProgramRuntimeInterface, + macros::{self, list_func_decls, pass_func_names_to}, }; #[cfg(core_build)] #[stable(feature = "rust1", since = "1.0.0")] -pub(crate) use defs::{macros, FfiPri, ProgramRuntimeInterface}; +pub(crate) use defs::{FfiPri, ProgramRuntimeInterface, macros}; diff --git a/common/src/utils.rs b/common/src/utils.rs index 880db42..d0eed98 100644 --- a/common/src/utils.rs +++ b/common/src/utils.rs @@ -13,8 +13,7 @@ pub(crate) use identity; #[inline(always)] pub const fn type_id_of() -> TypeId { - // NOTE: Constant evaluation of `Option` is not complete and inlining does not work. - unsafe { TypeId::new_unchecked(core::intrinsics::type_id::()) } + TypeId::new(core::intrinsics::type_id::()).unwrap() } #[cfg(feature = "std")] diff --git a/compiler/src/config.rs b/compiler/src/config.rs index 1989503..7e72142 100644 --- a/compiler/src/config.rs +++ b/compiler/src/config.rs @@ -1,4 +1,4 @@ -use derive_more::{derive::From, Deref}; +use derive_more::{Deref, derive::From}; use serde::Deserialize; use crate::CONFIG_ENV_PREFIX; @@ -49,6 +49,7 @@ impl RuntimeShimConfig { } #[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "snake_case")] pub(crate) enum RuntimeShimLocation { #[serde(alias = "core")] CoreLib, diff --git a/compiler/src/main.rs b/compiler/src/main.rs index a982793..6c11623 100644 --- a/compiler/src/main.rs +++ b/compiler/src/main.rs @@ -24,7 +24,6 @@ mod visit; extern crate rustc_abi; extern crate rustc_apfloat; extern crate rustc_ast; -extern crate rustc_attr; extern crate rustc_codegen_ssa; extern crate rustc_const_eval; extern crate rustc_data_structures; @@ -46,8 +45,6 @@ extern crate rustc_trait_selection; extern crate rustc_type_ir; extern crate thin_vec; -use rustc_driver::RunCompiler; - use common::log_info; use std::env; @@ -65,7 +62,7 @@ fn main() { fn init_logging() { use env; - use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; + use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt}; let env = env::var(constants::ENV_LOG).unwrap_or("warn".to_string()); let off_tags = [LOG_PASS_OBJECTS_TAG, LOG_PRI_DISCOVERY_TAG, LOG_BB_JUMP_TAG] @@ -86,7 +83,7 @@ fn init_logging() { } pub fn set_up_compiler() { - use rustc_session::{config::ErrorOutputType, EarlyDiagCtxt}; + use rustc_session::{EarlyDiagCtxt, config::ErrorOutputType}; rustc_driver::init_rustc_env_logger(&EarlyDiagCtxt::new(ErrorOutputType::default())); rustc_driver::install_ice_hook(URL_BUG_REPORT, |_| ()); @@ -103,7 +100,10 @@ pub fn run_compiler(args: impl IntoIterator) -> i32 { &driver_args::ArgsExt::parse_crate_options(&args), ); - rustc_driver::catch_with_exit_code(|| RunCompiler::new(&args, callbacks.as_mut()).run()) + rustc_driver::catch_with_exit_code(|| { + rustc_driver::run_compiler(&args, callbacks.as_mut()); + Ok(()) + }) } /// Returns `true` if the crate is ineffective for symbolic execution of the target. @@ -216,7 +216,6 @@ mod driver_callbacks { let passes = chain!( prerequisites_pass, - , , nctfe_pass, Instrumentor::new(true, None /* FIXME */, config.instr_rules.clone()), @@ -340,9 +339,8 @@ mod driver_callbacks { let search_path = make_search_path_for_transitive_deps(&rlib_path); log_debug!( - "Runtime shim path: {}, with {} transitive deps found at: {}", + "Runtime shim path: {} found at: {}", rlib_path.display(), - search_path.files.len(), search_path.dir.display() ); @@ -375,28 +373,11 @@ mod driver_callbacks { } fn make_search_path_for_transitive_deps(lib_file_path: &Path) -> SearchPath { - // The `deps` folder next to the library file - let deps_path = lib_file_path.parent().unwrap().join(DIR_DEPS); - // Source: rustc_session::search_paths::SearchPath::new - let files = std::fs::read_dir(&deps_path) - .map(|files| { - files - .filter_map(|e| { - e.ok().and_then(|e| { - e.file_name().to_str().map(|s| SearchPathFile { - path: e.path(), - file_name_str: s.to_string(), - }) - }) - }) - .collect::>() - }) - .unwrap_or_default(); - SearchPath { - kind: PathKind::Dependency, - dir: deps_path, - files, - } + SearchPath::new( + PathKind::Dependency, + // The `deps` folder next to the library file + lib_file_path.parent().unwrap().join(DIR_DEPS), + ) } } @@ -491,7 +472,7 @@ mod driver_callbacks { let result: PathBuf = toolchain_build::build_toolchain( current_sysroot, - rustc_config.opts.target_triple.triple(), + rustc_config.opts.target_triple.tuple(), rustc_config.output_dir.as_deref(), ) .unwrap_or_else(|e| { diff --git a/compiler/src/mir_transform/instr.rs b/compiler/src/mir_transform/instr.rs index 86bfa58..d47bd0b 100644 --- a/compiler/src/mir_transform/instr.rs +++ b/compiler/src/mir_transform/instr.rs @@ -405,7 +405,7 @@ impl<'tcx> BodyInstrumentationUnit<'tcx> { top_index: &mut BasicBlock, ) { blocks.extend_reserve(chunk.len()); - for non_sticky in chunk.extract_if(|b| !b.is_sticky) { + for non_sticky in chunk.extract_if(.., |b| !b.is_sticky) { Self::push_with_index_mapping( index_mapping, blocks, @@ -415,7 +415,7 @@ impl<'tcx> BodyInstrumentationUnit<'tcx> { ); } *top_index = blocks.next_index(); - for sticky in chunk.extract_if(|b| b.is_sticky) { + for sticky in chunk.extract_if(.., |b| b.is_sticky) { Self::push_with_index_mapping( index_mapping, blocks, diff --git a/compiler/src/mir_transform/jump.rs b/compiler/src/mir_transform/jump.rs index 638d8f8..25dcf16 100644 --- a/compiler/src/mir_transform/jump.rs +++ b/compiler/src/mir_transform/jump.rs @@ -131,6 +131,7 @@ where fn visit_inline_asm( &mut self, + _asm_macro: &mut rustc_middle::mir::InlineAsmMacro, _template: &'tcx [rustc_ast::InlineAsmTemplatePiece], _operands: &mut [rustc_middle::mir::InlineAsmOperand<'tcx>], _options: &mut rustc_ast::InlineAsmOptions, diff --git a/compiler/src/mir_transform/misc.rs b/compiler/src/mir_transform/misc.rs index 49babc9..f19eb93 100644 --- a/compiler/src/mir_transform/misc.rs +++ b/compiler/src/mir_transform/misc.rs @@ -41,7 +41,7 @@ impl<'tcx> BasicBlockDataSplitExt<'tcx> for BasicBlockData<'tcx> { fn split_with(self, predicate: impl Fn(&Statement) -> bool) -> Vec> { let mut result = Vec::new(); - let mut empty_block = BasicBlockData::new(None); + let mut empty_block = BasicBlockData::new(None, false); empty_block.is_cleanup = self.is_cleanup; let mut new_block = empty_block.clone(); diff --git a/compiler/src/passes/instr/call/context.rs b/compiler/src/passes/instr/call/context.rs index b6fa2a9..b74c36b 100644 --- a/compiler/src/passes/instr/call/context.rs +++ b/compiler/src/passes/instr/call/context.rs @@ -17,7 +17,7 @@ use crate::{ }; use super::{AtomicOrdering, InsertionLocation, OperandRef, PlaceRef, SwitchInfo}; -use crate::pri_utils::{sym::LeafSymbol, FunctionInfo, PriHelperFunctions, PriTypes}; +use crate::pri_utils::{FunctionInfo, PriHelperFunctions, PriTypes, sym::LeafSymbol}; pub(crate) trait TyContextProvider<'tcx> { fn tcx(&self) -> TyCtxt<'tcx>; @@ -558,27 +558,24 @@ macro_rules! make_caller_macro { // A macro that calls all "impl" macros defined above for the target type // except the ones to be excluded. -make_caller_macro!( - impl_traits, - [ - impl_pri_items_provider, - impl_local_manager, - impl_block_manager, - impl_jump_target_modifier, - impl_ty_ctxt_provider, - impl_body_provider, - impl_in_entry_function, - impl_has_local_decls, - impl_storage_provider, - impl_location_provider, - impl_insertion_location_provider, - impl_source_info_provider, - impl_dest_ref_provider, - impl_cast_operand_provider, - impl_discr_info_provider, - impl_atomic_intrinsic_params_provider, - ] -); +make_caller_macro!(impl_traits, [ + impl_pri_items_provider, + impl_local_manager, + impl_block_manager, + impl_jump_target_modifier, + impl_ty_ctxt_provider, + impl_body_provider, + impl_in_entry_function, + impl_has_local_decls, + impl_storage_provider, + impl_location_provider, + impl_insertion_location_provider, + impl_source_info_provider, + impl_dest_ref_provider, + impl_cast_operand_provider, + impl_discr_info_provider, + impl_atomic_intrinsic_params_provider, +]); impl_traits!(all for TransparentContext); impl_traits!(all - [ impl_body_provider ] for InBodyContext<'tcxb, 'bd>); diff --git a/compiler/src/passes/instr/call/mod.rs b/compiler/src/passes/instr/call/mod.rs index c137862..ced88cc 100644 --- a/compiler/src/passes/instr/call/mod.rs +++ b/compiler/src/passes/instr/call/mod.rs @@ -268,16 +268,17 @@ mod implementation { use crate::passes::Storage; use crate::pri_utils::sym::intrinsics::atomic::LeafAtomicIntrinsicSymbol; use crate::pri_utils::{ - sym::{self, LeafSymbol}, FunctionInfo, + sym::{self, LeafSymbol}, }; + use crate::utils::mir::TyCtxtExt; use self::ctxtreqs::*; use self::utils::ty::TyExt; use super::{super::MirSourceExt, context::*, *}; - use utils::*; use InsertionLocation::*; + use utils::*; pub(crate) trait MirCallAdder<'tcx> { fn make_bb_for_call( @@ -532,8 +533,18 @@ mod implementation { fn_def_ty } - fn current_param_env(&self) -> mir_ty::ParamEnv<'tcx> { - self.context.tcx().param_env(self.current_func_id()) + fn current_typing_env(&self) -> mir_ty::TypingEnv<'tcx> { + let body_def_id = self.current_func_id(); + mir_ty::TypingEnv { + typing_mode: if let Some(body_def_id) = body_def_id.as_local() { + self.tcx().typing_mode_for_body(body_def_id) + } else { + // It looks like that the type will be resolved at the crate level, + // so for external bodies they should be already resolved. + mir_ty::TypingMode::non_body_analysis() + }, + param_env: self.context.tcx().param_env(self.current_func_id()), + } } } @@ -682,15 +693,18 @@ mod implementation { destination: Place<'tcx>, target: Option, ) -> BasicBlockData<'tcx> { - BasicBlockData::new(Some(terminator::call( - self.context.tcx(), - func_id, - generic_args, - args, - destination, - target, - self.context.source_info(), - ))) + BasicBlockData::new( + Some(terminator::call( + self.context.tcx(), + func_id, + generic_args, + args, + destination, + target, + self.context.source_info(), + )), + false, + ) } } @@ -799,49 +813,40 @@ mod implementation { let (func_name, additional_args) = match proj { ProjectionElem::Deref => (sym::ref_place_deref, vec![]), - ProjectionElem::Field(index, _) => ( - sym::ref_place_field, - vec![operand::const_from_uint( + ProjectionElem::Field(index, _) => { + (sym::ref_place_field, vec![operand::const_from_uint( self.context.tcx(), u32::from(index), - )], - ), + )]) + } ProjectionElem::Index(index) => { let BlocksAndResult(additional_blocks, index_ref) = self.internal_reference_place(&Place::from(index)); new_blocks.extend(additional_blocks); - ( - sym::ref_place_index, - vec![operand::copy_for_local(index_ref)], - ) + (sym::ref_place_index, vec![operand::copy_for_local( + index_ref, + )]) } ProjectionElem::ConstantIndex { offset, min_length, from_end, - } => ( - sym::ref_place_constant_index, - vec![ - operand::const_from_uint(self.context.tcx(), offset), - operand::const_from_uint(self.context.tcx(), min_length), - operand::const_from_bool(self.context.tcx(), from_end), - ], - ), - ProjectionElem::Subslice { from, to, from_end } => ( - sym::ref_place_subslice, - vec![ - operand::const_from_uint(self.context.tcx(), from), - operand::const_from_uint(self.context.tcx(), to), - operand::const_from_bool(self.context.tcx(), from_end), - ], - ), - ProjectionElem::Downcast(_, index) => ( - sym::ref_place_downcast, - vec![operand::const_from_uint( + } => (sym::ref_place_constant_index, vec![ + operand::const_from_uint(self.context.tcx(), offset), + operand::const_from_uint(self.context.tcx(), min_length), + operand::const_from_bool(self.context.tcx(), from_end), + ]), + ProjectionElem::Subslice { from, to, from_end } => (sym::ref_place_subslice, vec![ + operand::const_from_uint(self.context.tcx(), from), + operand::const_from_uint(self.context.tcx(), to), + operand::const_from_bool(self.context.tcx(), from_end), + ]), + ProjectionElem::Downcast(_, index) => { + (sym::ref_place_downcast, vec![operand::const_from_uint( self.context.tcx(), u32::from(index), - )], - ), + )]) + } ProjectionElem::OpaqueCast(_) => (sym::ref_place_opaque_cast, vec![]), ProjectionElem::Subtype(_) => (sym::ref_place_subtype, vec![]), }; @@ -891,9 +896,9 @@ mod implementation { place_ref: Local, place_ty: Ty<'tcx>, ) -> Vec> { - if unlikely(!place_ty.is_sized(self.tcx(), self.current_param_env())) { + if unlikely(!place_ty.is_sized(self.tcx(), self.current_typing_env())) { log_warn!("Encountered unsized type. Skipping size setting."); - return vec![BasicBlockData::new(Some(terminator::goto(None)))]; + return vec![BasicBlockData::new(Some(terminator::goto(None)), false)]; } let (get_call_block, size_local) = self.make_bb_for_helper_call_with_all( @@ -903,13 +908,10 @@ mod implementation { None, ); - let set_call_block = self.make_bb_for_call( - sym::set_place_size, - vec![ - operand::copy_for_local(place_ref), - operand::move_for_local(size_local), - ], - ); + let set_call_block = self.make_bb_for_call(sym::set_place_size, vec![ + operand::copy_for_local(place_ref), + operand::move_for_local(size_local), + ]); vec![get_call_block, set_call_block] } @@ -924,22 +926,16 @@ mod implementation { } else if ty.is_char() { Some((sym::set_place_type_char, vec![])) } else if ty.is_integral() { - Some(( - sym::set_place_type_int, - vec![ - operand::const_from_uint(tcx, ty.primitive_size(tcx).bits()), - operand::const_from_bool(tcx, ty.is_signed()), - ], - )) + Some((sym::set_place_type_int, vec![ + operand::const_from_uint(tcx, ty.primitive_size(tcx).bits()), + operand::const_from_bool(tcx, ty.is_signed()), + ])) } else if ty.is_floating_point() { let (e_bits, s_bits) = ty::ebit_sbit_size(ty); - Some(( - sym::set_place_type_float, - vec![ - operand::const_from_uint(tcx, e_bits), - operand::const_from_uint(tcx, s_bits), - ], - )) + Some((sym::set_place_type_float, vec![ + operand::const_from_uint(tcx, e_bits), + operand::const_from_uint(tcx, s_bits), + ])) } else { None } { @@ -957,13 +953,10 @@ mod implementation { }; #[cfg(place_addr)] - blocks.push(self.make_bb_for_call( - sym::set_place_type_id, - vec![ - operand::copy_for_local(place_ref), - operand::move_for_local(id_local), - ], - )); + blocks.push(self.make_bb_for_call(sym::set_place_type_id, vec![ + operand::copy_for_local(place_ref), + operand::move_for_local(id_local), + ])); blocks } @@ -1023,10 +1016,9 @@ mod implementation { }; BlocksAndResult::from( - self.make_bb_for_operand_ref_call( - func_name, - vec![operand::copy_for_local(place_ref)], - ), + self.make_bb_for_operand_ref_call(func_name, vec![operand::copy_for_local( + place_ref, + )]), ) .prepend(additional_blocks) } @@ -1068,7 +1060,7 @@ mod implementation { self.internal_reference_func_def_const_operand(constant) } // NOTE: Check this after all other ZSTs that you want to distinguish. - else if ty::size_of(tcx, ty, self.current_param_env()) == rustc_abi::Size::ZERO { + else if ty::size_of(tcx, ty, self.current_typing_env()) == rustc_abi::Size::ZERO { self.make_bb_for_operand_ref_call(sym::ref_operand_const_zst, Default::default()) .into() } else if let Some(c) = operand::const_try_as_unevaluated(constant) { @@ -1119,10 +1111,9 @@ mod implementation { func_name: LeafSymbol, constant: &Box>, ) -> BlocksAndResult<'tcx> { - self.make_bb_for_operand_ref_call( - func_name, - vec![operand::const_from_existing(constant)], - ) + self.make_bb_for_operand_ref_call(func_name, vec![operand::const_from_existing( + constant, + )]) .into() } @@ -1136,14 +1127,12 @@ mod implementation { let tcx = self.tcx(); let (bit_rep_local, additional_stmts) = utils::cast_int_to_bit_rep(tcx, &mut self.context, constant); - let (mut block, result) = self.make_bb_for_operand_ref_call( - sym::ref_operand_const_int, - vec![ + let (mut block, result) = + self.make_bb_for_operand_ref_call(sym::ref_operand_const_int, vec![ operand::move_for_local(bit_rep_local), operand::const_from_uint(tcx, ty.primitive_size(tcx).bits()), operand::const_from_bool(tcx, ty.is_signed()), - ], - ); + ]); block.statements.extend(additional_stmts); (block, result).into() } @@ -1159,14 +1148,11 @@ mod implementation { let (bit_rep_local, conversion_block) = utils::cast_float_to_bit_rep(tcx, &mut self.context, constant); let (e_bits, s_bits) = ty::ebit_sbit_size(ty); - let block_pair = self.make_bb_for_operand_ref_call( - sym::ref_operand_const_float, - vec![ - operand::move_for_local(bit_rep_local), - operand::const_from_uint(tcx, e_bits), - operand::const_from_uint(tcx, s_bits), - ], - ); + let block_pair = self.make_bb_for_operand_ref_call(sym::ref_operand_const_float, vec![ + operand::move_for_local(bit_rep_local), + operand::const_from_uint(tcx, e_bits), + operand::const_from_uint(tcx, s_bits), + ]); BlocksAndResult::from(block_pair).prepend([conversion_block]) } @@ -1184,10 +1170,10 @@ mod implementation { operand::const_from_existing(constant), None, ); - let mut block_pair = self.make_bb_for_operand_ref_call( - sym::ref_operand_const_byte_str, - vec![operand::move_for_local(slice_local)], - ); + let mut block_pair = self + .make_bb_for_operand_ref_call(sym::ref_operand_const_byte_str, vec![ + operand::move_for_local(slice_local), + ]); block_pair.0.statements.insert(0, slice_assignment); BlocksAndResult::from(block_pair) } @@ -1266,35 +1252,30 @@ mod implementation { Self: MirCallAdder<'tcx> + BlockInserter<'tcx>, C: ForAssignment<'tcx>, { - type Cast<'b> = RuntimeCallAdder> - where CastAssignmentContext<'b, C>: ForCasting<'tcx> + 'b; + type Cast<'b> + = RuntimeCallAdder> + where + CastAssignmentContext<'b, C>: ForCasting<'tcx> + 'b; fn by_use(&mut self, operand: OperandRef) { - self.add_bb_for_assign_call( - sym::assign_use, - vec![operand::copy_for_local(operand.into())], - ) + self.add_bb_for_assign_call(sym::assign_use, vec![operand::copy_for_local( + operand.into(), + )]) } fn by_repeat(&mut self, operand: OperandRef, count: &Const<'tcx>) { - self.add_bb_for_assign_call( - sym::assign_repeat, - vec![ - operand::copy_for_local(operand.into()), - #[allow(clippy::clone_on_copy)] - operand::const_from_existing_ty_const(self.tcx().types.usize, count.clone()), - ], - ) + self.add_bb_for_assign_call(sym::assign_repeat, vec![ + operand::copy_for_local(operand.into()), + #[allow(clippy::clone_on_copy)] + operand::const_from_existing_ty_const(self.tcx().types.usize, count.clone()), + ]) } fn by_ref(&mut self, place: PlaceRef, is_mutable: bool) { - self.add_bb_for_assign_call( - sym::assign_ref, - vec![ - operand::copy_for_local(place.into()), - operand::const_from_bool(self.context.tcx(), is_mutable), - ], - ) + self.add_bb_for_assign_call(sym::assign_ref, vec![ + operand::copy_for_local(place.into()), + operand::const_from_bool(self.context.tcx(), is_mutable), + ]) } fn by_thread_local_ref(&mut self, _def_id: &DefId) { @@ -1306,20 +1287,16 @@ mod implementation { } fn by_raw_ptr(&mut self, place: PlaceRef, is_mutable: bool) { - self.add_bb_for_assign_call( - sym::assign_raw_ptr_of, - vec![ - operand::copy_for_local(place.into()), - operand::const_from_bool(self.context.tcx(), is_mutable), - ], - ) + self.add_bb_for_assign_call(sym::assign_raw_ptr_of, vec![ + operand::copy_for_local(place.into()), + operand::const_from_bool(self.context.tcx(), is_mutable), + ]) } fn by_len(&mut self, place: PlaceRef) { - self.add_bb_for_assign_call( - sym::assign_len, - vec![operand::copy_for_local(place.into())], - ) + self.add_bb_for_assign_call(sym::assign_len, vec![operand::copy_for_local( + place.into(), + )]) } fn by_cast(&mut self, operand: OperandRef) -> Self::Cast<'_> { @@ -1345,14 +1322,11 @@ mod implementation { local }; - self.add_bb_for_assign_call( - sym::assign_binary_op, - vec![ - operand::move_for_local(operator_local), - operand::copy_for_local(first.into()), - operand::copy_for_local(second.into()), - ], - ) + self.add_bb_for_assign_call(sym::assign_binary_op, vec![ + operand::move_for_local(operator_local), + operand::copy_for_local(first.into()), + operand::copy_for_local(second.into()), + ]) } fn by_unary_op(&mut self, operator: &UnOp, operand: OperandRef) { @@ -1369,13 +1343,10 @@ mod implementation { local }; - self.add_bb_for_assign_call( - sym::assign_unary_op, - vec![ - operand::move_for_local(operator_local), - operand::copy_for_local(operand.into()), - ], - ) + self.add_bb_for_assign_call(sym::assign_unary_op, vec![ + operand::move_for_local(operator_local), + operand::copy_for_local(operand.into()), + ]) } fn by_nullary_op(&mut self) { @@ -1387,10 +1358,9 @@ mod implementation { } fn by_discriminant(&mut self, place: PlaceRef) { - self.add_bb_for_assign_call( - sym::assign_discriminant, - vec![operand::copy_for_local(place.into())], - ) + self.add_bb_for_assign_call(sym::assign_discriminant, vec![operand::copy_for_local( + place.into(), + )]) } fn by_aggregate_array(&mut self, items: &[OperandRef]) { @@ -1406,14 +1376,9 @@ mod implementation { } fn by_aggregate_enum(&mut self, fields: &[OperandRef], variant: VariantIdx) { - self.add_bb_for_adt_assign_call( - sym::assign_aggregate_enum, - fields, - vec![operand::const_from_uint( - self.context.tcx(), - variant.as_u32(), - )], - ) + self.add_bb_for_adt_assign_call(sym::assign_aggregate_enum, fields, vec![ + operand::const_from_uint(self.context.tcx(), variant.as_u32()), + ]) } fn by_aggregate_union(&mut self, active_field: FieldIdx, value: OperandRef) { @@ -1466,23 +1431,17 @@ mod implementation { self.insert_blocks([block]); id_local }; - self.add_bb_for_assign_call( - sym::assign_shallow_init_box, - vec![ - operand::copy_for_local(operand.into()), - operand::move_for_local(id_local), - ], - ); + self.add_bb_for_assign_call(sym::assign_shallow_init_box, vec![ + operand::copy_for_local(operand.into()), + operand::move_for_local(id_local), + ]); } fn its_discriminant_to(&mut self, variant_index: &VariantIdx) { - self.add_bb_for_assign_call( - sym::set_discriminant, - vec![operand::const_from_uint( - self.context.tcx(), - variant_index.as_u32(), - )], - ) + self.add_bb_for_assign_call(sym::set_discriminant, vec![operand::const_from_uint( + self.context.tcx(), + variant_index.as_u32(), + )]) } } @@ -1613,25 +1572,19 @@ mod implementation { let is_signed = ty.is_signed(); let bits = ty.primitive_size(tcx).bits(); - self.add_bb_for_cast_assign_call_with_args( - sym::assign_cast_integer, - vec![ - operand::const_from_uint(tcx, bits), - operand::const_from_bool(tcx, is_signed), - ], - ) + self.add_bb_for_cast_assign_call_with_args(sym::assign_cast_integer, vec![ + operand::const_from_uint(tcx, bits), + operand::const_from_bool(tcx, is_signed), + ]) } } fn to_float(&mut self, ty: Ty<'tcx>) { let (e_bits, s_bits) = ty::ebit_sbit_size(ty); - self.add_bb_for_cast_assign_call_with_args( - sym::assign_cast_float, - vec![ - operand::const_from_uint(self.context.tcx(), e_bits), - operand::const_from_uint(self.context.tcx(), s_bits), - ], - ) + self.add_bb_for_cast_assign_call_with_args(sym::assign_cast_float, vec![ + operand::const_from_uint(self.context.tcx(), e_bits), + operand::const_from_uint(self.context.tcx(), s_bits), + ]) } fn through_unsizing(&mut self) { @@ -1660,11 +1613,11 @@ mod implementation { } fn to_another_ptr(&mut self, ty: Ty<'tcx>, kind: CastKind) { - use rustc_middle::ty::adjustment::PointerCoercion::*; use CastKind::*; + use rustc_middle::ty::adjustment::PointerCoercion::*; debug_assert_matches!( kind, - PtrToPtr | FnPtrToPtr | PointerCoercion(MutToConstPointer | ArrayToPointer) + PtrToPtr | FnPtrToPtr | PointerCoercion(MutToConstPointer | ArrayToPointer, _) ); /* NOTE: Currently, we do not distinguish between different pointer casts. * This is because they all keep the data untouched and are just about @@ -1678,10 +1631,9 @@ mod implementation { self.insert_blocks([block]); id_local }; - self.add_bb_for_cast_assign_call_with_args( - sym::assign_cast_transmute, - vec![operand::move_for_local(id_local)], - ) + self.add_bb_for_cast_assign_call_with_args(sym::assign_cast_transmute, vec![ + operand::move_for_local(id_local), + ]) } } @@ -1715,10 +1667,9 @@ mod implementation { self.insert_blocks([block]); id_local }; - self.add_bb_for_cast_assign_call_with_args( - func_name, - vec![operand::move_for_local(id_local)], - ); + self.add_bb_for_cast_assign_call_with_args(func_name, vec![operand::move_for_local( + id_local, + )]); } } @@ -1793,22 +1744,16 @@ mod implementation { } } else if discr_ty.is_integral() { // NOTE: Discriminants are integers. - ( - sym::take_branch_int, - vec![ - operand::const_from_uint(tcx, value), - operand::const_from_uint(tcx, discr_ty.primitive_size(tcx).bits()), - operand::const_from_bool(tcx, discr_ty.is_signed()), - ], - ) + (sym::take_branch_int, vec![ + operand::const_from_uint(tcx, value), + operand::const_from_uint(tcx, discr_ty.primitive_size(tcx).bits()), + operand::const_from_bool(tcx, discr_ty.is_signed()), + ]) } else if discr_ty.is_char() { - ( - sym::take_branch_char, - vec![operand::const_from_char( - tcx, - char::from_u32(value.try_into().unwrap()).unwrap(), - )], - ) + (sym::take_branch_char, vec![operand::const_from_char( + tcx, + char::from_u32(value.try_into().unwrap()).unwrap(), + )]) } else { unreachable!( "Branching node discriminant is supposed to be either bool, int, char, or enum discriminant." @@ -1942,7 +1887,7 @@ mod implementation { let BlocksAndResult(def_blocks, def_local) = func::definition_of_callee( tcx, self, - self.current_param_env(), + self.current_typing_env(), func, args.first().map(|a| &a.node), ); @@ -1966,18 +1911,15 @@ mod implementation { self, func, args.iter().map(|a| &a.node), - self.current_param_env(), + self.current_typing_env(), ); - let mut block = self.make_bb_for_call( - sym::before_call_func, - vec![ - operand::move_for_local(def_local), - operand::move_for_local(func_ref.into()), - operand::move_for_local(arguments_local), - operand::const_from_bool(tcx, are_args_tupled), - ], - ); + let mut block = self.make_bb_for_call(sym::before_call_func, vec![ + operand::move_for_local(def_local), + operand::move_for_local(func_ref.into()), + operand::move_for_local(arguments_local), + operand::const_from_bool(tcx, are_args_tupled), + ]); block.statements.extend(additional_stmts); blocks.push(block); @@ -1998,7 +1940,7 @@ mod implementation { let def_local = { let BlocksAndResult(def_blocks, def_local) = - func::definition_of_func(tcx, self, fn_def_ty, self.current_param_env()); + func::definition_of_func(tcx, self, fn_def_ty, self.current_typing_env()); blocks.extend(def_blocks); def_local }; @@ -2060,10 +2002,10 @@ mod implementation { fn after_call_func(&mut self, destination: &Place<'tcx>) { // we want the place reference to be after the function call as well let BlocksAndResult(mut blocks, dest_ref) = self.internal_reference_place(destination); - let after_call_block = self.make_bb_for_call( - sym::after_call_func, - vec![operand::copy_for_local(dest_ref)], - ); + let after_call_block = + self.make_bb_for_call(sym::after_call_func, vec![operand::copy_for_local( + dest_ref, + )]); blocks.push(after_call_block); debug_assert_matches!( self.context.insertion_loc(), @@ -2092,13 +2034,10 @@ mod implementation { id_local }; - ( - blocks, - [ - operand::const_from_uint(self.tcx(), 2 as common::types::LocalIndex), - operand::move_for_local(tuple_id_local), - ], - ) + (blocks, [ + operand::const_from_uint(self.tcx(), 2 as common::types::LocalIndex), + operand::move_for_local(tuple_id_local), + ]) } } @@ -2403,13 +2342,10 @@ mod implementation { AssertKind::BoundsCheck { len, index } => { let len_ref = self.reference_operand(len); let index_ref = self.reference_operand(index); - Some(( - sym::assert_bounds_check, - vec![ - operand::copy_for_local(len_ref.into()), - operand::copy_for_local(index_ref.into()), - ], - )) + Some((sym::assert_bounds_check, vec![ + operand::copy_for_local(len_ref.into()), + operand::copy_for_local(index_ref.into()), + ])) } AssertKind::Overflow(operator, op1, op2) => { let tcx = self.tcx(); @@ -2428,36 +2364,30 @@ mod implementation { let op1_ref = self.reference_operand(op1); let op2_ref = self.reference_operand(op2); - Some(( - sym::assert_overflow, - vec![ - // TODO: double check that moves and copies here are correct - operand::move_for_local(operator_local), - operand::copy_for_local(op1_ref.into()), - operand::copy_for_local(op2_ref.into()), - ], - )) + Some((sym::assert_overflow, vec![ + // TODO: double check that moves and copies here are correct + operand::move_for_local(operator_local), + operand::copy_for_local(op1_ref.into()), + operand::copy_for_local(op2_ref.into()), + ])) } AssertKind::OverflowNeg(op) => { let op_ref = self.reference_operand(op); - Some(( - sym::assert_overflow_neg, - vec![operand::copy_for_local(op_ref.into())], - )) + Some((sym::assert_overflow_neg, vec![operand::copy_for_local( + op_ref.into(), + )])) } AssertKind::DivisionByZero(op) => { let op_ref = self.reference_operand(op); - Some(( - sym::assert_div_by_zero, - vec![operand::copy_for_local(op_ref.into())], - )) + Some((sym::assert_div_by_zero, vec![operand::copy_for_local( + op_ref.into(), + )])) } AssertKind::RemainderByZero(op) => { let op_ref = self.reference_operand(op); - Some(( - sym::assert_rem_by_zero, - vec![operand::copy_for_local(op_ref.into())], - )) + Some((sym::assert_rem_by_zero, vec![operand::copy_for_local( + op_ref.into(), + )])) } AssertKind::ResumedAfterReturn(..) | AssertKind::ResumedAfterPanic(..) => { /* NOTE: These two assertions look to be used to make sure @@ -2470,13 +2400,10 @@ mod implementation { AssertKind::MisalignedPointerDereference { required, found } => { let required_ref = self.reference_operand(required); let found_ref = self.reference_operand(found); - Some(( - sym::assert_misaligned_ptr_deref, - vec![ - operand::copy_for_local(required_ref.into()), - operand::copy_for_local(found_ref.into()), - ], - )) + Some((sym::assert_misaligned_ptr_deref, vec![ + operand::copy_for_local(required_ref.into()), + operand::copy_for_local(found_ref.into()), + ])) } } } @@ -2527,13 +2454,10 @@ mod implementation { { fn debug_info(&mut self, info: &T) { let serialized = ron::to_string(info).unwrap(); - let block = self.make_bb_for_call( - sym::debug_info, - vec![operand::const_from_byte_str( - self.context.tcx(), - serialized.as_bytes(), - )], - ); + let block = self.make_bb_for_call(sym::debug_info, vec![operand::const_from_byte_str( + self.context.tcx(), + serialized.as_bytes(), + )]); self.insert_blocks([block]); } } @@ -2559,7 +2483,7 @@ mod implementation { SourceInfo, Statement, }, query::Key, - ty::{adjustment::PointerCoercion, ParamEnv, Ty, TyCtxt, TyKind}, + ty::{ParamEnv, Ty, TyCtxt, TyKind, TypingEnv, adjustment::PointerCoercion}, }; use rustc_span::DUMMY_SP; @@ -2648,14 +2572,9 @@ mod implementation { Operand::Constant(Box::new(ConstOperand { span: DUMMY_SP, user_ty: None, - const_: Const::from_ty_const( - mir_ty::Const::new_value( - tcx, - mir_ty::ValTree::from_raw_bytes(tcx, value), - ty, - ), + const_: Const::from_value( + tcx.valtree_to_const_val((ty, mir_ty::ValTree::from_raw_bytes(tcx, value))), ty, - tcx, ), })) } @@ -2758,7 +2677,7 @@ mod implementation { pub mod rvalue { use rustc_index::IndexVec; - use rustc_middle::mir::{AggregateKind, BorrowKind, CastKind}; + use rustc_middle::mir::{AggregateKind, BorrowKind, CastKind, CoercionSource}; use super::*; @@ -2770,15 +2689,19 @@ mod implementation { operand: Operand<'tcx>, to_ty: Ty<'tcx>, ) -> Rvalue<'tcx> { - cast_to_coerced(PointerCoercion::Unsize, operand, to_ty) + cast_to_coerced_as(PointerCoercion::Unsize, operand, to_ty) } - pub fn cast_to_coerced<'tcx>( + pub fn cast_to_coerced_as<'tcx>( coercion: PointerCoercion, operand: Operand<'tcx>, to_ty: Ty<'tcx>, ) -> Rvalue<'tcx> { - Rvalue::Cast(CastKind::PointerCoercion(coercion), operand, to_ty) + Rvalue::Cast( + CastKind::PointerCoercion(coercion, CoercionSource::AsCast), + operand, + to_ty, + ) } pub fn cast_to_fn_ptr<'tcx>( @@ -2786,7 +2709,7 @@ mod implementation { operand: Operand<'tcx>, operand_ty: Ty<'tcx>, ) -> Rvalue<'tcx> { - cast_to_coerced( + cast_to_coerced_as( PointerCoercion::ReifyFnPointer, operand, Ty::new_fn_ptr(tcx, ty::fn_ptr_sig(tcx, operand_ty)), @@ -2819,7 +2742,7 @@ mod implementation { pub trait TyExt<'tcx> { fn is_trivially_tuple(self) -> bool; - fn is_tuple(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> bool; + fn is_tuple(self, tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>) -> bool; } impl<'tcx> TyExt<'tcx> for Ty<'tcx> { @@ -2828,12 +2751,12 @@ mod implementation { matches!(self.kind(), TyKind::Tuple(..)) } - fn is_tuple(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> bool { + fn is_tuple(self, tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>) -> bool { self.is_trivially_tuple() || is_trait( tcx, self, - param_env, + typing_env, tcx.lang_items().tuple_trait().unwrap(), ) } @@ -2846,13 +2769,13 @@ mod implementation { pub fn size_of<'tcx>( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, ) -> Size { - tcx.layout_of(param_env.and(ty)).unwrap().size + tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size } pub fn ebit_sbit_size<'tcx>(ty: Ty<'tcx>) -> (u64, u64) { - use rustc_apfloat::{ieee::*, Float}; + use rustc_apfloat::{Float, ieee::*}; let mir_ty::Float(float_ty) = ty.kind() else { panic!("Expected floating point type but received: {}", ty) }; @@ -3024,15 +2947,15 @@ mod implementation { pub(super) fn is_trait<'tcx>( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, trait_def_id: DefId, ) -> bool { use rustc_infer::infer::TyCtxtInferExt; use rustc_trait_selection::infer::InferCtxtExt; tcx.infer_ctxt() - .build() - .type_implements_trait(trait_def_id, [ty], param_env) + .build(typing_env.typing_mode) + .type_implements_trait(trait_def_id, [ty], typing_env.param_env) .must_apply_modulo_regions() } } @@ -3086,7 +3009,7 @@ mod implementation { pub(super) mod func { use common::log_info; - use mir_ty::{AssocItem, ExistentialTraitRef, TraitRef}; + use mir_ty::{AssocItem, ExistentialTraitRef, TraitRef, TypingEnv}; use rustc_trait_selection::traits::is_vtable_safe_method; use crate::passes::instr::decision::get_baked_dyn_def_rules; @@ -3103,7 +3026,7 @@ mod implementation { + StorageProvider ), fn_def_ty: Ty<'tcx>, - param_env: mir_ty::ParamEnv<'tcx>, + typing_env: mir_ty::TypingEnv<'tcx>, ) -> BlocksAndResult<'tcx> { let TyKind::FnDef(def_id, generic_args) = *fn_def_ty.kind() else { unreachable!( @@ -3115,7 +3038,7 @@ mod implementation { let fn_value = operand::func(tcx, def_id, generic_args); if let Some((trait_ref, trait_item)) = as_dyn_compatible_method(tcx, def_id) - && trait_ref.self_ty().is_sized(tcx, param_env) + && trait_ref.self_ty().is_sized(tcx, typing_env) { let ruled_out = get_baked_dyn_def_rules(call_adder.storage()) .accept(&(tcx, def_id)) @@ -3130,7 +3053,7 @@ mod implementation { def_of_dyn_compatible_method( tcx, call_adder, - param_env, + typing_env, fn_value, trait_ref, trait_item.def_id, @@ -3169,7 +3092,7 @@ mod implementation { + MirCallAdder<'tcx> + PriItemsProvider<'tcx> ), - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, fn_value: Operand<'tcx>, trait_ref: TraitRef<'tcx>, method_id: DefId, @@ -3181,7 +3104,7 @@ mod implementation { let (raw_ptr_of_receiver_block, raw_ptr_of_receiver_local) = raw_ptr_of_receiver( tcx, call_adder, - param_env, + typing_env, call_adder .body() .args_iter() @@ -3230,7 +3153,7 @@ mod implementation { .impl_of_method(def_id) .and_then(|impl_id| tcx.impl_trait_ref(impl_id)) .map(|trait_ref| trait_ref.instantiate_identity()) - .filter(|trait_ref| tcx.is_object_safe(trait_ref.def_id)) + .filter(|trait_ref| tcx.is_dyn_compatible(trait_ref.def_id)) .filter(|trait_ref| { trait_ref.def_id != tcx.lang_items().deref_trait().unwrap() })?; @@ -3244,7 +3167,7 @@ mod implementation { call_adder: &mut ( impl BodyLocalManager<'tcx> + MirCallAdder<'tcx> + PriItemsProvider<'tcx> ), - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, fn_value: Operand<'tcx>, first_arg: Option<&Operand<'tcx>>, ) -> BlocksAndResult<'tcx> { @@ -3266,7 +3189,7 @@ mod implementation { def_of_possibly_virtual_callee( tcx, call_adder, - param_env, + typing_env, fn_value, item.def_id, self_ty, @@ -3308,7 +3231,7 @@ mod implementation { call_adder: &mut ( impl BodyLocalManager<'tcx> + MirCallAdder<'tcx> + PriItemsProvider<'tcx> ), - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, fn_value: Operand<'tcx>, method_id: DefId, self_ty: Ty<'tcx>, @@ -3319,7 +3242,7 @@ mod implementation { let (receiver_raw_ptr_block, receiver_raw_ptr_local) = match receiver { Operand::Copy(place) | Operand::Move(place) => { - raw_ptr_of_receiver(tcx, call_adder, param_env, *place, self_ty) + raw_ptr_of_receiver(tcx, call_adder, typing_env, *place, self_ty) } Operand::Constant(..) => { let receiver_local = call_adder.add_local(receiver.ty(call_adder, tcx)); @@ -3330,7 +3253,7 @@ mod implementation { let (mut block, local) = raw_ptr_of_receiver( tcx, call_adder, - param_env, + typing_env, receiver_local.into(), self_ty, ); @@ -3373,14 +3296,14 @@ mod implementation { + MirCallAdder<'tcx> + PriItemsProvider<'tcx> ), - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, receiver_place: Place<'tcx>, self_ty: Ty<'tcx>, ) -> (BasicBlockData<'tcx>, Local) { - let self_ty = tcx.normalize_erasing_regions(param_env, self_ty); + let self_ty = tcx.normalize_erasing_regions(typing_env, self_ty); let receiver_ty = receiver_place.ty(call_adder, tcx).ty; - let receiver_ty = tcx.normalize_erasing_regions(param_env, receiver_ty); + let receiver_ty = tcx.normalize_erasing_regions(typing_env, receiver_ty); let is_self_ref = if let TyKind::Ref(_, pointee, _) = receiver_ty.kind() && *pointee == self_ty @@ -3395,7 +3318,7 @@ mod implementation { let assignment = assignment::create( Place::from(local), Rvalue::RawPtr( - mir::Mutability::Not, + mir::RawPtrKind::Const, if is_self_ref { receiver_place.project_deeper(&[ProjectionElem::Deref], tcx) } else { @@ -3403,7 +3326,7 @@ mod implementation { }, ), ); - let mut block = BasicBlockData::new(Some(terminator::goto(None))); + let mut block = BasicBlockData::new(Some(terminator::goto(None)), false); block.statements.push(assignment); (block, local) } else { @@ -3419,7 +3342,7 @@ mod implementation { let is_pin = tcx .lang_items() .pin_type() - .zip(receiver_ty.ty_def_id()) + .zip(receiver_ty.def_id_for_ty_in_cycle()) .is_some_and(|(a, b)| a == b); let converter_func = if is_pin { call_adder.pri_helper_funcs().receiver_pin_to_raw_ptr @@ -3506,7 +3429,7 @@ mod implementation { local_manager: &impl HasLocalDecls<'tcx>, callee: &Operand<'tcx>, args: impl Iterator>, - param_env: mir_ty::ParamEnv<'tcx>, + typing_env: mir_ty::TypingEnv<'tcx>, ) -> bool { // Tupling is only observed in fn trait (closure) calls. if !is_fn_trait_method_call(tcx, callee.ty(local_manager, tcx)) { @@ -3520,7 +3443,7 @@ mod implementation { args.last() .unwrap() .ty(local_manager, tcx) - .is_tuple(tcx, param_env), + .is_tuple(tcx, typing_env), "Fn trait method call without tupled arguments observed. {:?}, {:?}", callee, args.iter() @@ -3620,15 +3543,18 @@ mod implementation { } else { context.pri_helper_funcs().f64_to_bits }; - let block = BasicBlockData::new(Some(terminator::call( - tcx, - conversion_func.def_id, - iter::empty(), - vec![operand::const_from_existing(constant)], - bit_rep_local.into(), - None, - context.source_info(), - ))); + let block = BasicBlockData::new( + Some(terminator::call( + tcx, + conversion_func.def_id, + iter::empty(), + vec![operand::const_from_existing(constant)], + bit_rep_local.into(), + None, + context.source_info(), + )), + false, + ); (bit_rep_local, block) } @@ -3641,7 +3567,7 @@ mod implementation { let ptr_local = local_manager.add_local(Ty::new_imm_ptr(tcx, place_ty)); let ptr_assignment = assignment::create( Place::from(ptr_local), - mir::Rvalue::RawPtr(rustc_ast::Mutability::Not, place.clone()), + mir::Rvalue::RawPtr(mir::RawPtrKind::Const, place.clone()), ); (ptr_assignment, ptr_local) diff --git a/compiler/src/passes/instr/decision.rs b/compiler/src/passes/instr/decision.rs index c33ec60..f4e6d9d 100644 --- a/compiler/src/passes/instr/decision.rs +++ b/compiler/src/passes/instr/decision.rs @@ -16,7 +16,7 @@ pub(super) const TAG_INSTR_DECISION: &str = concatcp!(super::TAG_INSTRUMENTATION const TOOL_NAME: &str = crate::constants::TOOL_LEAF; const ATTR_NAME: &str = "instrument"; -pub(super) use rules::{get_baked_dyn_def_rules, KEY_RULES}; +pub(super) use rules::{KEY_RULES, get_baked_dyn_def_rules}; pub(super) fn should_instrument<'tcx>( tcx: TyCtxt<'tcx>, @@ -71,7 +71,6 @@ fn decide_instance_kind(kind: &InstanceKind) -> bool { | VTableShim(..) | Virtual(..) | ConstructCoroutineInClosureShim { .. } - | CoroutineKindShim { .. } | ThreadLocalShim(..) | DropGlue(..) | FnPtrAddrShim(..) @@ -83,8 +82,8 @@ fn decide_instance_kind(kind: &InstanceKind) -> bool { /// that are currently problematic to instrument. fn get_exceptional_exclusions() -> Vec { use crate::config::{ - rules::{AllFormula, AnyFormula, LogicFormula::*, PatternMatch}, EntityLocationFilter, + rules::{AllFormula, AnyFormula, LogicFormula::*, PatternMatch}, }; fn def_path_pattern(pattern: &str) -> EntityLocationFilter { @@ -151,6 +150,7 @@ fn find_inheritable_first_filtered<'tcx>( /// If the attribute is not found, or the argument passed to the attribute is invalid /// returns `None`. fn opt_instrument_attr<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option { + use rustc_hir::{AttrArgs, AttrKind}; // Avoid possibly problematic const items. // See https://github.com/rust-lang/rust/issues/128145 if matches!( @@ -160,17 +160,19 @@ fn opt_instrument_attr<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option { return None; } - tcx.get_attrs_by_path( - def_id, - &[Symbol::intern(TOOL_NAME), Symbol::intern(ATTR_NAME)], - ) + tcx.get_attrs_by_path(def_id, &[ + Symbol::intern(TOOL_NAME), + Symbol::intern(ATTR_NAME), + ]) .next() .and_then(|attr| match &attr.kind { - rustc_ast::AttrKind::Normal(attr) => Some(attr), + AttrKind::Normal(attr) => Some(attr), _ => None, }) - .map(|attr| attr.item.args.inner_tokens()) - .map(|t| t.into_trees().next_ref().cloned()) + .and_then(|attr| match &attr.args { + AttrArgs::Delimited(delim_args) => Some(delim_args.tokens.iter().next().cloned()), + AttrArgs::Empty | AttrArgs::Eq { .. } => None, + }) .and_then(|token| { match token { // No argument means it's enabled. @@ -249,6 +251,7 @@ mod intrinsics { Atomic(AtomicOrdering, AtomicIntrinsicKind), NoOp, ConstEvaluated, + Contract, ToDo, NotPlanned, Unsupported, @@ -280,7 +283,6 @@ mod intrinsics { ptr_metadata, discriminant_value, offset, - float_to_int_unchecked, min_align_of, add_with_overflow, sub_with_overflow, @@ -316,7 +318,9 @@ mod intrinsics { pref_align_of, needs_drop, min_align_of_val, + // FIXME: These two are probably not intrinsics anymore. likely, + unlikely, forget, const_allocate, const_eval_select, @@ -325,15 +329,21 @@ mod intrinsics { assert_zero_valid, assert_mem_uninitialized_valid, assume, + // contract_checks, ) }; } + macro_rules! of_contract_funcs { + ($macro:ident) => { + $macro!(contract_check_requires, contract_check_ensures,) + }; + } + macro_rules! of_noop_funcs { ($macro:ident) => { $macro!( unreachable, - unlikely, rustc_peek, prefetch_write_instruction, prefetch_read_instruction, @@ -343,6 +353,7 @@ mod intrinsics { breakpoint, black_box, assert_inhabited, + cold_path, ) }; } @@ -350,10 +361,10 @@ mod intrinsics { macro_rules! of_float_arith_funcs { ($macro:ident) => { $macro!( + truncf16, + truncf32, truncf64, truncf128, - truncf32, - truncf16, sqrtf128, sqrtf64, sqrtf16, @@ -412,6 +423,10 @@ mod intrinsics { fsub_algebraic, fmul_algebraic, fmul_fast, + fmuladdf16, + fmuladdf32, + fmuladdf64, + fmuladdf128, fmaf128, fmaf64, floorf64, @@ -448,6 +463,7 @@ mod intrinsics { ceilf64, ceilf16, ceilf32, + float_to_int_unchecked, ) }; } @@ -679,7 +695,7 @@ mod intrinsics { volatile_copy_memory, unaligned_volatile_store, unaligned_volatile_load, - typed_swap, + typed_swap_nonoverlapping, select_unpredictable, raw_eq, ptr_mask, @@ -697,6 +713,7 @@ mod intrinsics { size_of_val, is_val_statically_known, arith_offset, + carrying_mul_add, ) }; } @@ -715,6 +732,7 @@ mod intrinsics { ctpop, ctlz_nonzero, ctlz, + // disjoint_bitor, ) }; } @@ -758,7 +776,7 @@ mod intrinsics { /* NTOE: This is used as a test to make sure that the list do not contain duplicates. * Do not change the count unless some intrinsics are added or removed to Rust. */ - const _ALL_INTRINSICS: [u8; 354] = [0; TOTAL_COUNT]; + const _ALL_INTRINSICS: [u8; 360] = [0; TOTAL_COUNT]; } use crate::pri_utils::sym::intrinsics as psym; @@ -774,6 +792,7 @@ mod intrinsics { match intrinsic.name { of_one_to_one_funcs!(any_of) => decide_one_to_one_intrinsic_call(intrinsic), of_noop_funcs!(any_of) => IntrinsicDecision::NoOp, + // of_contract_funcs!(any_of) => IntrinsicDecision::Contract, of_const_evaluated_funcs!(any_of) => IntrinsicDecision::ConstEvaluated, of_to_be_supported_funcs!(any_of) => IntrinsicDecision::ToDo, of_float_arith_funcs!(any_of) => IntrinsicDecision::NotPlanned, @@ -862,15 +881,15 @@ mod intrinsics { } } } -pub(super) use intrinsics::{decide_intrinsic_call, AtomicIntrinsicKind, IntrinsicDecision}; +pub(super) use intrinsics::{AtomicIntrinsicKind, IntrinsicDecision, decide_intrinsic_call}; mod rules { use std::ops::DerefMut; use crate::{ config::{ - rules::LogicFormula, CrateFilter, EntityFilter, EntityLocationFilter, - InstrumentationRules, MethodDynDefinitionFilter, WholeBodyFilter, + CrateFilter, EntityFilter, EntityLocationFilter, InstrumentationRules, + MethodDynDefinitionFilter, WholeBodyFilter, rules::LogicFormula, }, passes::StorageExt, utils::rules::{Predicate, ToPredicate}, diff --git a/compiler/src/passes/instr/mod.rs b/compiler/src/passes/instr/mod.rs index 2272267..8c7069f 100644 --- a/compiler/src/passes/instr/mod.rs +++ b/compiler/src/passes/instr/mod.rs @@ -6,13 +6,13 @@ use const_format::concatcp; use rustc_index::IndexVec; use rustc_middle::{ mir::{ - self, visit::Visitor, BasicBlock, BasicBlockData, Body, BorrowKind, CastKind, - HasLocalDecls, Location, MirSource, Operand, Place, Rvalue, SourceInfo, Statement, - TerminatorKind, UnwindAction, + self, BasicBlock, BasicBlockData, Body, BorrowKind, CastKind, HasLocalDecls, Location, + MirSource, Operand, Place, Rvalue, SourceInfo, Statement, TerminatorKind, UnwindAction, + visit::Visitor, }, ty::{IntrinsicDef, TyCtxt}, }; -use rustc_span::{def_id::DefId, source_map::Spanned, Span}; +use rustc_span::{Span, def_id::DefId, source_map::Spanned}; use rustc_target::abi::{FieldIdx, VariantIdx}; use common::{log_debug, log_info, log_warn}; @@ -21,7 +21,7 @@ use std::{collections::HashSet, num::NonZeroUsize, sync::atomic}; use crate::{ config::InstrumentationRules, mir_transform::{self, BodyInstrumentationUnit, JumpTargetModifier}, - passes::{instr::call::context::PriItems, StorageExt}, + passes::{StorageExt, instr::call::context::PriItems}, utils::mir::TyCtxtExt, visit::*, }; @@ -29,14 +29,15 @@ use crate::{ use super::{CompilationPass, OverrideFlags, Storage}; use call::{ + AssertionHandler, Assigner, AtomicIntrinsicHandler, BranchingHandler, BranchingReferencer, + CastAssigner, EntryFunctionHandler, FunctionHandler, + InsertionLocation::*, + IntrinsicHandler, OperandRef, OperandReferencer, PlaceReferencer, RuntimeCallAdder, context::{ AtLocationContext, BlockIndexProvider, PriItemsProvider, SourceInfoProvider, TyContextProvider, }, - ctxtreqs, AssertionHandler, Assigner, AtomicIntrinsicHandler, BranchingHandler, - BranchingReferencer, CastAssigner, EntryFunctionHandler, FunctionHandler, - InsertionLocation::*, - IntrinsicHandler, OperandRef, OperandReferencer, PlaceReferencer, RuntimeCallAdder, + ctxtreqs, }; const TAG_INSTRUMENTATION: &str = "instrumentation"; @@ -546,6 +547,7 @@ where fn visit_inline_asm( &mut self, + _asm_macro: &mir::InlineAsmMacro, _template: &[rustc_ast::InlineAsmTemplatePiece], _operands: &[mir::InlineAsmOperand<'tcx>], _options: &rustc_ast::InlineAsmOptions, @@ -591,7 +593,7 @@ where Atomic(ordering, kind) => { self.instrument_atomic_intrinsic_call(¶ms, ordering, kind); } - NoOp | ConstEvaluated => { + NoOp | ConstEvaluated | Contract => { // Currently, no instrumentation Default::default() } @@ -758,9 +760,10 @@ where self.call_adder.by_thread_local_ref(def_id); } - fn visit_raw_ptr(&mut self, mutability: &rustc_ast::Mutability, place: &Place<'tcx>) { + fn visit_raw_ptr(&mut self, kind: &mir::RawPtrKind, place: &Place<'tcx>) { let place_ref = self.call_adder.reference_place(place); - self.call_adder.by_raw_ptr(place_ref, mutability.is_mut()); + self.call_adder + .by_raw_ptr(place_ref, kind.to_mutbl_lossy().is_mut()); } fn visit_len(&mut self, place: &Place<'tcx>) { @@ -780,7 +783,7 @@ where match kind { IntToInt | FloatToInt => call_adder.to_int(*ty), IntToFloat | FloatToFloat => call_adder.to_float(*ty), - PointerCoercion(coercion) => { + PointerCoercion(coercion, _source) => { use rustc_middle::ty::adjustment::PointerCoercion::*; match coercion { Unsize => call_adder.through_unsizing(), @@ -797,12 +800,12 @@ where )); call_adder.to_another_ptr(*ty, *kind) } + DynStar => call_adder.through_sized_dynamization(*ty), } } PointerExposeProvenance => call_adder.expose_prov(), PointerWithExposedProvenance => call_adder.with_exposed_prov(*ty), PtrToPtr | FnPtrToPtr => call_adder.to_another_ptr(*ty, *kind), - DynStar => call_adder.through_sized_dynamization(*ty), Transmute => call_adder.transmuted(*ty), } } diff --git a/compiler/src/passes/logger.rs b/compiler/src/passes/logger.rs index 83b389c..63881c2 100644 --- a/compiler/src/passes/logger.rs +++ b/compiler/src/passes/logger.rs @@ -144,8 +144,18 @@ where } fn get_mir_pretty<'tcx>(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) -> String { + use mir::pretty::{PrettyPrintMirOptions, write_mir_fn}; let mut buffer = Vec::new(); - mir::pretty::write_mir_fn(tcx, body, &mut |_, _| Ok(()), &mut buffer).unwrap(); + write_mir_fn( + tcx, + body, + &mut |_, _| Ok(()), + &mut buffer, + PrettyPrintMirOptions { + include_extra_comments: false, + }, + ) + .unwrap(); String::from_utf8(buffer).unwrap() } diff --git a/compiler/src/passes/mod.rs b/compiler/src/passes/mod.rs index 8e52ae0..0875e9c 100644 --- a/compiler/src/passes/mod.rs +++ b/compiler/src/passes/mod.rs @@ -12,7 +12,7 @@ use std::sync::{Arc, Mutex}; use rustc_ast as ast; use rustc_driver::{self as driver, Compilation}; -use rustc_interface::{interface, Queries}; +use rustc_interface::interface; use rustc_middle::{mir, ty as mir_ty}; use rustc_session::Session; @@ -28,7 +28,6 @@ pub(crate) use logger::CompilationPassLogExt; #[allow(unused)] pub(crate) use noop::NoOpPass; pub(crate) use noop::OverrideFlagsForcePass; -pub(crate) use runtime_adder::LeafToolAdder; pub(crate) use runtime_adder::RuntimeExternCrateAdder; pub(crate) use tyexp::TypeExporter; @@ -195,12 +194,12 @@ pub(crate) trait StorageExt { mod implementation { use super::*; - use mir::mono::CodegenUnit; + use mir::mono::{CodegenUnit, MonoItemPartitions}; use mir_ty::TyCtxt; use rustc_driver::Compilation; use rustc_hir::def_id::DefId; use rustc_middle::query::TyCtxtAt; - use rustc_span::def_id::LocalDefId; + use rustc_span::{Symbol, def_id::LocalDefId}; use std::cell::Cell; type RRef = std::rc::Rc>; @@ -270,10 +269,10 @@ mod implementation { Option, > = Cell::new(None); static ORIGINAL_OPTIMIZED_MIR: Cell< - for<'tcx> fn(TyCtxt<'tcx>, LocalDefId) -> &mir::Body<'tcx> + for<'tcx> fn(TyCtxt<'tcx>, LocalDefId) -> &'tcx mir::Body<'tcx> > = Cell::new(|_, _| unreachable!()); static ORIGINAL_EXTERN_OPTIMIZED_MIR: Cell< - for<'tcx> fn(TyCtxt<'tcx>, DefId) -> &mir::Body<'tcx> + for<'tcx> fn(TyCtxt<'tcx>, DefId) -> &'tcx mir::Body<'tcx> > = Cell::new(|_, _| unreachable!()); static ORIGINAL_MIR_SHIMS: Cell< for<'tcx> fn(TyCtxt<'tcx>, mir_ty::InstanceKind<'tcx>) -> mir::Body<'tcx> @@ -282,8 +281,11 @@ mod implementation { for<'tcx> fn(TyCtxtAt<'tcx>, mir_ty::Instance<'tcx>) -> bool > = Cell::new(|_, _| unreachable!()); static ORIGINAL_COLLECT_PARTITION: Cell< - for<'tcx> fn(TyCtxt<'tcx>, ()) -> (&rustc_data_structures::unord::UnordSet, &[CodegenUnit]) + for<'tcx> fn(TyCtxt<'tcx>, ()) -> MonoItemPartitions<'tcx> > = Cell::new(|_, _| unreachable!()); + static ORIGINAL_REGISTERED_TOOLS: Cell< + for <'tcx> fn(TyCtxt<'tcx>, ()) -> mir_ty::RegisteredTools + > = Cell::new(|_,_| unreachable!()); } struct PassHolder(Arc>); @@ -390,6 +392,11 @@ mod implementation { providers.collect_and_partition_mono_items = Self::collect_and_partition_mono_items; } + + { + ORIGINAL_REGISTERED_TOOLS.set(providers.registered_tools); + providers.registered_tools = Self::registered_tools; + } }, ); @@ -410,18 +417,12 @@ mod implementation { fn after_crate_root_parsing<'tcx>( &mut self, compiler: &interface::Compiler, - queries: &'tcx Queries<'tcx>, + krate: &mut ast::Crate, ) -> Compilation { - let mut ast_steal = queries.parse().unwrap(); - let mut pass = self.pass.acquire(); - stop_if_stop!(pass.visit_ast_before(&ast_steal.borrow(), &mut global::get_storage())); - pass.transform_ast( - &compiler.sess, - ast_steal.get_mut(), - &mut global::get_storage(), - ); - stop_if_stop!(pass.visit_ast_after(&ast_steal.borrow(), &mut global::get_storage())); + stop_if_stop!(pass.visit_ast_before(krate, &mut global::get_storage())); + pass.transform_ast(&compiler.sess, krate, &mut global::get_storage()); + stop_if_stop!(pass.visit_ast_after(krate, &mut global::get_storage())); Compilation::Continue } @@ -429,7 +430,7 @@ mod implementation { fn after_expansion<'tcx>( &mut self, _compiler: &interface::Compiler, - _queries: &'tcx Queries<'tcx>, + _tcx: TyCtxt<'tcx>, ) -> Compilation { Compilation::Continue } @@ -437,13 +438,11 @@ mod implementation { fn after_analysis<'tcx>( &mut self, _compiler: &interface::Compiler, - queries: &'tcx Queries<'tcx>, + tcx: TyCtxt<'tcx>, ) -> Compilation { - queries.global_ctxt().unwrap().enter(global::set_ctxt_id); - queries.global_ctxt().unwrap().enter(|tcx| { - let mut pass = self.pass.acquire(); - pass.visit_tcx_after_analysis(tcx, &mut global::get_storage()) - }) + global::set_ctxt_id(tcx); + let mut pass = self.pass.acquire(); + pass.visit_tcx_after_analysis(tcx, &mut global::get_storage()) } } @@ -493,13 +492,7 @@ mod implementation { body } - fn collect_and_partition_mono_items( - tcx: TyCtxt, - _: (), - ) -> ( - &rustc_data_structures::unord::UnordSet, - &[CodegenUnit], - ) { + fn collect_and_partition_mono_items(tcx: TyCtxt, _: ()) -> MonoItemPartitions { fn clone_cgu<'tcx>(cgu: &CodegenUnit<'tcx>) -> CodegenUnit<'tcx> { let mut new_cgu = CodegenUnit::new(cgu.name().clone()); new_cgu.items_mut().extend(cgu.items().clone()); @@ -514,10 +507,31 @@ mod implementation { } global::set_ctxt_id(tcx); - let (items, units) = ORIGINAL_COLLECT_PARTITION.get()(tcx, ()); - let mut units = units.iter().map(clone_cgu).collect::>(); + let MonoItemPartitions { + codegen_units, + all_mono_items, + } = ORIGINAL_COLLECT_PARTITION.get()(tcx, ()); + let mut units = codegen_units.iter().map(clone_cgu).collect::>(); T::visit_codegen_units(tcx, &mut units, &mut global::get_storage()); - (items, tcx.arena.alloc_from_iter(units)) + MonoItemPartitions { + codegen_units: tcx.arena.alloc_from_iter(units), + all_mono_items, + } + } + + fn registered_tools(tcx: TyCtxt, _: ()) -> mir_ty::RegisteredTools { + // FIXME: Make it configurable + const TOOL_NAME: &str = crate::constants::TOOL_LEAF; + + let mut tools = ORIGINAL_REGISTERED_TOOLS.get()(tcx, ()).clone(); + + // #![register_tool(leaf_attr)] + tools.insert(rustc_span::Ident { + name: Symbol::intern(TOOL_NAME), + span: rustc_span::DUMMY_SP, + }); + + tools } } @@ -660,16 +674,16 @@ mod implementation { */ use super::*; - use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults}; + use rustc_codegen_ssa::{CodegenResults, traits::CodegenBackend}; use rustc_data_structures::fx::FxIndexMap; - use rustc_metadata::{creader::MetadataLoaderDyn, EncodedMetadata}; + use rustc_metadata::{EncodedMetadata, creader::MetadataLoaderDyn}; use rustc_middle::util::Providers; use rustc_query_system::dep_graph::{WorkProduct, WorkProductId}; use rustc_session::{ - config::{self, OutputFilenames, PrintRequest}, Session, + config::{self, OutputFilenames, PrintRequest}, }; - use rustc_span::{ErrorGuaranteed, Symbol}; + use rustc_span::Symbol; use delegate::delegate; @@ -685,7 +699,7 @@ mod implementation { fn init(&self, sess: &Session); fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session); - fn target_features(&self, sess: &Session, allow_unstable: bool) -> Vec; + fn target_features_cfg(&self, sess: &Session, allow_unstable: bool) -> Vec; fn print_passes(&self); fn print_version(&self); @@ -705,7 +719,7 @@ mod implementation { sess: &Session, codegen_results: CodegenResults, outputs: &OutputFilenames, - ) -> Result<(), ErrorGuaranteed>; + ); fn supports_parallel(&self) -> bool; } @@ -739,7 +753,7 @@ mod implementation { let early_dcx = rustc_session::EarlyDiagCtxt::new(opts.error_format); let sysroot = rustc_session::filesearch::materialize_sysroot(opts.maybe_sysroot.clone()); - let target = config::build_target_config(&early_dcx, opts, &sysroot); + let target = config::build_target_config(&early_dcx, &opts.target_triple, &sysroot); let backend = rustc_interface::util::get_codegen_backend( &early_dcx, &sysroot, @@ -853,7 +867,11 @@ mod implementation { } impl StorageExt for S { - type MutAccessor<'a, T> = DowncastValueBorrow<'a, T> where Self: 'a, T: 'a; + type MutAccessor<'a, T> + = DowncastValueBorrow<'a, T> + where + Self: 'a, + T: 'a; type ManualBorrow = ManualBorrow; fn get_or_insert_with_acc<'a, V: Any>( diff --git a/compiler/src/passes/runtime_adder.rs b/compiler/src/passes/runtime_adder.rs index d1c8a16..7e4da2e 100644 --- a/compiler/src/passes/runtime_adder.rs +++ b/compiler/src/passes/runtime_adder.rs @@ -1,9 +1,8 @@ -use rustc_ast::{ast, attr, ptr::P, Item, ItemKind, Visibility, VisibilityKind, DUMMY_NODE_ID}; +use rustc_ast::{DUMMY_NODE_ID, Item, ItemKind, Visibility, VisibilityKind, ptr::P}; use rustc_session::Session; use rustc_span::{ - sym, - symbol::{Ident, Symbol}, DUMMY_SP, + symbol::{Ident, Symbol}, }; use crate::pri_utils::sym::RUNTIME_LIB_CRATE; @@ -67,40 +66,3 @@ impl CompilationPass for RuntimeExternCrateAdder { ); } } - -// FIXME: Make it configurable -const TOOL_NAME: &str = crate::constants::TOOL_LEAF; - -#[derive(Debug, Default)] -pub(crate) struct LeafToolAdder; - -impl CompilationPass for LeafToolAdder { - fn transform_ast( - &mut self, - session: &Session, - krate: &mut rustc_ast::Crate, - _storage: &mut dyn super::Storage, - ) { - // #![feature(register_tool)] - let generator = &session.psess.attr_id_generator; - krate.attrs.push(attr::mk_attr_nested_word( - &generator, - ast::AttrStyle::Inner, - ast::Safety::Default, - sym::feature, - sym::register_tool, - DUMMY_SP, - )); - // #![register_tool(leaf)] - krate.attrs.push(attr::mk_attr_nested_word( - generator, - ast::AttrStyle::Inner, - ast::Safety::Default, - sym::register_tool, - Symbol::intern(TOOL_NAME), - DUMMY_SP, - )); - - log_info!("Added tool registration attributes to the crate."); - } -} diff --git a/compiler/src/passes/tyexp.rs b/compiler/src/passes/tyexp.rs index b3e53d9..1ecbe0a 100644 --- a/compiler/src/passes/tyexp.rs +++ b/compiler/src/passes/tyexp.rs @@ -1,11 +1,12 @@ use super::{CompilationPass, Storage, StorageExt}; -use rustc_abi::{FieldsShape, LayoutS, Scalar, TagEncoding, Variants}; +use rustc_abi::{FieldsShape, LayoutData, Scalar, TagEncoding, Variants}; use rustc_middle::mir::{self, visit::Visitor}; -use rustc_middle::ty::EarlyBinder; +use rustc_middle::ty::layout::HasTypingEnv; +use rustc_middle::ty::{EarlyBinder, TypingEnv}; use rustc_middle::ty::{ - layout::{HasParamEnv, HasTyCtxt, LayoutCx, TyAndLayout}, - GenericArgsRef, ParamEnv, Ty, TyCtxt, TyKind, + GenericArgsRef, Ty, TyCtxt, TyKind, + layout::{HasTyCtxt, LayoutCx, TyAndLayout}, }; use rustc_target::abi::{FieldIdx, Layout, VariantIdx}; @@ -81,7 +82,7 @@ fn capture_all_types<'s>( let mut type_map = storage.get_or_default::>(KEY_TYPE_MAP.to_owned()); tcx.collect_and_partition_mono_items(()) - .1 + .codegen_units .iter() .for_each(|unit| { unit.items().iter().for_each(|(item, _)| match item { @@ -92,7 +93,7 @@ fn capture_all_types<'s>( tcx, type_map: &mut type_map, args: instance.args, - param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()), + typing_env: TypingEnv::post_analysis(tcx, body.source.def_id()), local_decls: &body.local_decls, }; place_visitor.visit_body(body); @@ -102,7 +103,7 @@ fn capture_all_types<'s>( }); for ty in CoreTypes::from(get_core_types(tcx)).as_ref() { - add_type_information_to_map(&mut type_map, tcx, *ty, ParamEnv::empty()); + add_type_information_to_map(&mut type_map, tcx, *ty, TypingEnv::fully_monomorphized()); } type_map @@ -138,9 +139,9 @@ fn add_type_information_to_map<'tcx>( type_map: &mut HashMap, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, ) { - let layout = match tcx.layout_of(param_env.and(ty)) { + let layout = match tcx.layout_of(typing_env.as_query_input(ty)) { Ok(TyAndLayout { layout, .. }) => layout, Err(err) => { log_warn!("Failed to get layout of type {:?}: {:?}", ty, err); @@ -148,7 +149,7 @@ fn add_type_information_to_map<'tcx>( } }; log_debug!(target: TAG_TYPE_EXPORT, "Generating type information for {:?}", ty); - let cx = LayoutCx { tcx, param_env }; + let cx = LayoutCx::new(tcx, typing_env); let type_info: TypeInfo = layout.to_runtime(&cx, ty); type_map.insert(type_info.id, type_info); } @@ -180,7 +181,7 @@ struct PlaceVisitor<'tcx, 's, 'b> { tcx: TyCtxt<'tcx>, type_map: &'s mut HashMap, args: GenericArgsRef<'tcx>, - param_env: ParamEnv<'tcx>, + typing_env: TypingEnv<'tcx>, local_decls: &'b mir::LocalDecls<'tcx>, } @@ -188,7 +189,7 @@ impl<'tcx, 's, 'b> Visitor<'tcx> for PlaceVisitor<'tcx, 's, 'b> { fn visit_ty(&mut self, ty: Ty<'tcx>, context: mir::visit::TyContext) { let normalized_ty = self.tcx.instantiate_and_normalize_erasing_regions( self.args, - self.param_env, + self.typing_env, EarlyBinder::bind(ty), ); if normalized_ty != ty { @@ -202,7 +203,7 @@ impl<'tcx, 's, 'b> Visitor<'tcx> for PlaceVisitor<'tcx, 's, 'b> { return; } - add_type_information_to_map(self.type_map, self.tcx, normalized_ty, self.param_env); + add_type_information_to_map(self.type_map, self.tcx, normalized_ty, self.typing_env); // For pointee ty.builtin_deref(true) @@ -238,7 +239,7 @@ trait ToRuntimeInfo<'tcx, Cx, T> { impl<'tcx, Cx> ToRuntimeInfo<'tcx, Cx, TypeInfo> for Layout<'tcx> where - Cx: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, + Cx: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>, { type Def = Ty<'tcx>; @@ -258,6 +259,7 @@ where }; let (variants, tag) = match &self.variants { + Variants::Empty => (vec![], None), Variants::Single { .. } => (vec![self.0.to_runtime(cx, ty_layout)], None), Variants::Multiple { variants, @@ -286,9 +288,9 @@ where } } -impl<'tcx, Cx> ToRuntimeInfo<'tcx, Cx, VariantInfo> for &LayoutS +impl<'tcx, Cx> ToRuntimeInfo<'tcx, Cx, VariantInfo> for &LayoutData where - Cx: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, + Cx: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>, { type Def = TyAndLayout<'tcx>; @@ -298,7 +300,9 @@ where { let index = match self.variants { Variants::Single { index } => index, - Variants::Multiple { .. } => panic!("Recursive variants are not expected"), + Variants::Empty | Variants::Multiple { .. } => { + unreachable!("Empty and recursive variants are not expected") + } }; VariantInfo { @@ -310,7 +314,7 @@ where impl<'tcx, Cx> ToRuntimeInfo<'tcx, Cx, TagInfo> for (&Scalar, &TagEncoding, &usize) where - Cx: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, + Cx: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>, { type Def = TyAndLayout<'tcx>; @@ -353,7 +357,7 @@ impl<'tcx, Cx> ToRuntimeInfo<'tcx, Cx, TagEncodingInfo> for &TagEncoding ToRuntimeInfo<'tcx, Cx, FieldsShapeInfo> for &FieldsShape where - Cx: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, + Cx: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>, { type Def = TyAndLayout<'tcx>; @@ -389,7 +393,7 @@ where fn to_field_info<'tcx, Cx>(ty_layout: TyAndLayout<'tcx>, cx: &Cx, index: FieldIdx) -> FieldInfo where - Cx: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, + Cx: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>, { let ty = field_ty(ty_layout, cx, index); FieldInfo { @@ -400,7 +404,7 @@ where fn field_ty<'tcx, Cx>(ty_layout: TyAndLayout<'tcx>, cx: &Cx, index: FieldIdx) -> Ty<'tcx> where - Cx: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, + Cx: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>, { /* NOTE: Guarantee on functionality correctness. * This method is obtained by checking the compiler's source code. diff --git a/compiler/src/pri_utils.rs b/compiler/src/pri_utils.rs index f1fee5d..08e03ed 100644 --- a/compiler/src/pri_utils.rs +++ b/compiler/src/pri_utils.rs @@ -19,6 +19,7 @@ pub mod sym { pub struct LeafSymbol(&'static str); use const_format::concatcp; + use LeafSymbol as LS; pub const CORE_LIB_CRATE: LS = LS("core"); diff --git a/compiler/src/utils.rs b/compiler/src/utils.rs index 9396830..a5966ce 100644 --- a/compiler/src/utils.rs +++ b/compiler/src/utils.rs @@ -26,13 +26,14 @@ macro_rules! chain { pub(crate) use chain; pub(crate) mod mir { - use rustc_hir::definitions::DisambiguatedDefPathData; - use rustc_middle::ty::TyCtxt; - use rustc_span::def_id::DefId; + use rustc_hir::{def::DefKind, definitions::DisambiguatedDefPathData}; + use rustc_middle::ty::{TyCtxt, TypingMode}; + use rustc_span::def_id::{DefId, LocalDefId}; pub(crate) trait TyCtxtExt<'tcx> { fn is_llvm_intrinsic(self, def_id: DefId) -> bool; fn module_of(self, def_id: DefId) -> impl Iterator; + fn typing_mode_for_body(self, def_id: LocalDefId) -> TypingMode<'tcx>; } impl<'tcx> TyCtxtExt<'tcx> for TyCtxt<'tcx> { @@ -52,6 +53,50 @@ pub(crate) mod mir { .into_iter() .take_while(|p| matches!(p.data, DefPathData::TypeNs(_))) } + + // A safe wrapper around `opaque_types_defined_by` + fn typing_mode_for_body(self, item: LocalDefId) -> TypingMode<'tcx> { + let kind = self.def_kind(item); + match kind { + DefKind::AssocFn + | DefKind::Fn + | DefKind::Static { .. } + | DefKind::Const + | DefKind::AssocConst + | DefKind::AnonConst + | DefKind::Closure + | DefKind::InlineConst => { + if self.hir().maybe_body_owned_by(item).is_some() { + TypingMode::analysis_in_body(self, item) + } else { + TypingMode::non_body_analysis() + } + } + DefKind::OpaqueTy + | DefKind::TyAlias + | DefKind::AssocTy + | DefKind::Mod + | DefKind::Struct + | DefKind::Union + | DefKind::Enum + | DefKind::Variant + | DefKind::Trait + | DefKind::ForeignTy + | DefKind::TraitAlias + | DefKind::TyParam + | DefKind::ConstParam + | DefKind::Ctor(_, _) + | DefKind::Macro(_) + | DefKind::ExternCrate + | DefKind::Use + | DefKind::ForeignMod + | DefKind::Field + | DefKind::LifetimeParam + | DefKind::GlobalAsm + | DefKind::Impl { .. } + | DefKind::SyntheticCoroutineBody => TypingMode::non_body_analysis(), + } + } } } diff --git a/compiler/src/visit.rs b/compiler/src/visit.rs index a257147..69113f2 100644 --- a/compiler/src/visit.rs +++ b/compiler/src/visit.rs @@ -2,14 +2,15 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability}; use rustc_index::IndexVec; use rustc_middle::{ mir::{ - coverage::CoverageKind, AggregateKind, AssertMessage, BasicBlock, BinOp, BorrowKind, - CallSource, CastKind, FakeReadCause, InlineAsmOperand, Local, NonDivergingIntrinsic, - NullOp, Operand, Place, RetagKind, Rvalue, StatementKind, SwitchTargets, TerminatorKind, - UnOp, UnwindAction, UnwindTerminateReason, UserTypeProjection, + AggregateKind, AssertMessage, BackwardIncompatibleDropReason, BasicBlock, BinOp, + BorrowKind, CallSource, CastKind, FakeReadCause, InlineAsmMacro, InlineAsmOperand, Local, + NonDivergingIntrinsic, NullOp, Operand, Place, RawPtrKind, RetagKind, Rvalue, + StatementKind, SwitchTargets, TerminatorKind, UnOp, UnwindAction, UnwindTerminateReason, + UserTypeProjection, coverage::CoverageKind, }, ty::{Const, Region, Ty, Variance}, }; -use rustc_span::{source_map::Spanned, Span}; +use rustc_span::{Span, source_map::Spanned}; use rustc_target::abi::FieldIdx; use rustc_target::abi::VariantIdx; @@ -82,6 +83,14 @@ macro_rules! make_statement_kind_visitor { Default::default() } + fn visit_backward_incompatible_drop_hint( + &mut self, + place: & $($mutability)? Place<'tcx>, + reason: & $($mutability)? BackwardIncompatibleDropReason + ) -> T { + Default::default() + } + fn super_statement_kind(&mut self, kind: & $($mutability)? StatementKind<'tcx>) -> T { match kind { StatementKind::Assign(box (place, rvalue)) => self.visit_assign(place, rvalue), @@ -104,6 +113,10 @@ macro_rules! make_statement_kind_visitor { StatementKind::Intrinsic(intrinsic) => self.visit_intrinsic(intrinsic), StatementKind::ConstEvalCounter => self.visit_const_eval_counter(), StatementKind::Nop => self.visit_nop(), + StatementKind::BackwardIncompatibleDropHint { + place, + reason + } => self.visit_backward_incompatible_drop_hint(place, reason), } } } @@ -229,6 +242,7 @@ macro_rules! make_terminator_kind_visitor { fn visit_inline_asm( &mut self, + asm_macro: & $($mutability)? InlineAsmMacro, template: &'tcx [InlineAsmTemplatePiece], operands: & $($mutability)? [InlineAsmOperand<'tcx>], options: & $($mutability)? InlineAsmOptions, @@ -301,6 +315,7 @@ macro_rules! make_terminator_kind_visitor { ref $($mutability)? unwind, } => self.visit_false_unwind(real_target, unwind), TerminatorKind::InlineAsm { + ref $($mutability)? asm_macro, ref template, ref $($mutability)? operands, ref $($mutability)? options, @@ -308,6 +323,7 @@ macro_rules! make_terminator_kind_visitor { ref $($mutability)? targets, ref $($mutability)? unwind, } => self.visit_inline_asm( + asm_macro, template, operands, options, @@ -358,7 +374,7 @@ macro_rules! make_rvalue_visitor { fn visit_raw_ptr( &mut self, - mutability: & $($mutability)? Mutability, + kind: & $($mutability)? RawPtrKind, place: & $($mutability)? Place<'tcx>, ) -> T { Default::default() @@ -425,9 +441,7 @@ macro_rules! make_rvalue_visitor { self.visit_ref(region, borrow_kind, place) } Rvalue::ThreadLocalRef(def_id) => self.visit_thread_local_ref(def_id), - Rvalue::RawPtr(mutability, place) => { - self.visit_raw_ptr(mutability, place) - } + Rvalue::RawPtr(kind, place) => self.visit_raw_ptr(kind, place), Rvalue::Len(place) => self.visit_len(place), Rvalue::Cast(kind, operand, ty) => self.visit_cast(kind, operand, ty), Rvalue::BinaryOp(op, operands) => self.visit_binary_op(op, operands), diff --git a/compiler/tests/driver.rs b/compiler/tests/driver.rs index cd8172c..c7aeab1 100644 --- a/compiler/tests/driver.rs +++ b/compiler/tests/driver.rs @@ -100,11 +100,17 @@ fn test_execution_rs(fic: &str) { .current_dir(&work_dir) .env(ENV_RUST_BACKTRACE, "1") .status() - .expect("Failed to spawn and wait for the compiled binary"); + .unwrap_or_else(|e| { + panic!( + "Failed to spawn and wait for the compiled binary: {}, output available in: {}", + e.to_string(), + work_dir.display() + ) + }); assert!( execution_status.success(), - "Failed to execute {} with exit code: {}, output available in {}", + "Failed to execute {} with exit code: {}, output available in: {}", fic, execution_status.code().unwrap_or(-1), work_dir.display() diff --git a/integration/libafl/fuzzers/pure_concolic/src/main.rs b/integration/libafl/fuzzers/pure_concolic/src/main.rs index f494a4e..cf36b77 100644 --- a/integration/libafl/fuzzers/pure_concolic/src/main.rs +++ b/integration/libafl/fuzzers/pure_concolic/src/main.rs @@ -15,7 +15,7 @@ use sha2::{self, Digest, Sha256}; use libafl::{ executors::command::CommandConfigurator, prelude::*, stages::mutational::MultiMutationalStage, }; -use libafl_bolts::{current_nanos, nonzero, rands::StdRand, tuples::tuple_list, AsSlice, Named}; +use libafl_bolts::{AsSlice, Named, current_nanos, nonzero, rands::StdRand, tuples::tuple_list}; use libafl_leaf::DivergingMutator; const NAME_ORCHESTRATOR: &str = "leafo_onetime"; diff --git a/integration/libafl/lib/Cargo.toml b/integration/libafl/lib/Cargo.toml index cc75c78..d2db07d 100644 --- a/integration/libafl/lib/Cargo.toml +++ b/integration/libafl/lib/Cargo.toml @@ -7,4 +7,4 @@ edition = "2021" libafl = { workspace = true, features = ["std"] } libafl_bolts = { workspace = true } -log = { version = "0.4.22" } \ No newline at end of file +log = { version = "0.4.22" } diff --git a/integration/libafl/lib/src/mutation.rs b/integration/libafl/lib/src/mutation.rs index 2107d21..9ce84c5 100644 --- a/integration/libafl/lib/src/mutation.rs +++ b/integration/libafl/lib/src/mutation.rs @@ -5,9 +5,9 @@ use std::{ }; use libafl::{ + Error, inputs::{HasMutatorBytes, Input}, mutators::MultiMutator, - Error, }; use libafl_bolts::Named; diff --git a/integration/libafl/lib/src/stage.rs b/integration/libafl/lib/src/stage.rs index d4728c4..b9e00dc 100644 --- a/integration/libafl/lib/src/stage.rs +++ b/integration/libafl/lib/src/stage.rs @@ -1,14 +1,14 @@ use std::{borrow::Cow, marker::PhantomData, sync::mpsc, thread}; use libafl::{ + Error, Evaluator, HasNamedMetadata, corpus::Corpus, mutators::MultiMutator, stages::{ - mutational::{MutatedTransform, MutatedTransformPost}, RetryCountRestartHelper, Stage, + mutational::{MutatedTransform, MutatedTransformPost}, }, state::{HasCorpus, HasCurrentTestcase, HasRand, UsesState}, - Error, Evaluator, HasNamedMetadata, }; use libafl_bolts::Named; diff --git a/leafc_config.toml b/leafc_config.toml index b744e69..ca16511 100644 --- a/leafc_config.toml +++ b/leafc_config.toml @@ -7,5 +7,13 @@ override_sysroot = true crate_name = "leaf" search_path = "sysroot" +# The problematic recursive implementation in aho_corasick. More info: BurntSushi/aho-corasick#149 +[[instr_rules.exclude]] +entity = "dyn_def" +all = [ + { crate = { name = "aho_corasick" } } , + { def_path = '<&.* as .*Automaton>::\w+' }, +] + [internalization_rules] exclude = ["LLVMFuzzerInitialize"] diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 2234ab9..88e76a6 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -12,5 +12,5 @@ proc-macro = true ignore = "0.4" proc-macro2 = "1.0" quote = "1.0" -syn = {version = "2.0", features = ["full"]} -regex = "1.10.5" \ No newline at end of file +syn = { version = "2.0", features = ["full"] } +regex = "1.10.5" diff --git a/macros/src/lib.rs b/macros/src/lib.rs index a8ee993..ca71e59 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -2,8 +2,8 @@ use ignore::WalkBuilder; use proc_macro::TokenStream; use quote::{format_ident, quote}; use regex::Regex; -use std::path::{Path, MAIN_SEPARATOR}; -use syn::{parse_macro_input, Attribute, ImplItem, ItemFn, ItemImpl, LitStr}; +use std::path::{MAIN_SEPARATOR, Path}; +use syn::{Attribute, ImplItem, ItemFn, ItemImpl, LitStr, parse_macro_input}; #[proc_macro_attribute] pub fn gen_tests_rs(input_path: TokenStream, input_fn: TokenStream) -> TokenStream { diff --git a/orchestrator/Cargo.toml b/orchestrator/Cargo.toml index a71e298..30c0f48 100644 --- a/orchestrator/Cargo.toml +++ b/orchestrator/Cargo.toml @@ -23,4 +23,4 @@ sha2 = "0.10.8" clap = { workspace = true } derive_more = { workspace = true } glob = "0.3.1" -notify = "7.0.0" \ No newline at end of file +notify = "8.0.0" diff --git a/orchestrator/src/logging.rs b/orchestrator/src/logging.rs index dc9fed7..a6259c5 100644 --- a/orchestrator/src/logging.rs +++ b/orchestrator/src/logging.rs @@ -1,7 +1,7 @@ const LOG_ENV: &str = "LEAFO_LOG"; pub fn init_logging() { - use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; + use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt}; let env_filter = EnvFilter::builder() .with_env_var(LOG_ENV.to_string()) .from_env_lossy(); diff --git a/orchestrator/src/modes/onetime.rs b/orchestrator/src/modes/onetime.rs index 02002ff..b40e8c3 100644 --- a/orchestrator/src/modes/onetime.rs +++ b/orchestrator/src/modes/onetime.rs @@ -116,7 +116,7 @@ fn main() -> ExitCode { fn watch_diverging_inputs(dir: &Path) -> notify::RecommendedWatcher { use notify::{ - event::CreateKind, recommended_watcher, Event, EventKind, RecursiveMode, Result, Watcher, + Event, EventKind, RecursiveMode, Result, Watcher, event::CreateKind, recommended_watcher, }; use std::sync::mpsc; diff --git a/runtime/flavors/basic/Cargo.toml b/runtime/flavors/basic/Cargo.toml index f933520..46c1ee8 100644 --- a/runtime/flavors/basic/Cargo.toml +++ b/runtime/flavors/basic/Cargo.toml @@ -10,4 +10,4 @@ crate-type = ["cdylib"] [dependencies] common = { workspace = true } -runtime = { path = "../../lib" } \ No newline at end of file +runtime = { path = "../../lib" } diff --git a/runtime/flavors/basic_li/Cargo.toml b/runtime/flavors/basic_li/Cargo.toml index 13f4dff..90c1070 100644 --- a/runtime/flavors/basic_li/Cargo.toml +++ b/runtime/flavors/basic_li/Cargo.toml @@ -10,4 +10,4 @@ crate-type = ["cdylib"] [dependencies] common = { workspace = true } -runtime = { path = "../../lib" } \ No newline at end of file +runtime = { path = "../../lib" } diff --git a/runtime/flavors/noop/Cargo.toml b/runtime/flavors/noop/Cargo.toml index a9cc3f6..1e79205 100644 --- a/runtime/flavors/noop/Cargo.toml +++ b/runtime/flavors/noop/Cargo.toml @@ -10,4 +10,4 @@ crate-type = ["cdylib"] [dependencies] common = { workspace = true } -runtime = { path = "../../lib" } \ No newline at end of file +runtime = { path = "../../lib" } diff --git a/runtime/lib/src/abs/backend.rs b/runtime/lib/src/abs/backend.rs index 1fa66ab..669d07d 100644 --- a/runtime/lib/src/abs/backend.rs +++ b/runtime/lib/src/abs/backend.rs @@ -350,8 +350,10 @@ pub(crate) mod implementation { for<'a> P: 'a, { type Place = Place; - type ProjectionHandler<'a> = DefaultPlaceProjectionHandler<'a, Self::Place> - where Self::Place :'a; + type ProjectionHandler<'a> + = DefaultPlaceProjectionHandler<'a, Self::Place> + where + Self::Place: 'a; type MetadataHandler<'a> = (); fn of_local(self, local: Local) -> Self::Place { diff --git a/runtime/lib/src/abs/expr/logger.rs b/runtime/lib/src/abs/expr/logger.rs index d29b226..41950bd 100644 --- a/runtime/lib/src/abs/expr/logger.rs +++ b/runtime/lib/src/abs/expr/logger.rs @@ -7,8 +7,8 @@ use common::log_debug; use crate::abs::CastKind; use super::{ - macros::macro_rules_method_with_optional_args, BinaryExprBuilder, CastExprBuilder, - TernaryExprBuilder, UnaryExprBuilder, + BinaryExprBuilder, CastExprBuilder, TernaryExprBuilder, UnaryExprBuilder, + macros::macro_rules_method_with_optional_args, }; pub(crate) const TAG: &str = "expr_builder"; diff --git a/runtime/lib/src/abs/expr/variance.rs b/runtime/lib/src/abs/expr/variance.rs index 1cbc61c..355df28 100644 --- a/runtime/lib/src/abs/expr/variance.rs +++ b/runtime/lib/src/abs/expr/variance.rs @@ -2,8 +2,8 @@ /// that work as adapters. Most of the adapters provide non-trivial covariance and contravariance /// over the input and output types of the wrapped expression builder. use super::{ - macros::macro_rules_method_with_optional_args, BinaryExprBuilder, CastExprBuilder, - TernaryExprBuilder, UnaryExprBuilder, + BinaryExprBuilder, CastExprBuilder, TernaryExprBuilder, UnaryExprBuilder, + macros::macro_rules_method_with_optional_args, }; use crate::abs::{BinaryOp, CastKind, TernaryOp, UnaryOp}; use std::ops::DerefMut; diff --git a/runtime/lib/src/backends/basic/alias.rs b/runtime/lib/src/backends/basic/alias.rs index 40bd8ab..282435d 100644 --- a/runtime/lib/src/backends/basic/alias.rs +++ b/runtime/lib/src/backends/basic/alias.rs @@ -1,12 +1,11 @@ use super::{ - expr::{SymBinaryOperands, SymTernaryOperands, SymValueRef, ValueRef}, ConstValue, LazyTypeInfo, + expr::{SymBinaryOperands, SymTernaryOperands, SymValueRef, ValueRef}, }; use crate::abs::{ - self, + self, FloatType, IntType, TypeId, backend::*, expr::{BinaryExprBuilder, CastExprBuilder, TernaryExprBuilder, UnaryExprBuilder}, - FloatType, IntType, TypeId, }; use common::tyexp::TypeInfo; diff --git a/runtime/lib/src/backends/basic/call.rs b/runtime/lib/src/backends/basic/call.rs index 9e1954a..cd84af4 100644 --- a/runtime/lib/src/backends/basic/call.rs +++ b/runtime/lib/src/backends/basic/call.rs @@ -7,10 +7,10 @@ use crate::{ }; use super::{ - config::{CallConfig, ExternalCallStrategy}, - expr::place::DeterPlaceValueRef, CalleeDef, ConcreteValue, FuncDef, GenericCallStackManager, UntupleHelper, ValueRef, VariablesState, + config::{CallConfig, ExternalCallStrategy}, + expr::place::DeterPlaceValueRef, }; use common::{log_debug, log_warn, types::RawAddress}; @@ -518,7 +518,7 @@ mod logging { use super::*; use const_format::concatcp; - use tracing::{debug_span, Span}; + use tracing::{Span, debug_span}; pub(super) const TAG: &str = "call_manager"; const TAG_STACK: &str = concatcp!(TAG, "::stack"); diff --git a/runtime/lib/src/backends/basic/concrete.rs b/runtime/lib/src/backends/basic/concrete.rs index a23a871..14c179a 100644 --- a/runtime/lib/src/backends/basic/concrete.rs +++ b/runtime/lib/src/backends/basic/concrete.rs @@ -1,8 +1,8 @@ use crate::abs::ConstraintKind; use super::{ - alias::{RRef, ValueRefBinaryExprBuilder}, BasicTraceManager, ConcreteValueRef, Constraint, SymValueRef, + alias::{RRef, ValueRefBinaryExprBuilder}, }; use common::log_debug; diff --git a/runtime/lib/src/backends/basic/expr/builders.rs b/runtime/lib/src/backends/basic/expr/builders.rs index 2b3e7fa..4b90022 100644 --- a/runtime/lib/src/backends/basic/expr/builders.rs +++ b/runtime/lib/src/backends/basic/expr/builders.rs @@ -4,11 +4,11 @@ use super::super::alias::{ }; use super::{BinaryOp as BasicBinaryOp, UnaryOp as BasicUnaryOp, *}; use crate::abs::{ + BinaryOp as AbsBinaryOp, CastKind, TernaryOp as AbsTernaryOp, UnaryOp as AbsUnaryOp, expr::{ - macros::*, BinaryExprBuilder, CastExprBuilder, ChainedExprBuilder, CompositeExprBuilder, - LoggerExprBuilder, TernaryExprBuilder, UnaryExprBuilder, + BinaryExprBuilder, CastExprBuilder, ChainedExprBuilder, CompositeExprBuilder, + LoggerExprBuilder, TernaryExprBuilder, UnaryExprBuilder, macros::*, }, - BinaryOp as AbsBinaryOp, CastKind, TernaryOp as AbsTernaryOp, UnaryOp as AbsUnaryOp, }; use crate::utils::alias::RRef; @@ -839,21 +839,15 @@ mod core { match from_type { ValueType::Bool => Expr::Ite { condition: operand, - if_target: ConstValue::new_int( - 1 as u128, - IntType { - bit_size, - is_signed, - }, - ) + if_target: ConstValue::new_int(1 as u128, IntType { + bit_size, + is_signed, + }) .to_value_ref(), - else_target: ConstValue::new_int( - 0 as u128, - IntType { - bit_size, - is_signed, - }, - ) + else_target: ConstValue::new_int(0 as u128, IntType { + bit_size, + is_signed, + }) .to_value_ref(), } .to_value_ref(), @@ -1117,36 +1111,30 @@ mod simp { #[inline] fn is_first_unsigned_zero(&self) -> bool { - matches!( - self, - BinaryOperands::Rev { - first: ConstValue::Int { - bit_rep: Wrapping(0), - ty: IntType { - is_signed: false, - .. - } - }, - .. - } - ) + matches!(self, BinaryOperands::Rev { + first: ConstValue::Int { + bit_rep: Wrapping(0), + ty: IntType { + is_signed: false, + .. + } + }, + .. + }) } #[inline] fn is_second_unsigned_zero(&self) -> bool { - matches!( - self, - BinaryOperands::Orig { - second: ConstValue::Int { - bit_rep: Wrapping(0), - ty: IntType { - is_signed: false, - .. - } - }, - .. - } - ) + matches!(self, BinaryOperands::Orig { + second: ConstValue::Int { + bit_rep: Wrapping(0), + ty: IntType { + is_signed: false, + .. + } + }, + .. + }) } #[inline] diff --git a/runtime/lib/src/backends/basic/expr/prelude.rs b/runtime/lib/src/backends/basic/expr/prelude.rs index 960bc33..797a7db 100644 --- a/runtime/lib/src/backends/basic/expr/prelude.rs +++ b/runtime/lib/src/backends/basic/expr/prelude.rs @@ -1,10 +1,10 @@ pub(crate) use super::{ - place::{ - DeterPlaceValueRef, DeterministicPlaceValue, PlaceValue, PlaceValueRef, SymPlaceValueRef, - SymbolicPlaceValue, - }, AdtField, AdtKind, AdtValue, ArrayValue, BinaryExpr, BinaryOp, ConcreteValue, ConcreteValueRef, ConstValue, Expr, ExtensionExpr, FatPtrValue, LazyTypeInfo, MultiValue, MultiValueLeaf, MultiValueTree, PorterValue, RawAddress, RawConcreteValue, SymValue, SymValueRef, SymbolicVar, TruncationExpr, TypeId, UnaryOp, UnevalValue, Value, ValueRef, ValueType, + place::{ + DeterPlaceValueRef, DeterministicPlaceValue, PlaceValue, PlaceValueRef, SymPlaceValueRef, + SymbolicPlaceValue, + }, }; diff --git a/runtime/lib/src/backends/basic/expr/translators.rs b/runtime/lib/src/backends/basic/expr/translators.rs index b71d485..50687b3 100644 --- a/runtime/lib/src/backends/basic/expr/translators.rs +++ b/runtime/lib/src/backends/basic/expr/translators.rs @@ -9,13 +9,13 @@ pub(crate) mod z3 { }; use z3::{ - ast::{self, Ast}, Context, + ast::{self, Ast}, }; use crate::{ - abs::{expr::sym_place::SelectTarget, IntType, ValueType}, - backends::basic::expr::{prelude::*, OverflowingBinaryOp, SymBinaryOperands, SymVarId}, + abs::{IntType, ValueType, expr::sym_place::SelectTarget}, + backends::basic::expr::{OverflowingBinaryOp, SymBinaryOperands, SymVarId, prelude::*}, solvers::z3::{ArrayNode, ArraySort, AstNodeSort, BVExt, BVNode, BVSort}, }; @@ -574,12 +574,9 @@ pub(crate) mod z3 { ); } - ArrayNode( - array, - ArraySort { - range: Box::new(element_sort), - }, - ) + ArrayNode(array, ArraySort { + range: Box::new(element_sort), + }) } fn translate_multi_value_leaf(&mut self, leaf: &MultiValueLeaf) -> AstNode<'ctx> { @@ -726,13 +723,10 @@ pub(crate) mod z3 { match ast { AstNode::Bool(ast) => super::super::ConstValue::Bool(ast.as_bool().unwrap()), AstNode::BitVector(BVNode(ast, BVSort { is_signed })) => { - super::super::ConstValue::new_int( - ast.as_u128().unwrap(), - IntType { - bit_size: ast.get_size() as u64, - is_signed, - }, - ) + super::super::ConstValue::new_int(ast.as_u128().unwrap(), IntType { + bit_size: ast.get_size() as u64, + is_signed, + }) } AstNode::Array(_) => { unimplemented!("Symbolic arrays are not supported by this converter.") diff --git a/runtime/lib/src/backends/basic/mod.rs b/runtime/lib/src/backends/basic/mod.rs index 3e310ef..92c75dd 100644 --- a/runtime/lib/src/backends/basic/mod.rs +++ b/runtime/lib/src/backends/basic/mod.rs @@ -25,9 +25,9 @@ use sym_vars::SymVariablesManager; use crate::{ abs::{ - self, backend::*, place::HasMetadata, AssertKind, BasicBlockLocation, CalleeDef, CastKind, - ConstraintKind, FieldIndex, FuncDef, IntType, Local, LocalIndex, PlaceUsage, SymVariable, - Tag, TypeId, UnaryOp, VariantIndex, + self, AssertKind, BasicBlockLocation, CalleeDef, CastKind, ConstraintKind, FieldIndex, + FuncDef, IntType, Local, LocalIndex, PlaceUsage, SymVariable, Tag, TypeId, UnaryOp, + VariantIndex, backend::*, place::HasMetadata, }, tyexp::{FieldsShapeInfoExt, TypeInfoExt}, utils::alias::RRef, @@ -41,9 +41,9 @@ use self::{ }, concrete::BasicConcretizer, config::BasicBackendConfig, - expr::{prelude::*, SymVarId}, + expr::{SymVarId, prelude::*}, place::PlaceMetadata, - state::{make_sym_place_handler, RawPointerVariableState}, + state::{RawPointerVariableState, make_sym_place_handler}, types::BasicTypeManager, }; @@ -127,27 +127,33 @@ impl BasicBackend { } impl RuntimeBackend for BasicBackend { - type PlaceHandler<'a> = BasicPlaceHandler<'a> + type PlaceHandler<'a> + = BasicPlaceHandler<'a> where Self: 'a; - type OperandHandler<'a> = BasicOperandHandler<'a> + type OperandHandler<'a> + = BasicOperandHandler<'a> where Self: 'a; - type AssignmentHandler<'a> = BasicAssignmentHandler<'a, BasicExprBuilder> + type AssignmentHandler<'a> + = BasicAssignmentHandler<'a, BasicExprBuilder> where Self: 'a; - type ConstraintHandler<'a> = BasicConstraintHandler<'a, BasicExprBuilder> + type ConstraintHandler<'a> + = BasicConstraintHandler<'a, BasicExprBuilder> where Self: 'a; - type FunctionHandler<'a> = BasicFunctionHandler<'a> + type FunctionHandler<'a> + = BasicFunctionHandler<'a> where Self: 'a; - type AnnotationHandler<'a> = BasicAnnotationHandler<'a> + type AnnotationHandler<'a> + = BasicAnnotationHandler<'a> where Self: 'a; diff --git a/runtime/lib/src/backends/basic/place.rs b/runtime/lib/src/backends/basic/place.rs index 9e03182..da7cc02 100644 --- a/runtime/lib/src/backends/basic/place.rs +++ b/runtime/lib/src/backends/basic/place.rs @@ -7,15 +7,15 @@ use std::{ use common::{log_warn, types::RawAddress}; use crate::abs::{ + Local, TypeId, TypeSize, ValueType, backend::{ - implementation::{DefaultPlaceBuilder, DefaultPlaceProjectionHandler}, PlaceBuilder, PlaceProjectionHandler, + implementation::{DefaultPlaceBuilder, DefaultPlaceProjectionHandler}, }, place::HasMetadata, - Local, TypeId, TypeSize, ValueType, }; -use super::{expr::place::DeterPlaceValueRef, PlaceValueRef}; +use super::{PlaceValueRef, expr::place::DeterPlaceValueRef}; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct PlaceMetadata { diff --git a/runtime/lib/src/backends/basic/state/mod.rs b/runtime/lib/src/backends/basic/state/mod.rs index bfd2642..db8e4e8 100644 --- a/runtime/lib/src/backends/basic/state/mod.rs +++ b/runtime/lib/src/backends/basic/state/mod.rs @@ -1,7 +1,7 @@ mod pointer_based; -pub(super) use pointer_based::sym_place::strategies::make_sym_place_handler; pub(super) use pointer_based::RawPointerVariableState; +pub(super) use pointer_based::sym_place::strategies::make_sym_place_handler; use super::{ConcreteValueRef, SymValueRef}; diff --git a/runtime/lib/src/backends/basic/state/pointer_based/memory.rs b/runtime/lib/src/backends/basic/state/pointer_based/memory.rs index 8a15c6b..80f25cc 100644 --- a/runtime/lib/src/backends/basic/state/pointer_based/memory.rs +++ b/runtime/lib/src/backends/basic/state/pointer_based/memory.rs @@ -1,7 +1,7 @@ use std::{ collections::{ - btree_map::{Cursor, CursorMut, Entry}, BTreeMap, + btree_map::{Cursor, CursorMut, Entry}, }, fmt::{self, Debug, Display}, ops::{Bound, Range}, diff --git a/runtime/lib/src/backends/basic/state/pointer_based/mod.rs b/runtime/lib/src/backends/basic/state/pointer_based/mod.rs index f657d19..3167c88 100644 --- a/runtime/lib/src/backends/basic/state/pointer_based/mod.rs +++ b/runtime/lib/src/backends/basic/state/pointer_based/mod.rs @@ -8,23 +8,23 @@ use std::{ use crate::{ abs::{PlaceUsage, PointerOffset, TypeId, TypeSize}, backends::basic::{ + GenericVariablesState, alias::{SymValueRefExprBuilder, TypeManager}, config::{SymbolicPlaceConfig, SymbolicPlaceStrategy}, expr::{ lazy::RawPointerRetriever, place::{DeterministicPlaceValue, SymbolicPlaceValue}, }, - GenericVariablesState, }, tyexp::TypeInfoExt, - utils::{alias::RRef, InPlaceSelfHierarchical}, + utils::{InPlaceSelfHierarchical, alias::RRef}, }; use common::tyexp::{FieldsShapeInfo, StructShape, TypeInfo, UnionShape}; use super::super::{ + ValueRef, expr::prelude::*, place::{LocalWithMetadata, PlaceWithMetadata, Projection}, - ValueRef, }; mod memory; @@ -205,13 +205,10 @@ impl GenericVariablesState for RawPointerVariableSta #[tracing::instrument(level = "debug", skip(self))] fn ref_place(&self, place: &Place, usage: PlaceUsage) -> PlaceValueRef { - self.get_place( - place, - match usage { - PlaceUsage::Read => self.sym_read_handler.borrow_mut(), - PlaceUsage::Write => self.sym_write_handler.borrow_mut(), - }, - ) + self.get_place(place, match usage { + PlaceUsage::Read => self.sym_read_handler.borrow_mut(), + PlaceUsage::Write => self.sym_write_handler.borrow_mut(), + }) } #[tracing::instrument(level = "debug", skip(self))] @@ -221,14 +218,10 @@ impl GenericVariablesState for RawPointerVariableSta ptr_type_id: TypeId, usage: PlaceUsage, ) -> PlaceValueRef { - self.get_deref_of_ptr( - ptr, - ptr_type_id, - match usage { - PlaceUsage::Read => self.sym_read_handler.borrow_mut(), - PlaceUsage::Write => self.sym_write_handler.borrow_mut(), - }, - ) + self.get_deref_of_ptr(ptr, ptr_type_id, match usage { + PlaceUsage::Read => self.sym_read_handler.borrow_mut(), + PlaceUsage::Write => self.sym_write_handler.borrow_mut(), + }) } #[tracing::instrument(level = "debug", skip(self))] diff --git a/runtime/lib/src/backends/basic/state/pointer_based/sym_place/mod.rs b/runtime/lib/src/backends/basic/state/pointer_based/sym_place/mod.rs index 8ce7ba3..f00303d 100644 --- a/runtime/lib/src/backends/basic/state/pointer_based/sym_place/mod.rs +++ b/runtime/lib/src/backends/basic/state/pointer_based/sym_place/mod.rs @@ -11,7 +11,7 @@ use crate::{ place::HasMetadata, }, backends::basic::{ - expr::{place::*, SliceIndex}, + expr::{SliceIndex, place::*}, place::PlaceMetadata, }, }; diff --git a/runtime/lib/src/backends/basic/trace.rs b/runtime/lib/src/backends/basic/trace.rs index 7ef8d9d..fc567dc 100644 --- a/runtime/lib/src/backends/basic/trace.rs +++ b/runtime/lib/src/backends/basic/trace.rs @@ -11,23 +11,23 @@ use std::{cell::RefCell, collections::HashMap, rc::Rc}; use common::{log_debug, pri::BasicBlockLocation}; use crate::{ - abs::{backend::Model, Constraint, HasTags, Tag}, - solvers::{z3::Z3Solver, MapSolverExt}, + abs::{Constraint, HasTags, Tag, backend::Model}, + solvers::{MapSolverExt, z3::Z3Solver}, trace::{ - divergence::{DivergenceFilter, ImmediateDivergingAnswerFinder}, - sanity_check::ConstraintSanityChecker, AdapterTraceManagerExt, AggregatorTraceManager, BranchCoverageStepInspector, FilterStepInspectorExt, InspectionTraceManagerExt, LoggerTraceManagerExt, StepInspector, TraceInspector, + divergence::{DivergenceFilter, ImmediateDivergingAnswerFinder}, + sanity_check::ConstraintSanityChecker, }, utils::alias::RRef, }; use super::{ + ConstValue, Solver, SymVarId, TraceManager, ValueRef, config::{self, ExecutionTraceConfig, OutputConfig, SolverImpl, TraceInspectorType}, expr::translators::z3::Z3ValueTranslator, sym_vars::SymVariablesManager, - ConstValue, Solver, SymVarId, TraceManager, ValueRef, }; use dumping::*; @@ -227,7 +227,7 @@ mod divergence { use common::log_info; use crate::trace::divergence::{ - filter::all, BranchCoverageDepthDivergenceFilter, DepthProvider, + BranchCoverageDepthDivergenceFilter, DepthProvider, filter::all, }; use super::*; @@ -523,7 +523,7 @@ mod dumping { use std::fs; use common::pri::{BasicBlockIndex, DefId}; - use serde::{de::DeserializeOwned, Deserialize}; + use serde::{Deserialize, de::DeserializeOwned}; use crate::utils::file::{FileFormat, FileGenConfig}; diff --git a/runtime/lib/src/backends/basic/types.rs b/runtime/lib/src/backends/basic/types.rs index 69bbb1a..075a1e6 100644 --- a/runtime/lib/src/backends/basic/types.rs +++ b/runtime/lib/src/backends/basic/types.rs @@ -1,9 +1,9 @@ use std::collections::HashMap; -use common::tyexp::{pass_core_type_names_to, CoreTypes, TypeExport, TypesData}; +use common::tyexp::{CoreTypes, TypeExport, TypesData, pass_core_type_names_to}; use crate::{ - abs::{backend::TypeManager, IntType}, + abs::{IntType, backend::TypeManager}, tyexp, }; diff --git a/runtime/lib/src/pri/basic/instance.rs b/runtime/lib/src/pri/basic/instance.rs index 32aef61..f2848bd 100644 --- a/runtime/lib/src/pri/basic/instance.rs +++ b/runtime/lib/src/pri/basic/instance.rs @@ -1,11 +1,11 @@ use super::utils::{DefaultRefManager, RefManager}; use super::{OperandRef, PlaceHandler, PlaceRef, SwitchInfo}; use crate::abs::{ + BasicBlockLocation, PlaceUsage, backend::{ AssignmentHandler, ConstraintHandler, OperandHandler, PlaceBuilder, RuntimeBackend, Shutdown, }, - BasicBlockLocation, PlaceUsage, }; use crate::backends::basic::BasicPlaceBuilder; use crate::utils::UnsafeSync; diff --git a/runtime/lib/src/pri/basic/mod.rs b/runtime/lib/src/pri/basic/mod.rs index f0f58c0..a3a3ecc 100644 --- a/runtime/lib/src/pri/basic/mod.rs +++ b/runtime/lib/src/pri/basic/mod.rs @@ -6,8 +6,8 @@ use common::{log_debug, log_info, pri::*}; use self::instance::*; use crate::abs::{ - self, backend::*, AssertKind, CastKind, Constant, FloatType, IntType, Local, SymVariable, - ValueType, + self, AssertKind, CastKind, Constant, FloatType, IntType, Local, SymVariable, ValueType, + backend::*, }; use common::log_warn; use leaf_macros::trait_log_fn; diff --git a/runtime/lib/src/solvers/map.rs b/runtime/lib/src/solvers/map.rs index b9cba29..f3ba31d 100644 --- a/runtime/lib/src/solvers/map.rs +++ b/runtime/lib/src/solvers/map.rs @@ -1,8 +1,8 @@ use core::hash::Hash; use crate::abs::{ - backend::{Model, SolveResult}, Constraint, + backend::{Model, SolveResult}, }; use super::Solver; diff --git a/runtime/lib/src/solvers/z3.rs b/runtime/lib/src/solvers/z3.rs index f0a2a94..1fc8707 100644 --- a/runtime/lib/src/solvers/z3.rs +++ b/runtime/lib/src/solvers/z3.rs @@ -1,15 +1,14 @@ use derive_more as dm; use z3::{ - self, + self, Context, SatResult, Solver, ast::{self, Ast}, - Context, SatResult, Solver, }; use std::{collections::HashMap, hash::Hash}; use common::log_debug; -use crate::abs::{backend, Constraint, ConstraintKind}; +use crate::abs::{Constraint, ConstraintKind, backend}; use self::backend::SolveResult; diff --git a/runtime/lib/src/trace/divergence/mod.rs b/runtime/lib/src/trace/divergence/mod.rs index 2bb837f..d0ccdc4 100644 --- a/runtime/lib/src/trace/divergence/mod.rs +++ b/runtime/lib/src/trace/divergence/mod.rs @@ -5,7 +5,7 @@ use common::{log_debug, log_info, log_warn}; use crate::abs::backend::{SolveResult, Solver}; -use super::{inspect::TraceInspector, Constraint}; +use super::{Constraint, inspect::TraceInspector}; mod coverage; pub(crate) mod filter; diff --git a/runtime/lib/src/trace/mod.rs b/runtime/lib/src/trace/mod.rs index aa327df..abca5ac 100644 --- a/runtime/lib/src/trace/mod.rs +++ b/runtime/lib/src/trace/mod.rs @@ -1,4 +1,4 @@ -use crate::abs::{backend::TraceManager, Constraint}; +use crate::abs::{Constraint, backend::TraceManager}; mod adapt; mod agg; diff --git a/runtime/lib/src/utils/logging.rs b/runtime/lib/src/utils/logging.rs index 281252d..31a14aa 100644 --- a/runtime/lib/src/utils/logging.rs +++ b/runtime/lib/src/utils/logging.rs @@ -6,8 +6,8 @@ pub(crate) fn comma_separated(iter: impl Iterator) -> Stri } pub(crate) fn init_logging() { - use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; - use tracing_tree::{time::FormatTime, HierarchicalLayer}; + use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt}; + use tracing_tree::{HierarchicalLayer, time::FormatTime}; const ENV_LOG: &str = "LEAF_LOG"; const ENV_WRITE_STYLE: &str = "LEAF_LOG_STYLE"; diff --git a/runtime/shim/src/pri/mod.rs b/runtime/shim/src/pri/mod.rs index 795beff..9b8b948 100644 --- a/runtime/shim/src/pri/mod.rs +++ b/runtime/shim/src/pri/mod.rs @@ -66,13 +66,11 @@ mod ffi { static mut REC_GUARD: bool = false; pub(crate) fn run_rec_guarded(default: T, f: impl FnOnce() -> T) -> T { - let value = unsafe { REC_GUARD }; - let guarded = if UNLIKELY { - core::intrinsics::unlikely(value) - } else { - value - }; + let guarded = unsafe { REC_GUARD }; if guarded { + if UNLIKELY { + core::intrinsics::cold_path(); + } return default; } unsafe { @@ -99,7 +97,13 @@ macro_rules! export_to_rust_abi { * instrumented function statically, but that does not seem to be * easy to achieve. So unless we have evidence that this is significantly * affecting the performance, we will keep this solution. */ - if core::intrinsics::unlikely(unsafe { REC_GUARD }) { + /* NOTE: Be very careful about the functions you call here. + * The guard checking statement (the if condition) must not call + * any function that may possibly be instrumented. Watch out for + * intrinsics or inlineable functions that may not be optimized in + * some build configs. */ + if unsafe { REC_GUARD } { + core::intrinsics::cold_path(); return Default::default(); } unsafe { diff --git a/rust-toolchain.toml b/rust-toolchain.toml index ab0ea93..47239e0 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2024-08-28" +channel = "nightly-2025-01-30" components = ["rust-src", "rustc-dev", "llvm-tools", "rustfmt", "clippy"] diff --git a/samples/casting/dyn_star/basic.rs b/samples/casting/dyn_star/basic.rs index 749e47d..fba4951 100644 --- a/samples/casting/dyn_star/basic.rs +++ b/samples/casting/dyn_star/basic.rs @@ -12,8 +12,15 @@ impl Bar for Foo { } } +impl Bar for Box { + fn bar(&self) -> usize { + Bar::bar(self.as_ref()) + } +} + fn main() { let x = Foo(10); + let x = Box::new(x); let bar = x as dyn* Bar; foo(bar); } diff --git a/samples/casting/dyn_star/symbolic_inner.rs b/samples/casting/dyn_star/symbolic_inner.rs index f51846c..1e6eb7f 100644 --- a/samples/casting/dyn_star/symbolic_inner.rs +++ b/samples/casting/dyn_star/symbolic_inner.rs @@ -14,8 +14,15 @@ impl Bar for Foo { } } +impl Bar for Box { + fn bar(&self) -> usize { + Bar::bar(self.as_ref()) + } +} + fn main() { let x = Foo(10.mark_symbolic()); + let x = Box::new(x); let bar = x as dyn* Bar; test(bar); } diff --git a/samples/misc/leaf_attr/main.rs b/samples/misc/leaf_attr/main.rs new file mode 100644 index 0000000..5f2603a --- /dev/null +++ b/samples/misc/leaf_attr/main.rs @@ -0,0 +1,15 @@ +use leaf::annotations::*; + +fn main() { + let x: u8 = 10.mark_symbolic(); + + // No SMT solving should happen + if calc(x) < 5 { + println!("Hello, world!"); + } +} + +#[leaf_attr::instrument(false)] +fn calc(num: u8) -> u8 { + num + 5 +} diff --git a/scripts/toolchain_builder/build b/scripts/toolchain_builder/build index 3ceb9ae..4c152a5 100755 --- a/scripts/toolchain_builder/build +++ b/scripts/toolchain_builder/build @@ -328,7 +328,6 @@ def build_env_vars(toolchain_path: Path): return { **common_env_vars(), ENV_RUSTC: os.environ.get(ENV_LEAFC, default="leafc"), - ENV_LEAFC_BUILDING_CORE: "true", "RUSTUP_TOOLCHAIN": str(toolchain_path), }