Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions decompiler/crates/kuna-analysis/src/analyzers/fid/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ use crate::fid::skipper::{InstructionSkipper, X86InstructionSkipper};
/// kept out of the per-decompilation `--option` surface in v1 (a real `--fidb
/// <path>` flag is deferred, `docs/history/fid-design.md` §7.2). Absent / empty ⇒ the pass
/// is inert (no DB to match against).
pub const FID_DB_ENV: &str = "kuna_fid_db";
pub const FID_DB_ENV: &str = kuna_decomp::kuna_loadoptions::FID_DB_ENV;

/// The FID matching consumer pass — the kuna analog of Ghidra's FID identification
/// analyzer (`FidServiceImpl` over the function-id query service), the third
Expand Down Expand Up @@ -101,10 +101,10 @@ impl AnalysisPass for FidPass {
let Some(listing) = ctx.listing else {
return out;
};
let Some(path) = std::env::var_os(FID_DB_ENV).filter(|p| !p.is_empty()) else {
let Some(path) = fid_db_path() else {
return out;
};
let (report, db) = kuna_fidapply::open(std::path::Path::new(&path), ctx.arch);
let (report, db) = kuna_fidapply::open(&path, ctx.arch);
out.fid_databases.push(report);
let Some(db) = db else {
return out;
Expand All @@ -130,6 +130,13 @@ impl AnalysisPass for FidPass {
}
}

/// The `.fid` database the load names: `LoadOptions::fid_db`, else
/// [`FID_DB_ENV`]. `None` when neither names one.
fn fid_db_path() -> Option<std::path::PathBuf> {
use kuna_decomp::kuna_loadoptions::{env, scoped};
scoped(|o| o.fid_db.clone()).unwrap_or_else(env::fid_db)
}

/// Fingerprint a discovered function using the same extent and masks as the FID pass.
/// The error distinguishes an undersized function from a failed instruction mask.
pub fn fingerprint_function(
Expand Down
13 changes: 9 additions & 4 deletions decompiler/crates/kuna-analysis/src/analyzers/flirt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::pass::{AnalysisCtx, AnalysisOutput, AnalysisPass, FidMatch, Phase};
use flirt_sig::{Endian, Matcher, Module, Signature, FLAG_STARTUP};

/// The environment variable that lists the `.sig` files.
pub const FLIRT_SIGS_ENV: &str = "KUNA_FLIRT_SIGS";
pub const FLIRT_SIGS_ENV: &str = kuna_decomp::kuna_loadoptions::FLIRT_SIGS_ENV;

/// Matching rounds: a module whose reference names a function another module
/// names is accepted in the round after that name exists.
Expand Down Expand Up @@ -75,12 +75,17 @@ impl AnalysisPass for FlirtPass {
}
}

/// Parse the signature files `KUNA_FLIRT_SIGS` names (files, or directories
/// Parse the signature files the load names (`LoadOptions::flirt_sigs`, else
/// `KUNA_FLIRT_SIGS`: files, or directories
/// whose `*.sig` files are all taken) that apply to a binary of `format`:
/// startup signatures and those whose header excludes the file type are left
/// out. Unreadable or malformed files are skipped.
pub fn load_sigs(format: object::BinaryFormat) -> Vec<Signature> {
let Some(list) = std::env::var_os(FLIRT_SIGS_ENV) else { return Vec::new() };
use kuna_decomp::kuna_loadoptions::{env, scoped};
let list = scoped(|o| o.flirt_sigs.clone()).unwrap_or_else(env::flirt_sigs);
if list.is_empty() {
return Vec::new();
}
let ft = match format {
object::BinaryFormat::Elf => Some(18),
object::BinaryFormat::Pe => Some(11),
Expand All @@ -89,7 +94,7 @@ pub fn load_sigs(format: object::BinaryFormat) -> Vec<Signature> {
_ => None,
};
let mut paths: Vec<std::path::PathBuf> = Vec::new();
for p in std::env::split_paths(&list) {
for p in list {
match std::fs::read_dir(&p) {
Ok(dir) => {
let mut sigs: Vec<_> = dir
Expand Down
2 changes: 1 addition & 1 deletion decompiler/crates/kuna-analysis/src/analyzers/objc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl AnalysisPass for ObjcMetadataPass {
// The type-mapping context for IMP/ivar prototypes (PR-O2).
let (ptr_size, word_size) = ctx.arch.data_org();
let tctx = TypeCtx::new(ctx.arch.types(), ptr_size, word_size);
let sdk = match kuna_decomp::kuna_objcsdk::sdk_path_from_env() {
let sdk = match kuna_decomp::kuna_objcsdk::sdk_path() {
Some(root) => kuna_objcsdk::signatures(&root, &kuna_objcsdk::linked_frameworks(ctx.file, ctx.bytes)),
None => HashMap::new(),
};
Expand Down
26 changes: 15 additions & 11 deletions decompiler/crates/kuna-analysis/src/analyzers/pdb/locate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,20 @@ use crate::pdb::codeview::CodeViewInfo;
/// `fid` `kuna_fid_db` env gate (the FID-database external-artifact precedent):
/// the `.pdb` source is kept OFF the per-decompilation `--option` surface (so the
/// catalog carries a single on|off `pdb` settable, not a path-valued one).
pub const PDB_PATH_ENV: &str = "kuna_pdb_path";
pub const PDB_PATH_ENV: &str = kuna_decomp::kuna_loadoptions::PDB_PATH_ENV;

/// The explicitly supplied `.pdb` path: the load's `LoadOptions::pdb_path`, else
/// [`PDB_PATH_ENV`]. `None` when neither names one.
pub fn explicit_pdb_path() -> Option<PathBuf> {
use kuna_decomp::kuna_loadoptions::{env, scoped};
scoped(|o| o.pdb_path.clone()).unwrap_or_else(env::pdb_path)
}

/// Resolve the explicitly supplied `.pdb` path from [`PDB_PATH_ENV`]. `None` when
/// the variable is unset or empty.
/// the variable is unset or empty. Reads only the environment; a load in
/// progress reads [`explicit_pdb_path`].
pub fn pdb_path_from_env() -> Option<PathBuf> {
let p = std::env::var_os(PDB_PATH_ENV)?;
if p.is_empty() {
return None;
}
Some(PathBuf::from(p))
kuna_decomp::kuna_loadoptions::env::pdb_path()
}

/// The ordered `.pdb` candidates for an image, most specific first (see the module
Expand All @@ -65,7 +69,7 @@ pub fn pdb_candidates(image_path: Option<&Path>, cv: &CodeViewInfo) -> Vec<PathB
out.push(p);
}
};
if let Some(explicit) = pdb_path_from_env() {
if let Some(explicit) = explicit_pdb_path() {
add(explicit);
}
let Some(image) = image_path else {
Expand Down Expand Up @@ -205,11 +209,11 @@ mod tests {
let _guard = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
// (Serial-ish: tolerate whatever the ambient env holds by setting + clearing.)
std::env::remove_var(PDB_PATH_ENV);
assert!(pdb_path_from_env().is_none());
assert!(explicit_pdb_path().is_none());
std::env::set_var(PDB_PATH_ENV, "");
assert!(pdb_path_from_env().is_none());
assert!(explicit_pdb_path().is_none());
std::env::set_var(PDB_PATH_ENV, "/some/where.pdb");
assert_eq!(pdb_path_from_env(), Some(PathBuf::from("/some/where.pdb")));
assert_eq!(explicit_pdb_path(), Some(PathBuf::from("/some/where.pdb")));
std::env::remove_var(PDB_PATH_ENV);
}

Expand Down
10 changes: 5 additions & 5 deletions decompiler/crates/kuna-analysis/src/analyzers/sourcelang/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,19 +247,19 @@ impl Compiler {
}
}

/// The compiler verdict every consumer should act on: the `KUNA_SOURCELANG`
/// override when the environment carries one (`option sourcelang`, set by the
/// CLI before `load file` so it reaches pass selection), else detection.
/// The compiler verdict every consumer should act on: the load's forced
/// `sourcelang` when it has one (`LoadOptions::sourcelang`, or the
/// `KUNA_SOURCELANG` the CLI sets before `load file`), else detection.
pub fn effective_compiler(file: &object::File, bytes: &[u8]) -> Compiler {
match kuna_decomp::kuna_sourcelang::forced_from_env() {
match kuna_decomp::kuna_sourcelang::forced() {
Some(lang) => Compiler::from_forced_lang(lang),
None => detect_compiler(file, bytes),
}
}

/// [`effective_compiler`] over raw image bytes (the `load file` entry point).
pub fn effective_compiler_bytes(bytes: &[u8]) -> Compiler {
match kuna_decomp::kuna_sourcelang::forced_from_env() {
match kuna_decomp::kuna_sourcelang::forced() {
Some(lang) => Compiler::from_forced_lang(lang),
None => detect_compiler_bytes(bytes),
}
Expand Down
18 changes: 15 additions & 3 deletions decompiler/crates/kuna-analysis/src/image_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ impl ImageBytes {
/// Mapping requires the input file to remain unchanged while it is analyzed.
/// A kernel collection (`MH_FILESET`) declines: its entry is selected into an
/// owned copy.
/// The load's `load_mmap` option (`KUNA_LOAD_MMAP=off` outside a load)
/// selects the owned path.
pub fn map_thin_macho(path: &str) -> KunaResult<Option<Self>> {
if std::env::var("KUNA_LOAD_MMAP")
.is_ok_and(|value| matches!(value.as_str(), "off" | "0" | "false"))
{
use kuna_decomp::kuna_loadoptions::{env, scoped};
if !scoped(|o| o.load_mmap).unwrap_or_else(env::load_mmap) {
return Ok(None);
}
let file = File::open(path).map_err(|error| {
Expand Down Expand Up @@ -87,4 +88,15 @@ mod tests {
let fileset = format!("{fixtures}/kernelcache/fileset.macho");
assert!(ImageBytes::map_thin_macho(&fileset).unwrap().is_none(), "MH_FILESET entry selection");
}

#[test]
fn a_load_without_mmap_keeps_the_owned_path() {
use kuna_decomp::kuna_loadoptions::LoadOptions;
let thin = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/macho_objc_arm64");
let owned = LoadOptions { load_mmap: false, ..LoadOptions::default() };
let _load = owned.enter();
assert!(ImageBytes::map_thin_macho(thin).unwrap().is_none());
let _load = LoadOptions::default().enter();
assert!(ImageBytes::map_thin_macho(thin).unwrap().is_some());
}
}
2 changes: 1 addition & 1 deletion decompiler/crates/kuna-analysis/src/loader/elf_shdr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub fn read_image_selected(
Some(image) => image.map_err(std::io::Error::other)?,
None => std::fs::read(path)?,
};
let choice = kuna_decomp::kuna_kernelcache::KernelcacheChoice::from_env();
let choice = kuna_decomp::kuna_kernelcache::KernelcacheChoice::in_force();
let peeled = super::kuna_kernelcache::peel(bytes, &choice).map_err(std::io::Error::other)?;
let bytes = super::macho_fat::peel_fat_image(peeled.bytes, pref);
let (bytes, shdr) = tolerate_unusable_section_table(bytes);
Expand Down
42 changes: 20 additions & 22 deletions decompiler/crates/kuna-analysis/src/loader/macho_fat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,22 +123,24 @@ pub fn fat_slice_offset(bytes: &[u8], pref: SlicePref) -> Option<u64> {
Some((slice.as_ptr() as usize - bytes.as_ptr() as usize) as u64) // cast: a sub-slice's index
}

/// The environment variable carrying a `--slice <arch>` fat-slice override.
/// Read live (per image read) so a test — and the in-process CLI surfaces — can
/// set it without threading a token; empty/unset selects the default slice.
pub const SLICE_ENV: &str = "KUNA_MACHO_SLICE";
/// The environment variable carrying a `--slice <arch>` fat-slice override to
/// the `decomp_dbg` subprocess and the in-process CLI surfaces; empty/unset
/// selects the default slice.
pub const SLICE_ENV: &str = kuna_decomp::kuna_loadoptions::MACHO_SLICE_ENV;

/// The slice preference a run asks for, in precedence order: an explicit
/// `--slice` token, else [`SLICE_ENV`], else the `--target` token's leading arch
/// `--slice` token, else the load's slice (`LoadOptions::macho_slice`, or
/// [`SLICE_ENV`] outside a load scope), else the `--target` token's leading arch
/// stem, else the deterministic default. An explicit slice that names nothing
/// recognizable stays the default rather than falling through to `--target`, so
/// a typo'd `--slice` cannot be silently answered by the language override.
pub fn slice_pref(slice: Option<&str>, target: Option<&str>) -> SlicePref {
use kuna_decomp::kuna_loadoptions::{env, scoped};
let explicit = slice
.map(str::trim)
.filter(|token| !token.is_empty())
.map(str::to_string)
.or_else(|| std::env::var(SLICE_ENV).ok().filter(|t| !t.trim().is_empty()));
.or_else(|| scoped(|o| o.macho_slice.clone()).unwrap_or_else(env::macho_slice));
if let Some(token) = explicit {
return SlicePref::parse(&token);
}
Expand Down Expand Up @@ -234,29 +236,25 @@ mod tests {
assert!(select_fat_slice(&[0x7f, b'E', b'L', b'F'], SlicePref::default()).is_none());
}

/// The preference order the CLI and the dispatch share. The environment
/// override is asserted through an explicit token rather than by setting the
/// var, because `std::env` is process-global and cargo runs these in
/// parallel.
/// The preference order the CLI and the dispatch share. A load scope stands
/// in for the environment, so the ambient `KUNA_MACHO_SLICE` cannot reach
/// these assertions.
#[test]
fn slice_pref_prefers_an_explicit_slice_over_a_target_stem() {
let _load = kuna_decomp::kuna_loadoptions::LoadOptions::default().enter();
assert_eq!(
slice_pref(Some("arm64"), Some("x86:LE:64:default:gcc")).0,
Some(Architecture::Aarch64),
"--slice wins over the --target stem"
);
// The `--target`-only fallbacks read the environment first, so they are
// only meaningful with no ambient override set.
if std::env::var_os(SLICE_ENV).is_none() {
assert_eq!(
slice_pref(None, Some("x86:LE:64:default:gcc")).0,
Some(Architecture::X86_64),
"--target alone still steers the slice"
);
// A blank token is not an override.
assert_eq!(slice_pref(Some(" "), Some("arm64")).0, Some(Architecture::Aarch64));
assert_eq!(slice_pref(None, None).0, None);
}
assert_eq!(
slice_pref(None, Some("x86:LE:64:default:gcc")).0,
Some(Architecture::X86_64),
"--target alone still steers the slice"
);
// A blank token is not an override.
assert_eq!(slice_pref(Some(" "), Some("arm64")).0, Some(Architecture::Aarch64));
assert_eq!(slice_pref(None, None).0, None);
// An unrecognized --slice stays the DEFAULT rather than falling through
// to --target: a typo must not be answered by the language override.
assert_eq!(slice_pref(Some("riscv-banana"), Some("arm64")).0, None);
Expand Down
19 changes: 9 additions & 10 deletions decompiler/crates/kuna-analysis/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,17 @@ use crate::loadimage_object::ObjectLoadImage;
use crate::pass::{run_analyses, AnalysisCtx, AnalysisOutput, AnalysisPass};
use crate::sourcelang::Compiler;

pub const LOAD_OBJC_ENV: &str = "KUNA_LOAD_OBJC";
pub const LOAD_STRINGS_ENV: &str = "KUNA_LOAD_STRINGS";
pub use kuna_decomp::kuna_loadoptions::{LOAD_OBJC_ENV, LOAD_STRINGS_ENV};

/// Whether the load runs pass `id`: the `objc` and `strings` passes can be
/// skipped by the load's options.
fn load_pass_enabled(id: &str) -> bool {
let env = match id {
"objc" => LOAD_OBJC_ENV,
"strings" => LOAD_STRINGS_ENV,
_ => return true,
};
!std::env::var(env).is_ok_and(|value| {
matches!(value.trim().to_ascii_lowercase().as_str(), "off" | "0" | "false")
})
use kuna_decomp::kuna_loadoptions::{env, scoped};
match id {
"objc" => scoped(|o| o.load_objc).unwrap_or_else(env::load_objc),
"strings" => scoped(|o| o.load_strings).unwrap_or_else(env::load_strings),
_ => true,
}
}

/// The default program-prep passes, in stage order.
Expand Down
5 changes: 5 additions & 0 deletions decompiler/crates/kuna-base/src/filemanage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ impl FileManage {
}
}

/// The search path, in the order directories were added (kuna).
pub fn path_list(&self) -> &[String] {
&self.pathlist
}

/// Add current working directory to path (C++ `addCurrentDir`).
///
/// C++ calls `getcwd` into a 256-byte buffer and silently adds nothing on
Expand Down
4 changes: 4 additions & 0 deletions decompiler/crates/kuna-console/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ path = "tests/verify_macho_fat.rs"
name = "verify_msvcfpconst"
path = "tests/verify_msvcfpconst.rs"

[[test]]
name = "verify_loadoptions"
path = "tests/verify_loadoptions.rs"

[[test]]
name = "verify_pdatachained"
path = "tests/verify_pdatachained.rs"
Expand Down
3 changes: 3 additions & 0 deletions decompiler/crates/kuna-console/src/assertions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ pub fn parse_hex_bytes(tok: &str) -> Result<Vec<u8>, String> {
/// `readonly`/`volatile` precedent is the same constraint inverted — a range
/// property stated after the symbols over it are mapped is silently inert.
pub fn apply_image_scoped(prog: &mut ConsoleProgram) {
let _load = prog.arch().load_scope();
let directives = prog.assertions().to_vec();
for (i, directive) in directives.iter().enumerate() {
let Body::Bytes { addr, data } = &directive.body else {
Expand Down Expand Up @@ -382,6 +383,7 @@ fn overlay_bytes(prog: &mut ConsoleProgram, vma: u64, data: &[u8]) -> Result<(),
/// it, which is how "you asked about a function this run did not decompile"
/// becomes a report row instead of silence.
pub fn apply_program_scoped(prog: &mut ConsoleProgram) {
let _load = prog.arch().load_scope();
let directives = prog.assertions().to_vec();
for (i, directive) in directives.iter().enumerate() {
// A QUALIFIED `param`/`return` is a statement about the named function's
Expand Down Expand Up @@ -1112,6 +1114,7 @@ pub fn apply_symbol_scoped(
name: &str,
single: bool,
) -> Option<Vec<Expected>> {
let _load = prog.arch().load_scope();
let directives = prog.assertions().to_vec();
let mut applied_any = false;
let mut touched: Vec<(usize, kuna_decomp::database::SymbolId, Option<Rc<Datatype>>)> = Vec::new();
Expand Down
3 changes: 3 additions & 0 deletions decompiler/crates/kuna-console/src/decompile_step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ pub fn decompile_one_prefollowed(
proto_overrides: &[(Address, PrototypePieces)],
prefollowed: Option<Funcdata>,
) -> DecompileStep {
// The lazy callee materialization between the drives names functions, so
// it reads the program's load-time options too.
let _load = arch.load_scope();
let mut first = decompile_one_prefollowed_once(
arch,
name,
Expand Down
Loading