From 1c7ec59910f603c78cc5e847bc600b19073d3e70 Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:31:59 +0800 Subject: [PATCH 1/3] drm: drop the string obfuscation, the project is open source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `gndrm-obf` and `gndrm-obf-macros` XOR-encoded every message literal and decoded it into a stack buffer at the use site, so `strings` over a shipped artifact found nothing. Both crates are deleted, with every dependency on them. The log text is a plain literal again, and that is the point: a diagnostic a user can grep out of the .so is worth more than one they cannot. Rust call sites — 585 `gndrm_obf::obf!` and one `obfc!`, across the ICD shim, the daemon and the app side: - a literal with no placeholders is the literal; - anything else is the message and its arguments, e.g. `logf!("proxy pool: fourcc 0x{:x} route={}", …)`. The log macros do the formatting now: `logf!`, `logi!` and `log_reason!` take `$($arg:tt)*` and pass them to `format_args!`, so a call site is the message and not a wrapper around it. `log_reason!` still owns the line, because it stores it as the reported reason. `log.rs`'s logcat tag was the one `obfc!` use — six gate tags decoded into a NUL-terminated buffer. They are `c"…"` literals now, and the `tag!` arm takes an expression rather than a string literal. Four `Display` impls were rewritten to write the message straight (`write!(f, "{layout} (env)")`) instead of formatting into a `String` first. C side: `tools/obf-shim.py` rewrote each `LOG(...)` site in the LD_PRELOAD shim into an XOR-decode at build time, and `build-shim.sh` compiled the generated copy from `target/shim/gen/`. The script is deleted and the shim compiles its source as written, so the shipped `libgndrm_shim.so` now carries `intercepting %s for %s in %s` and the rest. Manifests: the two crate entries leave the workspace, and the dependency lines (and the comments explaining why the obfuscation existed) leave `gndrm-android`, `gndrm-daemon`, `gndrm-lsfg`, `gndrm-uapi` and `icd_shim`. Text that described the removed behaviour: the log module docs said the tag is decoded at runtime; `gndrm-daemon`'s two logger thunks explained a "stack decode"; `asc.rs` said its refusal labels are owned because the literals are obfuscated; `docs/performance/05` justified "no heap" by pointing at `gndrm-obf/src/lib.rs:46`. All four now state what the code does. The historical diff hunks in 05 and 06 are left as they were — they record patches as applied. `THIRD_PARTY_NOTICES` listed "the obfuscation crates" in the licence scope; it lists the ICD shim instead. Verified: `cargo clippy --workspace --all-targets -- -D warnings` clean, `cargo test --workspace` 340 passed / 0 failed across 30 suites, `tools/build-android.sh` green through the export allowlist and undefined-symbol audit, `tools/build-shim.sh android` green. `strings` on both rebuilt libraries now shows the log text. --- Cargo.lock | 21 - Cargo.toml | 2 - THIRD_PARTY_NOTICES | 4 +- .../05-daemon-present-allocations.md | 2 +- icd_shim/Cargo.toml | 1 - icd_shim/src/advertise.rs | 24 +- icd_shim/src/divisor.rs | 4 +- icd_shim/src/export.rs | 132 +-- icd_shim/src/image_count.rs | 2 +- icd_shim/src/lib.rs | 162 +-- icd_shim/src/lsfg/mod.rs | 74 +- icd_shim/src/placed.rs | 34 +- icd_shim/src/present.rs | 6 +- icd_shim/src/proxy.rs | 938 ++++++------------ icd_shim/src/resolve_probe.rs | 14 +- icd_shim/src/scanout.rs | 32 +- icd_shim/src/segv.rs | 10 +- icd_shim/src/thunk.rs | 22 +- icd_shim/src/x11.rs | 99 +- modules/gndrm-android/Cargo.toml | 5 - modules/gndrm-android/src/asc.rs | 248 ++--- modules/gndrm-android/src/choreographer.rs | 39 +- modules/gndrm-android/src/dump.rs | 2 +- modules/gndrm-android/src/foreign.rs | 16 +- modules/gndrm-android/src/injector.rs | 52 +- modules/gndrm-android/src/layout.rs | 6 +- modules/gndrm-android/src/lib.rs | 146 ++- modules/gndrm-android/src/log.rs | 30 +- modules/gndrm-android/src/vsync.rs | 6 +- modules/gndrm-daemon/Cargo.toml | 1 - modules/gndrm-daemon/src/bin/gndrm-hostd.rs | 6 +- modules/gndrm-daemon/src/commit.rs | 70 +- modules/gndrm-daemon/src/foreign.rs | 8 +- modules/gndrm-daemon/src/lib.rs | 62 +- modules/gndrm-daemon/src/objects.rs | 2 +- modules/gndrm-daemon/src/scanout.rs | 34 +- modules/gndrm-daemon/src/server.rs | 54 +- modules/gndrm-lsfg/Cargo.toml | 3 - modules/gndrm-lsfg/src/cache.rs | 12 +- modules/gndrm-lsfg/src/lib.rs | 2 +- modules/gndrm-obf-macros/Cargo.toml | 21 - modules/gndrm-obf-macros/src/lib.rs | 245 ----- modules/gndrm-obf/Cargo.toml | 21 - modules/gndrm-obf/src/lib.rs | 158 --- modules/gndrm-uapi/Cargo.toml | 3 - tools/build-shim.sh | 10 +- tools/obf-shim.py | 218 ---- 47 files changed, 835 insertions(+), 2228 deletions(-) delete mode 100644 modules/gndrm-obf-macros/Cargo.toml delete mode 100644 modules/gndrm-obf-macros/src/lib.rs delete mode 100644 modules/gndrm-obf/Cargo.toml delete mode 100644 modules/gndrm-obf/src/lib.rs delete mode 100644 tools/obf-shim.py diff --git a/Cargo.lock b/Cargo.lock index 9e69928..8915da8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,7 +7,6 @@ name = "adrenotools_gamescope" version = "0.1.0" dependencies = [ "gndrm-lsfg", - "gndrm-obf", "gndrm-uapi", "libc", ] @@ -92,7 +91,6 @@ version = "0.1.0" dependencies = [ "bitflags", "gndrm-daemon", - "gndrm-obf", "gndrm-uapi", "jni", "libc", @@ -106,7 +104,6 @@ dependencies = [ name = "gndrm-daemon" version = "0.1.0" dependencies = [ - "gndrm-obf", "gndrm-uapi", "libc", ] @@ -115,32 +112,14 @@ dependencies = [ name = "gndrm-lsfg" version = "0.1.0" dependencies = [ - "gndrm-obf", "libc", ] -[[package]] -name = "gndrm-obf" -version = "0.1.0" -dependencies = [ - "gndrm-obf-macros", -] - -[[package]] -name = "gndrm-obf-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "gndrm-uapi" version = "0.1.0" dependencies = [ "cc", - "gndrm-obf", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 0a4834c..ee53f6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,8 +2,6 @@ resolver = "2" members = [ "modules/gndrm-lsfg", - "modules/gndrm-obf", - "modules/gndrm-obf-macros", "modules/gndrm-uapi", "modules/gndrm-daemon", "modules/gndrm-android", diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICES index 148f3e6..4b5ec28 100644 --- a/THIRD_PARTY_NOTICES +++ b/THIRD_PARTY_NOTICES @@ -30,6 +30,6 @@ License text: `lsfg/thirdparty/dxbc/LICENSE.md`. Also recorded in GameNative's --- The `LICENSE` in this repository covers its own code — the daemon, the DRM UAPI -crate, the obfuscation crates and the tools — under GPL-3.0-or-later, the same -license as the library the engine is linked into. Copyright (C) 2026 Joshua Tam +crate, the ICD shim and the tools — under GPL-3.0-or-later, the same license as +the library the engine is linked into. Copyright (C) 2026 Joshua Tam and Utkarsh Dalal. diff --git a/docs/performance/05-daemon-present-allocations.md b/docs/performance/05-daemon-present-allocations.md index 4ac117c..6c45406 100644 --- a/docs/performance/05-daemon-present-allocations.md +++ b/docs/performance/05-daemon-present-allocations.md @@ -32,7 +32,7 @@ frame, i.e. ~340 Hz, on a path the doc calls **exactly one deep**: every µs her | — | `PresentDone::encode()` (`wire.rs:727`) | **refuted** | — | — | returns `[u8; 24]`, stack | | — | `server.rs` serve pollfd array (`:386`) | **refuted** | — | — | fixed `[pollfd; 2]` on the stack | | — | `dump_published` env lookup (`asc.rs:149`) | **refuted** | — | — | `OnceLock`, one lookup per process | -| — | log macros on the hot path | **refuted** | `log.rs:20` | — | gate is tested before `fmt::format`; `obf!` decodes into a stack array (`gndrm-obf/src/lib.rs:46`), no heap | +| — | log macros on the hot path | **refuted** | `log.rs:20` | — | gate is tested before `fmt::format`, so a disabled line formats nothing | Non-allocation hot-path cost found while verifying, listed for completeness, **not** in this plan item: `Device::diag_on()` (`lib.rs:903`) takes the logger `Mutex` once per commit — a diff --git a/icd_shim/Cargo.toml b/icd_shim/Cargo.toml index 3e8e298..be31a8f 100644 --- a/icd_shim/Cargo.toml +++ b/icd_shim/Cargo.toml @@ -35,5 +35,4 @@ libc = "0.2" # LD_PRELOAD shim's — a second, hand-mirrored set of structs is how the two # sides drift apart. gndrm-lsfg = { path = "../modules/gndrm-lsfg" } -gndrm-obf = { path = "../modules/gndrm-obf" } gndrm-uapi = { path = "../modules/gndrm-uapi" } diff --git a/icd_shim/src/advertise.rs b/icd_shim/src/advertise.rs index 9425909..03039d6 100644 --- a/icd_shim/src/advertise.rs +++ b/icd_shim/src/advertise.rs @@ -167,10 +167,8 @@ pub fn mask(c: &mut CoreFeatures, base: &CoreFeatures) -> Vec<&'static str> { // same at its create ("Faking feature support for ..."); here it is the // calibration signal when a game misbehaves under a lift the driver gated. if !cleared.is_empty() && !MASKED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "feature lift masked back to the driver's answer: {}", - cleared.join(" ") - )); + crate::logf!("feature lift masked back to the driver's answer: {}", + cleared.join(" ")); } cleared } @@ -220,14 +218,10 @@ pub unsafe fn features(f: *mut c_void) { let zero = zeros(c); let raised = lift_core(c); if !LOGGED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "driver core features zero: {}", - zero.join(" ") - )); - crate::logf!(gndrm_obf::obf!( - "wrapper-style feature lift over the driver's zeros: {}", - raised.join(" ") - )); + crate::logf!("driver core features zero: {}", + zero.join(" ")); + crate::logf!("wrapper-style feature lift over the driver's zeros: {}", + raised.join(" ")); } } @@ -264,10 +258,8 @@ pub fn request_mismatch(c: &CoreFeatures, base: &CoreFeatures) -> Vec<&'static s inheritedQueries, ); if !bad.is_empty() && !MISMATCH.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "guest requests features the driver answers zero: {}", - bad.join(" ") - )); + crate::logf!("guest requests features the driver answers zero: {}", + bad.join(" ")); } bad } diff --git a/icd_shim/src/divisor.rs b/icd_shim/src/divisor.rs index bc15036..d8543cc 100644 --- a/icd_shim/src/divisor.rs +++ b/icd_shim/src/divisor.rs @@ -16,9 +16,7 @@ static FAKED: AtomicBool = AtomicBool::new(false); pub fn note_faked() { if !FAKED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "proxy: advertised VK_EXT_vertex_attribute_divisor over the KHR extension" - )); + crate::logf!("proxy: advertised VK_EXT_vertex_attribute_divisor over the KHR extension"); } } diff --git a/icd_shim/src/export.rs b/icd_shim/src/export.rs index 50db7c0..c861b5f 100644 --- a/icd_shim/src/export.rs +++ b/icd_shim/src/export.rs @@ -352,11 +352,9 @@ fn register_image(e: EmuImage) { if old.image != e.image { return true; } - crate::logf!(gndrm_obf::obf!( - "export-emu: image {:#x} reused; dropping stale fd={}", + crate::logf!("export-emu: image {:#x} reused; dropping stale fd={}", old.image, - old.fd - )); + old.fd); close_fd(old.fd); false }); @@ -525,12 +523,10 @@ pub unsafe extern "C" fn gn_vkGetPhysicalDeviceImageFormatProperties2( LINEAR_MODIFIER_REFUSED.store(true, Ordering::Relaxed); } if !LOGGED_QUERY.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "export-emu: modifier query fmt={} usage={:#x} flags={:#x} driver={res} features={features:#x} linear={lres}", + crate::logf!("export-emu: modifier query fmt={} usage={:#x} flags={:#x} driver={res} features={features:#x} linear={lres}", lin.format, lin.usage, - lin.flags - )); + lin.flags); } if lres != VK_SUCCESS { return res; @@ -602,18 +598,14 @@ pub unsafe fn try_create_image( && std::env::var_os("GNDRM_EXPORT_AHB").is_some_and(|v| v == "1") { DMABUF_IMPORT.store(DMABUF_REFUSED, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "export-emu: GNDRM_EXPORT_AHB=1, importing pool buffers as AHardwareBuffers from the start" - )); + crate::logf!("export-emu: GNDRM_EXPORT_AHB=1, importing pool buffers as AHardwareBuffers from the start"); } if DMABUF_IMPORT.load(Ordering::Relaxed) == DMABUF_UNKNOWN && LINEAR_MODIFIER_REFUSED.load(Ordering::Relaxed) && std::env::var_os("GNDRM_EXPORT_AHB").is_none_or(|v| v != "0") { DMABUF_IMPORT.store(DMABUF_REFUSED, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "export-emu: the driver refuses LINEAR DRM-modifier images; importing pool buffers as AHardwareBuffers from the start (GNDRM_EXPORT_AHB=0 forces the dma-buf route)" - )); + crate::logf!("export-emu: the driver refuses LINEAR DRM-modifier images; importing pool buffers as AHardwareBuffers from the start (GNDRM_EXPORT_AHB=0 forces the dma-buf route)"); } let route = DMABUF_IMPORT.load(Ordering::Relaxed); let (w, h) = (ci.extent.width, ci.extent.height); @@ -624,9 +616,7 @@ pub unsafe fn try_create_image( } .or_else(|| crate::scanout::allocate(w, h)); let Some(buf) = buf else { - crate::logf!(gndrm_obf::obf!( - "export-emu: pool allocation {w}x{h} refused; driver create" - )); + crate::logf!("export-emu: pool allocation {w}x{h} refused; driver create"); return None; }; let fl = unsafe { find_in(ci.pNext, STYPE_IMAGE_FORMAT_LIST_CREATE_INFO) } @@ -675,17 +665,13 @@ pub unsafe fn try_create_image( } } if buf.ahb.is_null() { - crate::logf!(gndrm_obf::obf!( - "export-emu: no AHardwareBuffer from the daemon for {w}x{h}; nothing to fall back to" - )); + crate::logf!("export-emu: no AHardwareBuffer from the daemon for {w}x{h}; nothing to fall back to"); close_fd(buf.fd); return Some(refused.unwrap_or(VK_ERROR_INITIALIZATION_FAILED)); } if let Some(r) = refused { DMABUF_IMPORT.store(DMABUF_REFUSED, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "export-emu: dma-buf import failed ({r}), importing pool buffer as AHardwareBuffer" - )); + crate::logf!("export-emu: dma-buf import failed ({r}), importing pool buffer as AHardwareBuffer"); } let res = unsafe { create_ahb_backed(gd, ci, &buf, fl_ptr, alloc) }; unsafe { crate::scanout::ahb_release(buf.ahb) }; @@ -801,14 +787,12 @@ pub unsafe fn try_create_import_image( note_import(unsafe { *out }, true); } if IMPORT_LOGS.fetch_add(1, Ordering::Relaxed) < IMPORT_LOG_FIRST_N { - crate::logf!(gndrm_obf::obf!( - "export-emu: import image {:#x} {}x{} fmt={} usage={:#x} created for the AHardwareBuffer route: {res}", + crate::logf!("export-emu: import image {:#x} {}x{} fmt={} usage={:#x} created for the AHardwareBuffer route: {res}", if res == VK_SUCCESS { unsafe { *out } } else { 0 }, ci.extent.width, ci.extent.height, ci.format, - ci.usage - )); + ci.usage); } Some(res) } @@ -850,20 +834,16 @@ unsafe fn try_allocate_import( close_fd(buf.fd); unsafe { crate::scanout::ahb_release(buf.ahb) }; DMABUF_IMPORT.store(DMABUF_REFUSED, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "export-emu: dma-buf import of pool buffer ino={ino} for image {:#x} failed ({res}); later imports take the AHardwareBuffer route", - image - )); + crate::logf!("export-emu: dma-buf import of pool buffer ino={ino} for image {:#x} failed ({res}); later imports take the AHardwareBuffer route", + image); } } return Some(res); } let ino = fd_ino(fd); let Some(buf) = crate::scanout::lookup_ahb(ino) else { - crate::logf!(gndrm_obf::obf!( - "export-emu: import ino={ino} for image {:#x}: no pool AHardwareBuffer from the daemon", - image - )); + crate::logf!("export-emu: import ino={ino} for image {:#x}: no pool AHardwareBuffer from the daemon", + image); return Some(VK_ERROR_INVALID_EXTERNAL_HANDLE); }; close_fd(buf.fd); @@ -922,10 +902,8 @@ unsafe fn import_ahb_dedicated( }; let res = unsafe { get_props(dev, ahb, &mut props) }; if res != VK_SUCCESS || props.memory_type_bits == 0 { - crate::logf!(gndrm_obf::obf!( - "export-emu: import ino={ino} AHB properties {res} memTypeBits={:#x}", - props.memory_type_bits - )); + crate::logf!("export-emu: import ino={ino} AHB properties {res} memTypeBits={:#x}", + props.memory_type_bits); return if res != VK_SUCCESS { res } else { @@ -956,21 +934,18 @@ unsafe fn import_ahb_dedicated( }; let res = unsafe { alloc_mem(dev, &ai, ptr::null(), out) }; if IMPORT_LOGS.fetch_add(1, Ordering::Relaxed) < IMPORT_LOG_FIRST_N || res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!( - "export-emu: import ino={ino} as AHardwareBuffer for image {:#x} size={} type={} format={} fd link={} -> {res}", + crate::logf!("export-emu: import ino={ino} as AHardwareBuffer for image {:#x} size={} type={} format={} fd link={} -> {res}", image, props.allocation_size, mem_type, fmt.format, - crate::scanout::fd_link(fd) - )); + crate::scanout::fd_link(fd)); } res } fn log_image(ci: &VkImageCreateInfo, buf: &crate::scanout::ScanoutBuf, image: VkImage, how: &str) { - crate::logf!(gndrm_obf::obf!( - "export-emu: image {:#x} {}x{} fmt={} usage={:#x} pool fd={} ino={} stride={} {how}", + crate::logf!("export-emu: image {:#x} {}x{} fmt={} usage={:#x} pool fd={} ino={} stride={} {how}", image, ci.extent.width, ci.extent.height, @@ -978,8 +953,7 @@ fn log_image(ci: &VkImageCreateInfo, buf: &crate::scanout::ScanoutBuf, image: Vk ci.usage, buf.fd, buf.ino, - buf.stride - )); + buf.stride); } /// The first memory type in `bits`, preferring a device-local one. @@ -1067,9 +1041,7 @@ unsafe fn create_dmabuf_backed( ci2.tiling = VK_IMAGE_TILING_LINEAR; res = unsafe { create(dev, &ci2, alloc, &mut image) }; linear_tiling = true; - crate::logf!(gndrm_obf::obf!( - "export-emu: explicit LINEAR create {r1}; LINEAR tiling create {res}" - )); + crate::logf!("export-emu: explicit LINEAR create {r1}; LINEAR tiling create {res}"); } if res != VK_SUCCESS { return Err(res); @@ -1116,17 +1088,13 @@ unsafe fn create_dmabuf_backed( break; } } - crate::logf!(gndrm_obf::obf!( - "export-emu: {} image {:#x} layout pitch={pitch} offset={offset} (pool stride {})", + crate::logf!("export-emu: {} image {:#x} layout pitch={pitch} offset={offset} (pool stride {})", if linear_tiling { "LINEAR-tiling" } else { "explicit-LINEAR" }, image, - buf.stride - )); + buf.stride); if pitch != 0 && (pitch != u64::from(buf.stride) || offset != 0) { - crate::logf!(gndrm_obf::obf!( - "export-emu: driver pitch {pitch} != pool stride {}; the dma-buf route cannot scan out, trying AHardwareBuffer", - buf.stride - )); + crate::logf!("export-emu: driver pitch {pitch} != pool stride {}; the dma-buf route cannot scan out, trying AHardwareBuffer", + buf.stride); return fail(VK_ERROR_FORMAT_NOT_SUPPORTED); } } @@ -1138,12 +1106,10 @@ unsafe fn create_dmabuf_backed( unsafe { libc::lseek(buf.fd, 0, libc::SEEK_SET) }; } if pool_size >= 0 && (pool_size as u64) < reqs.size { - crate::logf!(gndrm_obf::obf!( - "export-emu: pool fd for image {:#x} is {} bytes < size={}", + crate::logf!("export-emu: pool fd for image {:#x} is {} bytes < size={}", image, pool_size, - reqs.size - )); + reqs.size); return fail(VK_ERROR_INVALID_EXTERNAL_HANDLE); } let mut fd_bits = u32::MAX; @@ -1165,11 +1131,9 @@ unsafe fn create_dmabuf_backed( if r == VK_SUCCESS && p.memoryTypeBits & reqs.memoryTypeBits != 0 { fd_bits = p.memoryTypeBits; } else { - crate::logf!(gndrm_obf::obf!( - "export-emu: dma-buf fd properties {r} memTypeBits {:#x} (image {:#x})", + crate::logf!("export-emu: dma-buf fd properties {r} memTypeBits {:#x} (image {:#x})", p.memoryTypeBits, - reqs.memoryTypeBits - )); + reqs.memoryTypeBits); } } let types = unsafe { memory_types(gd) }; @@ -1200,15 +1164,13 @@ unsafe fn create_dmabuf_backed( }; let mut mem: VkDeviceMemory = 0; let res = unsafe { alloc_mem(dev, &ai, ptr::null(), &mut mem) }; - crate::logf!(gndrm_obf::obf!( - "export-emu: import pool fd for image {:#x} size={} pool={} type={} bits={:#x}/{:#x} -> {res}", + crate::logf!("export-emu: import pool fd for image {:#x} size={} pool={} type={} bits={:#x}/{:#x} -> {res}", image, reqs.size, pool_size, mem_type, reqs.memoryTypeBits, - fd_bits - )); + fd_bits); if res != VK_SUCCESS { unsafe { libc::close(fd) }; return fail(res); @@ -1243,9 +1205,7 @@ unsafe fn create_ahb_backed( )) }; let Some(get_props) = get_props else { - crate::logf!(gndrm_obf::obf!( - "export-emu: driver resolves no vkGetAndroidHardwareBufferPropertiesANDROID" - )); + crate::logf!("export-emu: driver resolves no vkGetAndroidHardwareBufferPropertiesANDROID"); return Err(VK_ERROR_INITIALIZATION_FAILED); }; let mut fmt = AhbFormatProperties { @@ -1264,15 +1224,13 @@ unsafe fn create_ahb_backed( memory_type_bits: 0, }; let res = unsafe { get_props(dev, buf.ahb, &mut props) }; - crate::logf!(gndrm_obf::obf!( - "export-emu: AHB ino={} size={} memTypeBits={:#x} format={} external={:#x} (image fmt {}): {res}", + crate::logf!("export-emu: AHB ino={} size={} memTypeBits={:#x} format={} external={:#x} (image fmt {}): {res}", buf.ino, props.allocation_size, props.memory_type_bits, fmt.format, fmt.external_format, - ci.format - )); + ci.format); if res != VK_SUCCESS { return Err(res); } @@ -1292,9 +1250,7 @@ unsafe fn create_ahb_backed( let mut image: VkImage = 0; let res = unsafe { create(dev, &ci2, alloc, &mut image) }; if res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!( - "export-emu: AHB image create failed: {res}" - )); + crate::logf!("export-emu: AHB image create failed: {res}"); return Err(res); } let img_bits = unsafe { image_requirements(gd, image) }.map_or(u32::MAX, |r| r.memoryTypeBits); @@ -1321,12 +1277,10 @@ unsafe fn create_ahb_backed( }; let mut mem: VkDeviceMemory = 0; let res = unsafe { alloc_mem(dev, &ai, ptr::null(), &mut mem) }; - crate::logf!(gndrm_obf::obf!( - "export-emu: AHB import for image {:#x} size={} type={} -> {res}", + crate::logf!("export-emu: AHB import for image {:#x} size={} type={} -> {res}", image, props.allocation_size, - mem_type - )); + mem_type); if res != VK_SUCCESS { unsafe { destroy_real_image(gd, image, alloc) }; return Err(res); @@ -1400,11 +1354,9 @@ pub unsafe extern "C" fn gn_vkDestroyImage( if enabled() && image != 0 { forget_import(image); if let Some((e, mems)) = forget_image(image) { - crate::logf!(gndrm_obf::obf!( - "export-emu: drop image {:#x} pool fd={} mems={mems}", + crate::logf!("export-emu: drop image {:#x} pool fd={} mems={mems}", e.image, - e.fd - )); + e.fd); unclaimed = e.mem; } } @@ -1592,9 +1544,7 @@ pub unsafe extern "C" fn gn_vkUpdateDescriptorSets( } } if skipped > 0 && !LOGGED_NULL_SKIP.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "export-emu: skipped {skipped} null descriptor element(s) in {write_count} write(s)" - )); + crate::logf!("export-emu: skipped {skipped} null descriptor element(s) in {write_count} write(s)"); } unsafe { real( diff --git a/icd_shim/src/image_count.rs b/icd_shim/src/image_count.rs index 8c1ad60..40b6566 100644 --- a/icd_shim/src/image_count.rs +++ b/icd_shim/src/image_count.rs @@ -105,7 +105,7 @@ pub unsafe fn note_instance(app: *const VkApplicationInfo) { let comm = std::fs::read_to_string("/proc/self/comm").unwrap_or_default(); if let Some(game) = find_strict_game(comm.trim_end(), app_name, engine_name, engine_version) { if MATCHED.set(game).is_ok() { - crate::logi!(gndrm_obf::obf!("strict image count on: {:?}", game)); + crate::logi!("strict image count on: {:?}", game); } } } diff --git a/icd_shim/src/lib.rs b/icd_shim/src/lib.rs index a75ce3f..d3e812c 100644 --- a/icd_shim/src/lib.rs +++ b/icd_shim/src/lib.rs @@ -45,13 +45,13 @@ /// Emit a `gn-vkshim:` line to stderr, unless `GNDRM_LOG_VKSHIM` is off /// (unset, `""` or `"0"` — the default). `$e` is a ready-to-format value: a -/// call site passes `gndrm_obf::obf!(...)` so the message text is decoded at +/// call site passes `...` so the message text is decoded at /// runtime and never lands in `.rodata`. The prefix is decoded likewise. #[macro_export] macro_rules! logf { - ($e:expr) => { + ($($arg:tt)*) => { if $crate::vkshim_enabled() { - eprintln!("{} {}", ::gndrm_obf::obf!("gn-vkshim:"), $e); + eprintln!("{} {}", "gn-vkshim:", format_args!($($arg)*)); } }; } @@ -62,8 +62,8 @@ macro_rules! logf { /// gamescope, so a gated line can never be turned on there. #[macro_export] macro_rules! logi { - ($e:expr) => { - eprintln!("{} {}", ::gndrm_obf::obf!("gn-vkshim:"), $e) + ($($arg:tt)*) => { + eprintln!("{} {}", "gn-vkshim:", format_args!($($arg)*)) }; } @@ -71,10 +71,10 @@ macro_rules! logi { /// with no driver. #[macro_export] macro_rules! log_reason { - ($e:expr) => {{ - let line = format!("{}", $e); + ($($arg:tt)*) => {{ + let line = format!($($arg)*); $crate::note_reason(&line); - eprintln!("{} {}", ::gndrm_obf::obf!("gn-vkshim:"), line); + eprintln!("{} {}", "gn-vkshim:", line); }}; } @@ -150,14 +150,12 @@ fn announce(entry: &str) { static ONCE: Once = Once::new(); ONCE.call_once(|| { let comm = std::fs::read_to_string("/proc/self/comm").unwrap_or_default(); - logi!(gndrm_obf::obf!( - "ICD loaded [shim {} {}] pid={} comm={} first entry {}", + logi!("ICD loaded [shim {} {}] pid={} comm={} first entry {}", SHIM_BUILD, SHIM_GIT, std::process::id(), comm.trim_end(), - entry - )); + entry); }); } @@ -346,9 +344,7 @@ fn negotiate_icd(h: *mut c_void) { let f: unsafe extern "C" fn(*mut u32) -> VkResult = unsafe { std::mem::transmute(sym) }; let mut v: u32 = 5; let r = unsafe { f(&mut v) }; - logf!(gndrm_obf::obf!( - "wrapper icd: negotiated interface {v} ({r})" - )); + logf!("wrapper icd: negotiated interface {v} ({r})"); } fn try_system_driver() { @@ -360,46 +356,34 @@ fn try_system_driver() { if let Some(w) = wrapper.as_deref() { let h = unsafe { libc::dlopen(w.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if h.is_null() { - logf!(gndrm_obf::obf!( - "wrapper icd: dlopen failed: {}", - dlerror_str() - )); + logf!("wrapper icd: dlopen failed: {}", + dlerror_str()); } else { - logf!(gndrm_obf::obf!( - "wrapper icd: driving {}", - w.to_string_lossy() - )); + logf!("wrapper icd: driving {}", + w.to_string_lossy()); negotiate_icd(h); match unsafe { resolve_gipa(h) } { Some(gipa) if proxy::device_prereqs(gipa, allow_ahb) => { opened = Some((h, gipa, true)); } - Some(_) => logf!(gndrm_obf::obf!( - "wrapper icd fails the proxy's prerequisite probe (see 'proxy prereq' above) — opening the system vulkan loader directly" - )), - None => logf!(gndrm_obf::obf!( - "wrapper icd exports no vkGetInstanceProcAddr — opening the system vulkan loader directly" - )), + Some(_) => logf!("wrapper icd fails the proxy's prerequisite probe (see 'proxy prereq' above) — opening the system vulkan loader directly"), + None => logf!("wrapper icd exports no vkGetInstanceProcAddr — opening the system vulkan loader directly"), } } } if opened.is_none() { let h = unsafe { libc::dlopen(SYSTEM_LOADER.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if h.is_null() { - log_reason!(gndrm_obf::obf!( - "dlopen system vulkan loader failed: {}", - dlerror_str() - )); + log_reason!("dlopen system vulkan loader failed: {}", + dlerror_str()); return; } let Some(gipa) = (unsafe { resolve_gipa(h) }) else { - log_reason!(gndrm_obf::obf!( - "system vulkan loader exports no vkGetInstanceProcAddr" - )); + log_reason!("system vulkan loader exports no vkGetInstanceProcAddr"); return; }; if !proxy::device_prereqs(gipa, allow_ahb) { - logi!(gndrm_obf::obf!("system vulkan driver fails the proxy's prerequisite probe (see 'proxy prereq' above) — not usable in GameScope mode")); + logi!("system vulkan driver fails the proxy's prerequisite probe (see 'proxy prereq' above) — not usable in GameScope mode"); return; } opened = Some((h, gipa, false)); @@ -424,15 +408,11 @@ fn try_system_driver() { DRIVER.handle = h; } if gamescope { - logi!(gndrm_obf::obf!( - "gamescope process: using system vulkan driver via WSI proxy [shim {}]", - SHIM_BUILD - )); + logi!("gamescope process: using system vulkan driver via WSI proxy [shim {}]", + SHIM_BUILD); } else { - logi!(gndrm_obf::obf!( - "guest process: using system vulkan driver via WSI proxy [shim {}]", - SHIM_BUILD - )); + logi!("guest process: using system vulkan driver via WSI proxy [shim {}]", + SHIM_BUILD); } } @@ -443,24 +423,18 @@ fn try_adrenotools() { let hooks = std::env::var("ADRENOTOOLS_HOOKS_PATH").ok().or_else(|| { std::env::var("PREFIX") .ok() - .map(|p| format!("{}", gndrm_obf::obf!("{p}/lib"))) + .map(|p| format!("{}", format_args!("{p}/lib"))) }); let Some(hooks) = hooks else { - logf!(gndrm_obf::obf!( - "ADRENOTOOLS_HOOKS_PATH unset and no PREFIX — skipping adrenotools" - )); + logf!("ADRENOTOOLS_HOOKS_PATH unset and no PREFIX — skipping adrenotools"); return; }; let Some(path) = path else { - logf!(gndrm_obf::obf!( - "ADRENOTOOLS_DRIVER_PATH unset — skipping adrenotools" - )); + logf!("ADRENOTOOLS_DRIVER_PATH unset — skipping adrenotools"); return; }; if !std::path::Path::new(&path).exists() { - logf!(gndrm_obf::obf!( - "ADRENOTOOLS_DRIVER_PATH {path} not accessible — skipping adrenotools" - )); + logf!("ADRENOTOOLS_DRIVER_PATH {path} not accessible — skipping adrenotools"); return; } let at = unsafe { @@ -470,10 +444,8 @@ fn try_adrenotools() { ) }; if at.is_null() { - logf!(gndrm_obf::obf!( - "dlopen libadrenotools.so failed: {}", - dlerror_str() - )); + logf!("dlopen libadrenotools.so failed: {}", + dlerror_str()); return; } let open_vk: Option = unsafe { @@ -485,16 +457,14 @@ fn try_adrenotools() { } }; let Some(open_vk) = open_vk else { - logf!(gndrm_obf::obf!( - "adrenotools_open_libvulkan not exported by libadrenotools.so" - )); + logf!("adrenotools_open_libvulkan not exported by libadrenotools.so"); return; }; // Patched copies live in a temp/ dir beside the driver (same layout the // wrapper creates); libadrenotools (re)generates them as needed. let tmp = format!( "{}", - gndrm_obf::obf!("{path}{}temp", if path.ends_with('/') { "" } else { "/" }) + format_args!("{path}{}temp", if path.ends_with('/') { "" } else { "/" }) ); let _ = std::fs::create_dir_all(&tmp); let c_tmp = CString::new(tmp).unwrap(); @@ -515,11 +485,9 @@ fn try_adrenotools() { ) }; if h.is_null() { - logf!(gndrm_obf::obf!( - "adrenotools_open_libvulkan failed for {}{}", + logf!("adrenotools_open_libvulkan failed for {}{}", path, - name.as_deref().unwrap_or("") - )); + name.as_deref().unwrap_or("")); return; } let exts = driver_instance_exts(h); @@ -527,32 +495,28 @@ fn try_adrenotools() { let has_headless = ext_list_has(&exts, c"VK_EXT_headless_surface"); let label = name.as_deref().unwrap_or(path.as_str()).to_string(); if has_wayland { - logf!(gndrm_obf::obf!( - "using adrenotools driver {label} (VK_KHR_wayland_surface present)" - )); + logf!("using adrenotools driver {label} (VK_KHR_wayland_surface present)"); unsafe { DRIVER.handle = h }; return; } // No wayland WSI (the whole adrenotools turnip family): present through // the WSI proxy (proxy.rs) on top of VK_EXT_headless_surface instead. if !has_headless || std::env::var_os("GN_VKSHIM_NO_PROXY").is_some() { - logf!(gndrm_obf::obf!( - "adrenotools driver {label} lacks VK_KHR_wayland_surface{} — not usable in GameScope mode", + logf!("adrenotools driver {label} lacks VK_KHR_wayland_surface{} — not usable in GameScope mode", if has_headless { " (GN_VKSHIM_NO_PROXY set)" } else { " and VK_EXT_headless_surface" - } - )); + }); return; } let Some(gipa) = (unsafe { resolve_gipa(h) }) else { - logf!(gndrm_obf::obf!("adrenotools driver {label} fails the proxy's prerequisite probe (see 'proxy prereq' above) — not usable in GameScope mode")); + logf!("adrenotools driver {label} fails the proxy's prerequisite probe (see 'proxy prereq' above) — not usable in GameScope mode"); return; }; let gipa_fn: GipaFn = gipa; if !proxy::device_prereqs(gipa_fn, false) { - logf!(gndrm_obf::obf!("adrenotools driver {label} fails the proxy's prerequisite probe (see 'proxy prereq' above) — not usable in GameScope mode")); + logf!("adrenotools driver {label} fails the proxy's prerequisite probe (see 'proxy prereq' above) — not usable in GameScope mode"); return; } proxy::set_real_gipa(gipa_fn); @@ -561,10 +525,8 @@ fn try_adrenotools() { DRIVER.proxy_active = true; DRIVER.handle = h; } - logf!(gndrm_obf::obf!( - "using adrenotools driver {label} via WSI proxy (headless surface + dma-buf export) [shim {}]", - SHIM_BUILD - )); + logf!("using adrenotools driver {label} via WSI proxy (headless surface + dma-buf export) [shim {}]", + SHIM_BUILD); } /// The real driver .so handle the shim opened (adrenotools- or freedreno- @@ -593,13 +555,9 @@ fn init_once() { let kgsl = kgsl_present(); if !kgsl || system_driver_forced() { if kgsl { - logi!(gndrm_obf::obf!( - "GN_VKSHIM_SYSTEM_DRIVER=1: using the system vulkan loader" - )); + logi!("GN_VKSHIM_SYSTEM_DRIVER=1: using the system vulkan loader"); } else { - logi!(gndrm_obf::obf!( - "no /dev/kgsl-3d0: using the system vulkan loader" - )); + logi!("no /dev/kgsl-3d0: using the system vulkan loader"); } try_system_driver(); } @@ -620,9 +578,7 @@ fn init_once() { .and_then(is_wrapper_driver) .unwrap_or(false) { - logf!(gndrm_obf::obf!( - "wrapper driver without adrenotools: trying the system vulkan driver" - )); + logf!("wrapper driver without adrenotools: trying the system vulkan driver"); try_system_driver(); } if unsafe { DRIVER.handle }.is_null() { @@ -632,25 +588,21 @@ fn init_once() { libc::RTLD_NOW | libc::RTLD_LOCAL, ) }; - logf!(gndrm_obf::obf!( - "falling back to payload freedreno {}", + logf!("falling back to payload freedreno {}", if h.is_null() { dlerror_str() } else { "loaded".into() - } - )); + }); unsafe { DRIVER.handle = h }; } } let handle = unsafe { DRIVER.handle }; if handle.is_null() { - logi!(gndrm_obf::obf!( - "no driver selected [shim {} {}]: every entry point resolves to NULL, so the loader skips this ICD and vkCreateInstance returns VK_ERROR_INCOMPATIBLE_DRIVER; reason: {}", + logi!("no driver selected [shim {} {}]: every entry point resolves to NULL, so the loader skips this ICD and vkCreateInstance returns VK_ERROR_INCOMPATIBLE_DRIVER; reason: {}", SHIM_BUILD, SHIM_GIT, - reason() - )); + reason()); return; } unsafe { @@ -665,9 +617,7 @@ fn init_once() { } }; if (*drv).gipa.is_none() { - logf!(gndrm_obf::obf!( - "driver exports no instance proc addr — ICD unusable" - )); + logf!("driver exports no instance proc addr — ICD unusable"); } } } @@ -727,7 +677,7 @@ pub unsafe extern "C" fn vk_icdGetInstanceProcAddr( if name == c"vkCreateInstance" { note_null_create_instance(&format!( "{}", - gndrm_obf::obf!("no driver selected ({})", reason()) + format_args!("no driver selected ({})", reason()) )); } return None; @@ -738,10 +688,8 @@ pub unsafe extern "C" fn vk_icdGetInstanceProcAddr( if out.is_none() && name == c"vkCreateInstance" { note_null_create_instance(&format!( "{}", - gndrm_obf::obf!( - "the driver's vkGetInstanceProcAddr returned NULL (proxy {})", - if proxy_active() { "active" } else { "inactive" } - ) + format_args!("the driver's vkGetInstanceProcAddr returned NULL (proxy {})", + if proxy_active() { "active" } else { "inactive" }) )); } out @@ -752,9 +700,7 @@ pub unsafe extern "C" fn vk_icdGetInstanceProcAddr( fn note_null_create_instance(why: &str) { static ONCE: Once = Once::new(); ONCE.call_once(|| { - logi!(gndrm_obf::obf!( - "vk_icdGetInstanceProcAddr(vkCreateInstance) -> NULL: {why}; the loader will report VK_ERROR_INCOMPATIBLE_DRIVER" - )); + logi!("vk_icdGetInstanceProcAddr(vkCreateInstance) -> NULL: {why}; the loader will report VK_ERROR_INCOMPATIBLE_DRIVER"); }); } diff --git a/icd_shim/src/lsfg/mod.rs b/icd_shim/src/lsfg/mod.rs index 68a0f5a..73e262d 100644 --- a/icd_shim/src/lsfg/mod.rs +++ b/icd_shim/src/lsfg/mod.rs @@ -132,28 +132,24 @@ pub fn open() -> Option { // generated frame. let handle = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if handle.is_null() { - crate::logf!(gndrm_obf::obf!( - "lsfg: cannot load {}: {}", + crate::logf!("lsfg: cannot load {}: {}", library, - dlerror_text() - )); + dlerror_text()); return None; } let abi = unsafe { resolve_one::(handle, "lsfg_engine_abi") }; let set_host = unsafe { resolve_one::(handle, "lsfg_engine_set_host") }; let (Some(abi), Some(set_host)) = (abi, set_host) else { - crate::logf!(gndrm_obf::obf!("lsfg: {} is not an engine", library)); + crate::logf!("lsfg: {} is not an engine", library); return None; }; let revision = unsafe { abi() }; if revision != EXPECTED_ABI { - crate::logf!(gndrm_obf::obf!( - "lsfg: {} speaks ABI {}, this build speaks {}", + crate::logf!("lsfg: {} speaks ABI {}, this build speaks {}", library, revision, - EXPECTED_ABI - )); + EXPECTED_ABI); return None; } @@ -165,7 +161,7 @@ pub fn open() -> Option { // Before any create: the engine loads its shader modules through here. unsafe { set_host(&gndrm_lsfg::HOST_OPS) }; let api = unsafe { Api::resolve(handle) }?; - crate::logf!(gndrm_obf::obf!("lsfg: engine ready ({})", library)); + crate::logf!("lsfg: engine ready ({})", library); Some(Engine { api, library }) } @@ -301,13 +297,11 @@ pub fn apply(config: gndrm_uapi::wire::LsfgConfig) { LIVE.refresh_mhz.store(config.refresh_mhz, Relaxed); let now = (config.enabled != 0, config.multiplier, config.fps_limit); if previous != now { - crate::logf!(gndrm_obf::obf!( - "lsfg: settings enabled={} multiplier={} source_cap={} refresh_hz={}", + crate::logf!("lsfg: settings enabled={} multiplier={} source_cap={} refresh_hz={}", now.0, now.1, now.2, - refresh_hz() - )); + refresh_hz()); } } @@ -387,11 +381,9 @@ pub fn apply_vsync(note: gndrm_uapi::wire::VsyncNote) { LIVE.vsync_period_ns.store(note.period_ns, Relaxed); LIVE.vsync_lead_ns.store(note.lead_ns, Relaxed); if had != note.period_ns { - crate::logf!(gndrm_obf::obf!( - "lsfg: panel grid period={}us lead={}us", + crate::logf!("lsfg: panel grid period={}us lead={}us", note.period_ns / 1000, - note.lead_ns / 1000 - )); + note.lead_ns / 1000); } } @@ -493,12 +485,12 @@ impl Session { // was captured at launch. if let Some(config) = from_daemon { if config.enabled == 0 || config.multiplier < 2 { - crate::logf!(gndrm_obf::obf!("lsfg: disabled by the app")); + crate::logf!("lsfg: disabled by the app"); return None; } } let Some(multiplier) = from_daemon.map(|s| s.multiplier) else { - crate::logf!(gndrm_obf::obf!("lsfg: the app has sent no settings")); + crate::logf!("lsfg: the app has sent no settings"); return None; }; if multiplier < 2 { @@ -512,22 +504,18 @@ impl Session { .map(|p| std::path::PathBuf::from(p.to_string_lossy().into_owned())) }); let Some(dll) = dll else { - crate::logf!(gndrm_obf::obf!("lsfg: no Lossless.dll path from the app")); + crate::logf!("lsfg: no Lossless.dll path from the app"); return None; }; if !dll.is_file() { - crate::logf!(gndrm_obf::obf!( - "lsfg: no Lossless.dll at {}; frame generation off", - dll.display() - )); + crate::logf!("lsfg: no Lossless.dll at {}; frame generation off", + dll.display()); return None; } let engine = open()?; if !unsafe { (engine.api.vkd_load)(instance, device, gipa) } { - crate::logf!(gndrm_obf::obf!( - "lsfg: dispatch load failed; frame generation off" - )); + crate::logf!("lsfg: dispatch load failed; frame generation off"); return None; } @@ -543,10 +531,8 @@ impl Session { }); let status = gndrm_lsfg::ensure_cache(&dll, &cache, fp16); if status != gndrm_lsfg::LsfgStatus::Ok { - crate::logf!(gndrm_obf::obf!( - "lsfg: shader cache unusable ({:?}); frame generation off", - status - )); + crate::logf!("lsfg: shader cache unusable ({:?}); frame generation off", + status); return None; } @@ -555,9 +541,7 @@ impl Session { }; let root = unsafe { (engine.api.create)(device, physical, cache_c.as_ptr()) }; if root.is_null() { - crate::logf!(gndrm_obf::obf!( - "lsfg: engine create failed; frame generation off" - )); + crate::logf!("lsfg: engine create failed; frame generation off"); return None; } @@ -574,14 +558,12 @@ impl Session { .unwrap_or(0.0); unsafe { (engine.api.configure)(root, multiplier, 0, flow, refresh) }; let (source, output) = grid(); - crate::logf!(gndrm_obf::obf!( - "lsfg: ready multiplier={} fp16={} source={} output={} cache={}", + crate::logf!("lsfg: ready multiplier={} fp16={} source={} output={} cache={}", multiplier, fp16, source, output, - cache.display() - )); + cache.display()); // Seed the live state with this session's decision: a push only arrives // when the user changes something, so `live()` must already be right. @@ -733,7 +715,7 @@ impl Session { if unsafe { create_image(device, &ici, std::ptr::null(), &mut image) } != crate::vk::VK_SUCCESS { - crate::logf!(gndrm_obf::obf!("lsfg: target image create failed")); + crate::logf!("lsfg: target image create failed"); return false; } @@ -769,13 +751,13 @@ impl Session { let mut mem: crate::vk::VkDeviceMemory = 0; if unsafe { alloc(device, &ai, std::ptr::null(), &mut mem) } != crate::vk::VK_SUCCESS { unsafe { destroy_image(device, image, std::ptr::null()) }; - crate::logf!(gndrm_obf::obf!("lsfg: target memory alloc failed")); + crate::logf!("lsfg: target memory alloc failed"); return false; } if unsafe { bind(device, image, mem, 0) } != crate::vk::VK_SUCCESS { unsafe { free(device, mem, std::ptr::null()) }; unsafe { destroy_image(device, image, std::ptr::null()) }; - crate::logf!(gndrm_obf::obf!("lsfg: target bind failed")); + crate::logf!("lsfg: target bind failed"); return false; } @@ -793,7 +775,7 @@ impl Session { { unsafe { free(device, mem, std::ptr::null()) }; unsafe { destroy_image(device, image, std::ptr::null()) }; - crate::logf!(gndrm_obf::obf!("lsfg: target view create failed")); + crate::logf!("lsfg: target view create failed"); return false; } @@ -806,13 +788,11 @@ impl Session { format, }); } - crate::logf!(gndrm_obf::obf!( - "lsfg: {} target(s) {}x{} fmt {}", + crate::logf!("lsfg: {} target(s) {}x{} fmt {}", self.targets.len(), width, height, - format - )); + format); true } diff --git a/icd_shim/src/placed.rs b/icd_shim/src/placed.rs index 0085261..2b93747 100644 --- a/icd_shim/src/placed.rs +++ b/icd_shim/src/placed.rs @@ -275,12 +275,10 @@ fn spoof_identity(p: &mut VkPhysicalDeviceProperties) { } static LOGGED: AtomicBool = AtomicBool::new(false); if !LOGGED.swap(true, Ordering::Relaxed) { - crate::logi!(gndrm_obf::obf!( - "proxy: guest sees device '{}' vendor {:#x} device {:#x}", + crate::logi!("proxy: guest sees device '{}' vendor {:#x} device {:#x}", unsafe { CStr::from_ptr(p.deviceName.as_ptr()) }.to_string_lossy(), p.vendorID, - p.deviceID - )); + p.deviceID); } } @@ -446,9 +444,7 @@ pub unsafe fn try_allocate( || unsafe { (api.allocate)(&desc, &mut ahb) } != 0 || ahb.is_null() { - crate::logf!(gndrm_obf::obf!( - "placed: AHB allocation of {size} bytes failed" - )); + crate::logf!("placed: AHB allocation of {size} bytes failed"); return None; } let mut props = AhbProperties { @@ -473,10 +469,8 @@ pub unsafe fn try_allocate( unsafe { *(*nh).data.as_ptr() } }; let (Some(chosen), VK_SUCCESS, true) = (chosen, pres, fd >= 0) else { - crate::logf!(gndrm_obf::obf!( - "placed: AHB unusable (props {pres}, types {:#x}, fd {fd}) for type {ty}", - props.memoryTypeBits - )); + crate::logf!("placed: AHB unusable (props {pres}, types {:#x}, fd {fd}) for type {ty}", + props.memoryTypeBits); unsafe { (api.release)(ahb) }; return None; }; @@ -493,11 +487,9 @@ pub unsafe fn try_allocate( }; let res = unsafe { alloc_mem(dev, &ai2, alloc, out) }; if LOG_N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::logf!(gndrm_obf::obf!( - "placed: AHB-backed alloc {} -> {} bytes type {ty}->{chosen} fd {fd}: {res}", + crate::logf!("placed: AHB-backed alloc {} -> {} bytes type {ty}->{chosen} fd {fd}: {res}", ai_ref.allocationSize, - props.allocationSize - )); + props.allocationSize); } if res != VK_SUCCESS { unsafe { (api.release)(ahb) }; @@ -565,10 +557,8 @@ pub unsafe extern "C" fn gn_vkMapMemory2KHR( }; let Some(b) = v.iter_mut().find(|b| b.mem == mi.memory) else { drop(v); - crate::logf!(gndrm_obf::obf!( - "placed: mem {:#x} is not AHB-backed; placed map refused", - mi.memory - )); + crate::logf!("placed: mem {:#x} is not AHB-backed; placed map refused", + mi.memory); return VK_ERROR_MEMORY_MAP_FAILED; }; let size = if mi.size == WHOLE_SIZE { @@ -588,11 +578,9 @@ pub unsafe extern "C" fn gn_vkMapMemory2KHR( ) }; if r != want { - crate::logf!(gndrm_obf::obf!( - "placed: mmap of AHB fd {} at {want:p} failed: {}", + crate::logf!("placed: mmap of AHB fd {} at {want:p} failed: {}", b.fd, - std::io::Error::last_os_error() - )); + std::io::Error::last_os_error()); return VK_ERROR_MEMORY_MAP_FAILED; } b.mapped = want as usize; diff --git a/icd_shim/src/present.rs b/icd_shim/src/present.rs index c974053..3028337 100644 --- a/icd_shim/src/present.rs +++ b/icd_shim/src/present.rs @@ -297,13 +297,11 @@ fn note_outcome(id: u64, what: &str, t0: std::time::Instant) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 8 || n.is_multiple_of(600) { - crate::logf!(gndrm_obf::obf!( - "present wait #{}: id={} {} after {} us", + crate::logf!("present wait #{}: id={} {} after {} us", n, id, what, - t0.elapsed().as_micros() - )); + t0.elapsed().as_micros()); } } diff --git a/icd_shim/src/proxy.rs b/icd_shim/src/proxy.rs index 4b73241..8de81d0 100644 --- a/icd_shim/src/proxy.rs +++ b/icd_shim/src/proxy.rs @@ -100,14 +100,11 @@ fn ring_dump(reason: &str) { let Ok(r) = RING.lock() else { return; }; - crate::logf!(gndrm_obf::obf!( - "x11 stall ring ({reason}): last {} entry points:", - r.len() - )); + crate::logf!("x11 stall ring ({reason}): last {} entry points:", + r.len()); let n = r.len(); for (i, e) in r.iter().enumerate() { - crate::logf!(gndrm_obf::obf!( - "x11 stall ring [{}/{}] tid={} {} args={:x} {:x} {:x} {:x} {:x}", + crate::logf!("x11 stall ring [{}/{}] tid={} {} args={:x} {:x} {:x} {:x} {:x}", i + 1, n, e.tid, @@ -116,8 +113,7 @@ fn ring_dump(reason: &str) { e.args[1], e.args[2], e.args[3], - e.args[4] - )); + e.args[4]); } } static LOG_COMMIT: AtomicUsize = AtomicUsize::new(0); @@ -303,8 +299,7 @@ fn wsi_hb() { { return; } - crate::logf!(gndrm_obf::obf!( - "proxy hb: fmt={} fmt2={} caps={} caps2={} pmodes={} create={} destroy={} images={} acq={} present={}", + crate::logf!("proxy hb: fmt={} fmt2={} caps={} caps2={} pmodes={} create={} destroy={} images={} acq={} present={}", HB_FMT.load(Ordering::Relaxed), HB_FMT2.load(Ordering::Relaxed), HB_CAPS.load(Ordering::Relaxed), @@ -314,8 +309,7 @@ fn wsi_hb() { HB_DESTROY.load(Ordering::Relaxed), HB_IMAGES.load(Ordering::Relaxed), HB_ACQ.load(Ordering::Relaxed), - HB_PRESENT.load(Ordering::Relaxed), - )); + HB_PRESENT.load(Ordering::Relaxed),); } const RATE_EVERY: Duration = Duration::from_secs(1); const IDLE_EVERY: Duration = Duration::from_secs(2); @@ -376,8 +370,7 @@ fn slot_flags(sc: *mut GnSwapchain) -> String { drop(g); format!( "{}", - gndrm_obf::obf!( - "acq={} pres={} rel={} commit={} starved={} in_flight={in_flight} slots=[{}] acqus=[n={} sum={} max={} nz={} ge8={} ge16={}] presiv=[n={} sum={} min={} max={} ge16667={} ge33333={}] cap=[fps={} notes={} gate_holds={} gate_us={} gate_avg_us={} gate_max_us={} acq_fps={:.2}]", + format_args!("acq={} pres={} rel={} commit={} starved={} in_flight={in_flight} slots=[{}] acqus=[n={} sum={} max={} nz={} ge8={} ge16={}] presiv=[n={} sum={} min={} max={} ge16667={} ge33333={}] cap=[fps={} notes={} gate_holds={} gate_us={} gate_avg_us={} gate_max_us={} acq_fps={:.2}]", N_ACQ.load(Ordering::Relaxed), N_PRES.load(Ordering::Relaxed), N_REL.load(Ordering::Relaxed), @@ -402,8 +395,7 @@ fn slot_flags(sc: *mut GnSwapchain) -> String { GATE_HOLD_SUM_US.load(Ordering::Relaxed), gate_hold_avg_us(), GATE_HOLD_MAX_US.load(Ordering::Relaxed), - acq_fps(), - ) + acq_fps(),) ) } @@ -411,8 +403,7 @@ fn slot_flags(sc: *mut GnSwapchain) -> String { fn counters() -> String { format!( "{}", - gndrm_obf::obf!( - "acq={} pres={} rel={} commit={} starved={} maint1=[fences={} released={}] acqus=[n={} sum={} max={} nz={} ge8={} ge16={}] presiv=[n={} sum={} min={} max={} ge16667={} ge33333={}] cap=[fps={} notes={} gate_holds={} gate_us={} gate_avg_us={} gate_max_us={} acq_fps={:.2}]", + format_args!("acq={} pres={} rel={} commit={} starved={} maint1=[fences={} released={}] acqus=[n={} sum={} max={} nz={} ge8={} ge16={}] presiv=[n={} sum={} min={} max={} ge16667={} ge33333={}] cap=[fps={} notes={} gate_holds={} gate_us={} gate_avg_us={} gate_max_us={} acq_fps={:.2}]", N_ACQ.load(Ordering::Relaxed), N_PRES.load(Ordering::Relaxed), N_REL.load(Ordering::Relaxed), @@ -438,8 +429,7 @@ fn counters() -> String { GATE_HOLD_SUM_US.load(Ordering::Relaxed), gate_hold_avg_us(), GATE_HOLD_MAX_US.load(Ordering::Relaxed), - acq_fps(), - ) + acq_fps(),) ) } @@ -459,7 +449,7 @@ extern "C" fn gn_wl_log(fmt: *const c_char, ap: *mut c_void) { let mut buf = [0 as c_char; 512]; unsafe { wlproto::vsnprintf(buf.as_mut_ptr(), buf.len(), fmt, ap) }; let msg = unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy(); - crate::logf!(gndrm_obf::obf!("libwayland: {}", msg.trim_end())); + crate::logf!("libwayland: {}", msg.trim_end()); } // dma-buf sync ioctl (same values as the daemon's EGL presenter). @@ -593,30 +583,26 @@ unsafe fn x11_present_slot(sc: *mut GnSwapchain, s: *mut GnSlot, idx: i32) -> bo unsafe { (*sc).x11_trace = trace_n + 1 }; let (a0, nz, px) = unsafe { slot_signature(sc, s) }; let acq = unsafe { (*s).acq_seq }; - crate::logf!(gndrm_obf::obf!( - "x11 trace {trace_n}: sc={sc:?} idx={idx} acq#{acq} {}x{} alpha0={a0}/{} nz={nz} px0=({},{},{},{})", + crate::logf!("x11 trace {trace_n}: sc={sc:?} idx={idx} acq#{acq} {}x{} alpha0={a0}/{} nz={nz} px0=({},{},{},{})", unsafe { (*sc).extent.width }, unsafe { (*sc).extent.height }, unsafe { (*sc).extent.width as usize * (*sc).extent.height as usize }, px[0], px[1], px[2], - px[3] - )); + px[3]); // Bounded one-shot two-view probe (first presents): the shim's own // linear mmap above vs the driver's own mapping of the same dma-buf // (vkMapMemory of the slot's imported memory). They only differ if the // image's real layout/stride is not what the shim advertises/reads. if trace_n < X11_VIEW_N { if let Some((va0, vnz, vpx)) = unsafe { slot_mem_signature(sc, s) } { - crate::logf!(gndrm_obf::obf!( - "x11 view {trace_n}: idx={idx} driver(mapmem) alpha0={va0}/{} nz={vnz} px0=({},{},{},{})", + crate::logf!("x11 view {trace_n}: idx={idx} driver(mapmem) alpha0={va0}/{} nz={vnz} px0=({},{},{},{})", unsafe { (*sc).extent.width as usize * (*sc).extent.height as usize }, vpx[0], vpx[1], vpx[2], - vpx[3] - )); + vpx[3]); } } } @@ -632,9 +618,7 @@ unsafe fn x11_present_slot(sc: *mut GnSwapchain, s: *mut GnSlot, idx: i32) -> bo } { Some(p) => unsafe { (*s).xpix = p }, None => { - crate::logf!(gndrm_obf::obf!( - "x11: slot {idx} has no pixmap - frame dropped" - )); + crate::logf!("x11: slot {idx} has no pixmap - frame dropped"); return false; } } @@ -649,19 +633,15 @@ unsafe fn x11_present_slot(sc: *mut GnSwapchain, s: *mut GnSlot, idx: i32) -> bo Some(serial) => { let n = LOG_COMMIT.fetch_add(1, Ordering::Relaxed); if n < LOG_FIRST_N || n.is_multiple_of(120) { - crate::logf!(gndrm_obf::obf!( - "x11 present: sc={sc:?} idx={idx} pix={} serial={serial} {}x{} {}", + crate::logf!("x11 present: sc={sc:?} idx={idx} pix={} serial={serial} {}x{} {}", unsafe { (*s).xpix }, unsafe { (*sc).extent.width }, unsafe { (*sc).extent.height }, - counters() - )); + counters()); } } None => { - crate::logf!(gndrm_obf::obf!( - "x11: slot {idx} present refused - frame dropped" - )); + crate::logf!("x11: slot {idx} present refused - frame dropped"); return false; } } @@ -705,7 +685,7 @@ unsafe fn x11_reap(sc: *mut GnSwapchain) { if logging { N_REL.fetch_add(1, Ordering::Relaxed); if rate_ok(&RATE_REL, RATE_EVERY) { - crate::logf!(gndrm_obf::obf!("x11 release: slot={i} {}", slot_flags(sc))); + crate::logf!("x11 release: slot={i} {}", slot_flags(sc)); } } } @@ -865,7 +845,7 @@ unsafe fn lsfg_destinations(sc: *mut GnSwapchain, count: usize) -> bool { let res = unsafe { slot_init_with_usage(sc, (*sc).slots.as_mut_ptr().add(index), GEN_USAGE) }; if res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!("lsfg: destination slot init failed: {res}")); + crate::logf!("lsfg: destination slot init failed: {res}"); // The half-made slot must not stay in the table: every later pass over // the slots would take it for a real one. And no further growth: the // allocator refused once, so the set stays at what it has. @@ -1723,16 +1703,14 @@ unsafe fn lsfg_generate(sc: *mut GnSwapchain, src_idx: i32) -> bool { .fetch_add(1, std::sync::atomic::Ordering::Relaxed) .is_multiple_of(600) { - crate::logf!(gndrm_obf::obf!( - "lsfg: generated {} (skips {}, queued {}, short: free {} plan {}, late {}, released {})", + crate::logf!("lsfg: generated {} (skips {}, queued {}, short: free {} plan {}, late {}, released {})", GEN_COMMITS.load(std::sync::atomic::Ordering::Relaxed), GEN_SKIPS.load(std::sync::atomic::Ordering::Relaxed), GEN_QUEUED.load(std::sync::atomic::Ordering::Relaxed), GEN_SHORT_FREE.load(std::sync::atomic::Ordering::Relaxed), GEN_SHORT_PLAN.load(std::sync::atomic::Ordering::Relaxed), GEN_LATE.load(std::sync::atomic::Ordering::Relaxed), - GEN_RELEASES.load(std::sync::atomic::Ordering::Relaxed) - )); + GEN_RELEASES.load(std::sync::atomic::Ordering::Relaxed)); } queued } @@ -1949,10 +1927,8 @@ fn pop_job(sc: *mut GnSwapchain) -> i32 { // presenting: the fence fires when the server drops the pixmap. unsafe { x11_reap(sc) }; if rate_ok(&RATE_IDLE, IDLE_EVERY) { - crate::logf!(gndrm_obf::obf!( - "gn-vkshim idle: present worker has no work {}", - slot_flags(sc) - )); + crate::logf!("gn-vkshim idle: present worker has no work {}", + slot_flags(sc)); } g = unsafe { (*sc).shared.lock().unwrap() }; } @@ -2027,22 +2003,18 @@ unsafe fn bind_window_at_first_commit(sc: *mut GnSwapchain) { if (*surf).window_provisional { let resolved = crate::x11::resolve_override_target((*surf).named_window); if resolved.window != (*surf).window { - crate::logf!(gndrm_obf::obf!( - "override: XID {:#x} re-resolved at first commit: {:#x} -> {:#x}", + crate::logf!("override: XID {:#x} re-resolved at first commit: {:#x} -> {:#x}", (*surf).named_window, (*surf).window, - resolved.window - )); + resolved.window); } (*surf).window = resolved.window; (*surf).window_provisional = resolved.provisional; } // Single xwayland server (--xwayland-count 1) is always id 0. wlproto::swapchain_override_window_content((*surf).swapchain_obj, 0, (*surf).window); - crate::logf!(gndrm_obf::obf!( - "override: swapchain {sc:?} binds surface {surf:?} to XID {:#x} at its first commit", - (*surf).window - )); + crate::logf!("override: swapchain {sc:?} binds surface {surf:?} to XID {:#x} at its first commit", + (*surf).window); } } @@ -2136,9 +2108,7 @@ unsafe fn commit_real(sc: *mut GnSwapchain, idx: i32, fence_ms: u128) { x11_reap(sc); } else { if !X11_DROP_LOGGED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "x11 route: present unavailable - frames dropped, slots kept free (guest keeps running)" - )); + crate::logf!("x11 route: present unavailable - frames dropped, slots kept free (guest keeps running)"); } let _g = (*sc).shared.lock().unwrap(); (*s).in_flight = false; @@ -2151,9 +2121,7 @@ unsafe fn commit_real(sc: *mut GnSwapchain, idx: i32, fence_ms: u128) { (*s).buf = slot_make_buffer(sc, s); } if (*s).buf.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy: wl_buffer creation failed — dropping frame" - )); + crate::logf!("proxy: wl_buffer creation failed — dropping frame"); crate::present::cancel_feedback(feedback_token); let _g = (*sc).shared.lock().unwrap(); (*s).in_flight = false; @@ -2214,14 +2182,12 @@ unsafe fn commit_real(sc: *mut GnSwapchain, idx: i32, fence_ms: u128) { let n = LOG_COMMIT.fetch_add(1, Ordering::Relaxed); let done = N_COMMIT_OK.fetch_add(1, Ordering::Relaxed); if n < LOG_FIRST_N || n.is_multiple_of(120) || fence_ms >= 100 { - crate::logf!(gndrm_obf::obf!( - "proxy commit: sc={sc:?} idx={idx} {}x{} flush_rc={flush_rc} dpy_err={} fence={fence_ms}ms commit={commit_ms}ms #{} {}", + crate::logf!("proxy commit: sc={sc:?} idx={idx} {}x{} flush_rc={flush_rc} dpy_err={} fence={fence_ms}ms commit={commit_ms}ms #{} {}", (*sc).extent.width, (*sc).extent.height, wlproto::wl_display_get_error((*(*sc).surf).dpy), done + 1, - counters(), - )); + counters(),); } } } @@ -2244,8 +2210,7 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( if let Some(config) = crate::scanout::lsfg_config() { crate::lsfg::apply(config); } - crate::logf!(gndrm_obf::obf!( - "proxy swapchain create: device={device:?} surface={:#x} {}x{} fmt={} cs={} min={} mode={} old={:#x} -> gd={:?} surf={:?}", + crate::logf!("proxy swapchain create: device={device:?} surface={:#x} {}x{} fmt={} cs={} min={} mode={} old={:#x} -> gd={:?} surf={:?}", ci.surface, ci.imageExtent.width, ci.imageExtent.height, @@ -2255,8 +2220,7 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( ci.presentMode, ci.oldSwapchain as usize, gd, - surf - )); + surf); if gd.is_null() || surf.is_null() { return VK_ERROR_INITIALIZATION_FAILED; } @@ -2270,17 +2234,13 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( let scaling = unsafe { crate::maint1::create_scaling(ci.pNext) }; let deferred = ci.flags & crate::maint1::CREATE_DEFERRED_MEMORY_ALLOCATION_BIT != 0; if modes.is_some() || scaling.is_some() || deferred { - crate::logf!(gndrm_obf::obf!( - "proxy swapchain create: maintenance1 modes={modes:?} scaling={scaling:?} deferred_alloc={deferred}" - )); + crate::logf!("proxy swapchain create: maintenance1 modes={modes:?} scaling={scaling:?} deferred_alloc={deferred}"); } } let fourcc = vk_format_to_fourcc(ci.imageFormat); if fourcc == 0 { - crate::logf!(gndrm_obf::obf!( - "proxy: unsupported swapchain format {}", - ci.imageFormat - )); + crate::logf!("proxy: unsupported swapchain format {}", + ci.imageFormat); return VK_ERROR_FORMAT_NOT_SUPPORTED; } // Only the scan-out pool's own layout can be served end to end (see @@ -2290,13 +2250,11 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( // colours. let layout = crate::scanout::layout(); if !swapchain_format_allowed(ci.imageFormat, layout, allows_other_eight_bit(layout)) { - crate::logf!(gndrm_obf::obf!( - "proxy: refusing swapchain format {} cs={} (scan-out pool is format {}; set {} to opt in)", + crate::logf!("proxy: refusing swapchain format {} cs={} (scan-out pool is format {}; set {} to opt in)", ci.imageFormat, ci.imageColorSpace, scanout_swapchain_format(layout), - other_eight_bit_env(layout) - )); + other_eight_bit_env(layout)); return VK_ERROR_FORMAT_NOT_SUPPORTED; } // Declare what this swapchain is to gamescope. The colourspace is the load @@ -2310,11 +2268,9 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( let colorspace = ci.imageColorSpace; let scobj = unsafe { (*surf).swapchain_obj }; if scobj.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy: no gamescope_swapchain to declare format {} colourspace {} on", + crate::logf!("proxy: no gamescope_swapchain to declare format {} colourspace {} on", ci.imageFormat, - colorspace - )); + colorspace); } else { let engine = c"gn-shim"; let _sg = SEND_LOCK.lock().unwrap(); @@ -2331,11 +2287,9 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( ); wlproto::wl_display_flush((*surf).dpy); } - crate::logf!(gndrm_obf::obf!( - "proxy: declared swapchain format {} colourspace {} to gamescope", + crate::logf!("proxy: declared swapchain format {} colourspace {} to gamescope", ci.imageFormat, - colorspace - )); + colorspace); } } // The container's mode, else the guest's, is the one this swapchain keeps @@ -2368,11 +2322,9 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( n_slots = n_slots.max(SC_FRAMEGEN_IMAGES.min(ceiling.max(2))); } if strict_count { - crate::logi!(gndrm_obf::obf!( - "proxy swapchain create: strict image count: requested {} gives {n_slots} images, mode={}", + crate::logi!("proxy swapchain create: strict image count: requested {} gives {n_slots} images, mode={}", ci.minImageCount, - ci.presentMode - )); + ci.presentMode); } let mut sc = Box::new(GnSwapchain { surf, @@ -2446,7 +2398,7 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( for j in (0..=inited).rev() { unsafe { slot_release(scp, sc.slots.as_mut_ptr().add(j)) }; } - crate::logf!(gndrm_obf::obf!("proxy: slot init failed: {res}")); + crate::logf!("proxy: slot init failed: {res}"); return res; } } @@ -2486,12 +2438,10 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( } sc.spare_slots = hidden as u32; if hidden != 0 { - crate::logi!(gndrm_obf::obf!( - "proxy swapchain create: strict image count: {} images, {} of {} ring slot(s) for hidden copies", + crate::logi!("proxy swapchain create: strict image count: {} images, {} of {} ring slot(s) for hidden copies", n_slots, hidden, - ring - )); + ring); } // What the guest was told the surface can be, next to what the slot images @@ -2501,8 +2451,7 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( if let Ok(adv) = ADVERTISED_CAPS.lock() { if let Some(a) = *adv { let stride = sc.slots.first().map_or(0, |s| s.stride); - crate::logf!(gndrm_obf::obf!( - "x11 caps vs slot: advertised current={}x{} min={}x{} max={}x{} -> image {}x{} stride={} slots={}", + crate::logf!("x11 caps vs slot: advertised current={}x{} min={}x{} max={}x{} -> image {}x{} stride={} slots={}", a.current.0, a.current.1, a.min.0, @@ -2512,18 +2461,15 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( ci.imageExtent.width, ci.imageExtent.height, stride, - sc.slots.len() - )); + sc.slots.len()); } } } let sc_addr = scp as usize; if !unsafe { (*(*scp).surf).x11 }.is_null() { - crate::logf!(gndrm_obf::obf!( - "X11 present engages: swapchain {scp:?} {}x{} presents through DRI3 + Present", + crate::logf!("X11 present engages: swapchain {scp:?} {}x{} presents through DRI3 + Present", ci.imageExtent.width, - ci.imageExtent.height - )); + ci.imageExtent.height); } let worker = std::thread::Builder::new() .name("gn-present".into()) @@ -2545,8 +2491,7 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( } unsafe { *out = sc as usize as VkSwapchainKHR; - crate::logf!(gndrm_obf::obf!( - "proxy swapchain {:?}: {}x{} fmt {} -> fourcc {:#x}, {} images; requested usage={:#x} minImages={} presentMode={} compositeAlpha={:#x} colorspace={} clipped={} tiling=LINEAR effective_mode={} gamescope_mode={}", + crate::logf!("proxy swapchain {:?}: {}x{} fmt {} -> fourcc {:#x}, {} images; requested usage={:#x} minImages={} presentMode={} compositeAlpha={:#x} colorspace={} clipped={} tiling=LINEAR effective_mode={} gamescope_mode={}", sc, (*sc).extent.width, (*sc).extent.height, @@ -2560,8 +2505,7 @@ unsafe extern "C" fn gn_vkCreateSwapchainKHR( ci.imageColorSpace, ci.clipped, mode, - gamescope_present_mode(live_present_mode(sc)) - )); + gamescope_present_mode(live_present_mode(sc))); } VK_SUCCESS } @@ -2592,7 +2536,7 @@ unsafe extern "C" fn gn_vkGetSwapchainImagesKHR( let hs: Vec = (0..n) .map(|i| format!("{:#x}", *images.add(i) as usize)) .collect(); - crate::logf!(gndrm_obf::obf!("x11 scimages: sc={sc:?} n={n} imgs={hs:?}")); + crate::logf!("x11 scimages: sc={sc:?} n={n} imgs={hs:?}"); } *count = n as u32; if n < n_slots { @@ -2652,13 +2596,11 @@ unsafe extern "C" fn gn_vkDestroySwapchainKHR( // One line per destroyed swapchain: a swapchain that goes away while the // guest keeps rendering is otherwise invisible, and nothing downstream // can tell it from a guest that simply stopped presenting. - crate::logf!(gndrm_obf::obf!( - "proxy swapchain destroyed: sc={sc:?} {}x{} presents={} commits={}", + crate::logf!("proxy swapchain destroyed: sc={sc:?} {}x{} presents={} commits={}", unsafe { (*sc).extent.width }, unsafe { (*sc).extent.height }, N_PRES.load(Ordering::Relaxed), - N_COMMIT_OK.load(Ordering::Relaxed) - )); + N_COMMIT_OK.load(Ordering::Relaxed)); } if let Some(worker) = unsafe { (*sc).worker.take() } { let _ = worker.join(); @@ -2726,11 +2668,9 @@ unsafe fn acquire_take_free(sc: *mut GnSwapchain, idx: &mut i32) { (*s).acq_seq = seq as u64; } if seq < X11_TRACE_N { - crate::logf!(gndrm_obf::obf!( - "x11 acquire {seq}: sc={sc:?} idx={} img={:#x}", + crate::logf!("x11 acquire {seq}: sc={sc:?} idx={} img={:#x}", *idx, - unsafe { (*s).image } as usize - )); + unsafe { (*s).image } as usize); } return; } @@ -2866,10 +2806,8 @@ unsafe fn gn_acquire_common( // a wl_buffer.release that never comes. N_STARVE.fetch_add(1, Ordering::Relaxed); if rate_ok(&RATE_STALL, RATE_EVERY) { - crate::logf!(gndrm_obf::obf!( - "gn-vkshim stall: acquire found no free slot (timeout={timeout}) {}", - slot_flags(sc) - )); + crate::logf!("gn-vkshim stall: acquire found no free slot (timeout={timeout}) {}", + slot_flags(sc)); } return if timeout == 0 { VK_NOT_READY @@ -2938,9 +2876,7 @@ unsafe fn gn_acquire_common( } let n = LOG_ACQ.fetch_add(1, Ordering::Relaxed); if n < LOG_FIRST_N || n.is_multiple_of(120) || acq_ms >= 100 { - crate::logf!(gndrm_obf::obf!( - "proxy acquire: sc={sc:?} slot={idx} wait={acq_ms}ms" - )); + crate::logf!("proxy acquire: sc={sc:?} slot={idx} wait={acq_ms}ms"); } VK_SUCCESS } @@ -3215,11 +3151,9 @@ fn log_present_chain_once(p_next: *const c_void, id: u64) { types.push(node.s_type); head = node.p_next.cast::(); } - crate::logf!(gndrm_obf::obf!( - "proxy present: first pNext chain sTypes={:?} present_id={}", + crate::logf!("proxy present: first pNext chain sTypes={:?} present_id={}", types, - id - )); + id); } /// Logged once per process: a maintenance1 mode switch the shim does not serve. @@ -3272,10 +3206,8 @@ unsafe extern "C" fn gn_vkReleaseSwapchainImagesKHR( } if crate::vkshim_enabled() { N_RELEASED_IMAGES.fetch_add(freed, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "proxy release images: sc={sc:?} asked={:?} freed={freed}", - indices - )); + crate::logf!("proxy release images: sc={sc:?} asked={:?} freed={freed}", + indices); } VK_SUCCESS } @@ -3309,11 +3241,9 @@ unsafe extern "C" fn gn_vkQueuePresentKHR(queue: VkQueue, pi: *const VkPresentIn loud("present.queue_miss", || { format!( "{}", - gndrm_obf::obf!( - "proxy: gn_vkQueuePresentKHR QUEUE MISS q={:#x} {}", + format_args!("proxy: gn_vkQueuePresentKHR QUEUE MISS q={:#x} {}", queue as usize, - unsafe { handle_note(false, queue as usize, first, n) } - ) + unsafe { handle_note(false, queue as usize, first, n) }) ) }); gd = G.lock().unwrap().devices; @@ -3322,10 +3252,8 @@ unsafe extern "C" fn gn_vkQueuePresentKHR(queue: VkQueue, pi: *const VkPresentIn loud("present.device_miss", || { format!( "{}", - gndrm_obf::obf!( - "proxy: gn_vkQueuePresentKHR DEVICE MISS q={:#x} — no device wrapper at all", - queue as usize - ) + format_args!("proxy: gn_vkQueuePresentKHR DEVICE MISS q={:#x} — no device wrapper at all", + queue as usize) ) }); return VK_ERROR_INITIALIZATION_FAILED; @@ -3363,10 +3291,8 @@ unsafe extern "C" fn gn_vkQueuePresentKHR(queue: VkQueue, pi: *const VkPresentIn if mode != unsafe { (*sc).requested_mode } && !MODE_SWITCH_NOTED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "proxy present: maintenance1 mode switch to {mode} requested (swapchain created with {}); not served, mode kept", - unsafe { (*sc).requested_mode } - )); + crate::logf!("proxy present: maintenance1 mode switch to {mode} requested (swapchain created with {}); not served, mode kept", + unsafe { (*sc).requested_mode }); } } // A slot presented again while it still carries an armed id: that @@ -3462,9 +3388,7 @@ unsafe extern "C" fn gn_vkQueuePresentKHR(queue: VkQueue, pi: *const VkPresentIn if res == VK_SUCCESS && guest_fence != 0 { let r2 = unsafe { (*gd).f.submit.unwrap()(real_q, 1, &fence_si, guest_fence) }; if r2 != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!( - "proxy: present fence submit failed: {r2}" - )); + crate::logf!("proxy: present fence submit failed: {r2}"); } else if crate::vkshim_enabled() { N_PRESENT_FENCE.fetch_add(1, Ordering::Relaxed); } @@ -3472,7 +3396,7 @@ unsafe extern "C" fn gn_vkQueuePresentKHR(queue: VkQueue, pi: *const VkPresentIn res }; if res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!("proxy: present wait submit failed: {res}")); + crate::logf!("proxy: present wait submit failed: {res}"); let hidden = unsafe { core::mem::replace(&mut (*slot).spare, NO_SPARE) }; if hidden != NO_SPARE { unsafe { spare_unclaim(sc, hidden as usize) }; @@ -3484,19 +3408,15 @@ unsafe extern "C" fn gn_vkQueuePresentKHR(queue: VkQueue, pi: *const VkPresentIn } unsafe { present_dispatch(sc, slot, indices[i] as i32) }; if LOG_PRESENT.fetch_add(1, Ordering::Relaxed) < LOG_FIRST_N { - crate::logf!(gndrm_obf::obf!( - "proxy present: sc={sc:?} idx={} {}", + crate::logf!("proxy present: sc={sc:?} idx={} {}", indices[i], - counters() - )); + counters()); } if LOUD_PRESENT.fetch_add(1, Ordering::Relaxed) < 4 { - crate::logf!(gndrm_obf::obf!( - "proxy: present flow pid={} sc={sc:?} idx={} {}", + crate::logf!("proxy: present flow pid={} sc={sc:?} idx={} {}", std::process::id(), indices[i], - counters() - )); + counters()); } } VK_SUCCESS @@ -3537,11 +3457,9 @@ unsafe fn submit_impl( loud("submit.miss", || { format!( "{}", - gndrm_obf::obf!( - "proxy: vkQueueSubmit QUEUE MISS q={:#x} {} — submitting guest CBs directly", + format_args!("proxy: vkQueueSubmit QUEUE MISS q={:#x} {} — submitting guest CBs directly", queue as usize, - unsafe { handle_note(false, queue as usize, first, n) } - ) + unsafe { handle_note(false, queue as usize, first, n) }) ) }); return VK_ERROR_INITIALIZATION_FAILED; @@ -3560,23 +3478,19 @@ unsafe fn submit_impl( ]; unsafe { translate_nested("vkQueueSubmit", &mut args, &mut stage) }; let seq = LOG_SUBMIT.fetch_add(1, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "proxy submit #{seq}: n={count} q={queue:?} entries={:?} fence={fence:?}", + crate::logf!("proxy submit #{seq}: n={count} q={queue:?} entries={:?} fence={fence:?}", unsafe { slice_or_empty(submits, count as usize) } .iter() .map(|s| s.commandBufferCount) - .collect::>() - )); + .collect::>()); if LOUD_SUBMIT.fetch_add(1, Ordering::Relaxed) < 4 { - crate::logf!(gndrm_obf::obf!( - "proxy: submit flow #{seq} pid={} q={queue:?} real_q={:?} n={count} ncmd={:?}", + crate::logf!("proxy: submit flow #{seq} pid={} q={queue:?} real_q={:?} n={count} ncmd={:?}", std::process::id(), unsafe { (*gq).real }, unsafe { slice_or_empty(submits, count as usize) } .iter() .map(|s| s.commandBufferCount) - .collect::>() - )); + .collect::>()); } let _submit = SUBMIT_LOCK.lock().unwrap_or_else(|e| e.into_inner()); unsafe { (*gd).f.submit.unwrap()((*gq).real, count, args[2] as *const VkSubmitInfo, fence) } @@ -3638,15 +3552,13 @@ unsafe extern "C" fn gn_vkWaitSemaphores( .and_then(|g| g.clone()) .map(|(s, v)| format!("{s}@{v}")) .unwrap_or_else(|| String::from("")); - crate::logf!(gndrm_obf::obf!( - "proxy wait: n={n} want=[{wants}] last_signalled={last} timeout={timeout}" - )); + crate::logf!("proxy wait: n={n} want=[{wants}] last_signalled={last} timeout={timeout}"); } let t0 = Instant::now(); let res = unsafe { f((*gd).real, wi, timeout) }; let ms = t0.elapsed().as_millis(); if ms >= 1000 { - crate::logf!(gndrm_obf::obf!("proxy wait done: res={res} after={ms}ms")); + crate::logf!("proxy wait done: res={res} after={ms}ms"); } res } @@ -3682,11 +3594,9 @@ unsafe fn submit2_impl( loud("submit2.miss", || { format!( "{}", - gndrm_obf::obf!( - "proxy: vkQueueSubmit2 QUEUE MISS q={:#x} {} — batch dropped", + format_args!("proxy: vkQueueSubmit2 QUEUE MISS q={:#x} {} — batch dropped", queue as usize, - unsafe { handle_note(false, queue as usize, first, n) } - ) + unsafe { handle_note(false, queue as usize, first, n) }) ) }); return VK_ERROR_INITIALIZATION_FAILED; @@ -3712,15 +3622,13 @@ unsafe fn submit2_impl( unsafe { translate_nested("vkQueueSubmit2", &mut args, &mut stage) }; let translated = args[2] as *const VkSubmitInfo2; if LOUD_SUBMIT2.fetch_add(1, Ordering::Relaxed) < 4 { - crate::logf!(gndrm_obf::obf!( - "proxy: submit2 flow pid={} q={queue:?} real_q={:?} n={count} ncmd={:?}", + crate::logf!("proxy: submit2 flow pid={} q={queue:?} real_q={:?} n={count} ncmd={:?}", std::process::id(), unsafe { (*gq).real }, unsafe { slice_or_empty(submits, count as usize) } .iter() .map(|s| s.commandBufferInfoCount) - .collect::>() - )); + .collect::>()); } { // Every submit, terse: the faulting call is the last line before the @@ -3743,7 +3651,7 @@ unsafe fn submit2_impl( for s in ws.iter().take(3) { sems.push(format!( "{}", - gndrm_obf::obf!("W{:?}@{}", s.semaphore, s.value) + format_args!("W{:?}@{}", s.semaphore, s.value) )); } let ns = si.signalSemaphoreInfoCount as usize; @@ -3753,7 +3661,7 @@ unsafe fn submit2_impl( for s in ss.iter().take(3) { sems.push(format!( "{}", - gndrm_obf::obf!("S{:?}@{}", s.semaphore, s.value) + format_args!("S{:?}@{}", s.semaphore, s.value) )); if let Ok(mut g) = LAST_SIG.lock() { *g = Some((format!("{:?}", s.semaphore), s.value)); @@ -3779,14 +3687,12 @@ unsafe fn submit2_impl( // submit floods the 256 KiB log ring in seconds and evicts the startup // sequence this log exists to explain. if seq < LOG_FIRST_N || seq.is_multiple_of(240) { - crate::logf!(gndrm_obf::obf!( - "proxy submit2 #{seq}: n={count} q={queue:?} real_q={:?} entries={:?} cbs={cbs:?} sems={sems:?} fence={fence:?}", + crate::logf!("proxy submit2 #{seq}: n={count} q={queue:?} real_q={:?} entries={:?} cbs={cbs:?} sems={sems:?} fence={fence:?}", unsafe { (*gq).real }, unsafe { slice_or_empty(submits, count as usize) } .iter() .map(|s| s.commandBufferInfoCount) - .collect::>() - )); + .collect::>()); } } let _submit = SUBMIT_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -3813,10 +3719,8 @@ unsafe extern "C" fn gn_vkAllocateCommandBuffers( loud("alloc_cmd.miss", || { format!( "{}", - gndrm_obf::obf!( - "proxy: vkAllocateCommandBuffers DEVICE MISS {} — guest CBs will be driver-raw", - unsafe { handle_note(false, device as usize, first, n) } - ) + format_args!("proxy: vkAllocateCommandBuffers DEVICE MISS {} — guest CBs will be driver-raw", + unsafe { handle_note(false, device as usize, first, n) }) ) }); return VK_ERROR_INITIALIZATION_FAILED; @@ -3841,10 +3745,8 @@ unsafe extern "C" fn gn_vkAllocateCommandBuffers( (*gd).cmds = gc; noted_wrapper(gc as usize); *out.add(i) = gc.cast::(); - crate::logf!(gndrm_obf::obf!( - "proxy alloc cmd: wrapper={:?} real={real:?}", - gc.cast::() - )); + crate::logf!("proxy alloc cmd: wrapper={:?} real={real:?}", + gc.cast::()); } } } @@ -3888,9 +3790,7 @@ unsafe extern "C" fn gn_vkCreateGraphicsPipelines( } let res = unsafe { real((*gd).real, cache, count, cis, alloc, out) }; if culled > 0 { - crate::logf!(gndrm_obf::obf!( - "proxy: winding compensation skipped on {culled}/{count} culling pipeline(s)" - )); + crate::logf!("proxy: winding compensation skipped on {culled}/{count} culling pipeline(s)"); } res } @@ -3933,8 +3833,7 @@ unsafe extern "C" fn gn_vkCreateImage( if seen.len() < LOG_IMAGE_FIRST_N && !seen.contains(&key) { seen.push(key); let pnext = unsafe { pnext_image_create_summary(ci_ref.pNext) }; - crate::logf!(gndrm_obf::obf!( - "guest image: fmt={} {}x{}x{} type={} mips={} layers={} samples={:#x} tiling={} usage={:#x} flags={:#x} pNext=[{pnext}]", + crate::logf!("guest image: fmt={} {}x{}x{} type={} mips={} layers={} samples={:#x} tiling={} usage={:#x} flags={:#x} pNext=[{pnext}]", ci_ref.format, ci_ref.extent.width, ci_ref.extent.height, @@ -3945,8 +3844,7 @@ unsafe extern "C" fn gn_vkCreateImage( ci_ref.samples, ci_ref.tiling, ci_ref.usage, - ci_ref.flags - )); + ci_ref.flags); } } res @@ -3990,7 +3888,7 @@ unsafe fn sc_slot_of(gd: *mut GnDevice, image: VkImage) -> Option<(*mut GnSwapch fn trace_sc_cmd(name: &str, cmd: VkCommandBuffer, hits: &str) { let n = TRACE_SC_CMD.fetch_add(1, Ordering::Relaxed); if n < TRACE_SC_CMD_N { - crate::logf!(gndrm_obf::obf!("x11 cmd {n}: {name} cb={cmd:?} {hits}")); + crate::logf!("x11 cmd {n}: {name} cb={cmd:?} {hits}"); } } @@ -4043,9 +3941,7 @@ fn trace_seen(name: &'static str) { } if let Ok(mut v) = TRACE_SEEN.lock() { if v.len() < 32 && !v.contains(&name) { - crate::logf!(gndrm_obf::obf!( - "x11 cmd-seen: {name} (guest records it through the shim)" - )); + crate::logf!("x11 cmd-seen: {name} (guest records it through the shim)"); v.push(name); } } @@ -4065,7 +3961,7 @@ unsafe fn cmd_real_and_dev(cmd: VkCommandBuffer) -> (VkCommandBuffer, *mut GnDev fn slot_note(s: Option<(*mut GnSwapchain, usize)>) -> String { match s { - Some((sc, i)) => format!("{}", gndrm_obf::obf!("SLOT sc={sc:?} slot={i}")), + Some((sc, i)) => format!("{}", format_args!("SLOT sc={sc:?} slot={i}")), None => "guest".into(), } } @@ -4130,7 +4026,7 @@ fn copy_size2(n: u32, regions: *const VkImageCopy2) -> (u32, u32) { /// A transfer region's extent, as a log field. fn extent_note(e: VkExtent3D) -> String { - format!("{}", gndrm_obf::obf!("r0={}x{}", e.width, e.height)) + format!("{}", format_args!("r0={}x{}", e.width, e.height)) } /// Extent of the first copy region of a v1 `VkImageCopy` array (does the @@ -4158,13 +4054,11 @@ fn blit_extent(n: u32, regions: *const VkImageBlit) -> String { let r = unsafe { &*regions }; format!( "{}", - gndrm_obf::obf!( - "blit={}x{} -> {}x{}", + format_args!("blit={}x{} -> {}x{}", r.srcOffsets[1].x - r.srcOffsets[0].x, r.srcOffsets[1].y - r.srcOffsets[0].y, r.dstOffsets[1].x - r.dstOffsets[0].x, - r.dstOffsets[1].y - r.dstOffsets[0].y - ) + r.dstOffsets[1].y - r.dstOffsets[0].y) ) } @@ -4298,15 +4192,13 @@ fn trace_viewports(name: &str, count: u32, vps: *const VkViewport) { } *last = Some(key); VP_LOGGED.fetch_add(1, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "x11 {name}: call={n} count={count} vp0 x={} y={} w={} h={} depth={}..{}", + crate::logf!("x11 {name}: call={n} count={count} vp0 x={} y={} w={} h={} depth={}..{}", v.x, v.y, v.width, v.height, v.minDepth, - v.maxDepth - )); + v.maxDepth); } fn trace_scissors(name: &str, count: u32, rects: *const VkRect2D) { @@ -4334,13 +4226,11 @@ fn trace_scissors(name: &str, count: u32, rects: *const VkRect2D) { } *last = Some(key); SC_LOGGED.fetch_add(1, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "x11 {name}: call={n} count={count} sc0 off=({},{}) ext={}x{}", + crate::logf!("x11 {name}: call={n} count={count} sc0 off=({},{}) ext={}x{}", r.offset.x, r.offset.y, r.extent.width, - r.extent.height - )); + r.extent.height); } unsafe extern "C" fn gn_vkCmdSetViewport( @@ -4577,33 +4467,29 @@ unsafe extern "C" fn gn_vkCmdBeginRendering(cmd: VkCommandBuffer, info: *const V let note = match img { Some(i) => match unsafe { sc_slot_of(gd, i) } { Some((sc, si)) => { - format!("{}", gndrm_obf::obf!("SLOT sc={sc:?} slot={si}")) + format!("{}", format_args!("SLOT sc={sc:?} slot={si}")) } - None => format!("{}", gndrm_obf::obf!("img={:#x}", i as usize)), + None => format!("{}", format_args!("img={:#x}", i as usize)), }, - None => format!("{}", gndrm_obf::obf!("view={:#x}", a.imageView as usize)), + None => format!("{}", format_args!("view={:#x}", a.imageView as usize)), }; let c = a.clearValue.float32; parts.push(format!( "{}", - gndrm_obf::obf!( - "a{k}[{note} layout={} load={} store={} clear=({},{},{},{})]", + format_args!("a{k}[{note} layout={} load={} store={} clear=({},{},{},{})]", a.imageLayout, a.loadOp, a.storeOp, c[0], c[1], c[2], - c[3] - ) + c[3]) )); } - crate::logf!(gndrm_obf::obf!( - "x11 rndr {n}: {}x{} colors={na} {}", + crate::logf!("x11 rndr {n}: {}x{} colors={na} {}", ri.renderArea.extent.width, ri.renderArea.extent.height, - parts.join(" ") - )); + parts.join(" ")); } } call_cmd!(gd, cmd_begin_rendering, "vkCmdBeginRendering", |f| f( @@ -4629,8 +4515,7 @@ unsafe extern "C" fn gn_vkCmdBeginRenderPass2( } else { [0f32; 4] }; - crate::logf!(gndrm_obf::obf!( - "x11 rpb2 {n}: {}x{} off=({},{}) fb={:#x} rp={:#x} clears={} clear0=({},{},{},{}) rpOps={} slots={slots:?}", + crate::logf!("x11 rpb2 {n}: {}x{} off=({},{}) fb={:#x} rp={:#x} clears={} clear0=({},{},{},{}) rpOps={} slots={slots:?}", bi.renderArea.extent.width, bi.renderArea.extent.height, bi.renderArea.offset.x, @@ -4639,8 +4524,7 @@ unsafe extern "C" fn gn_vkCmdBeginRenderPass2( bi.renderPass as usize, bi.clearValueCount, c[0], c[1], c[2], c[3], - rp_ops_note(bi.renderPass) - )); + rp_ops_note(bi.renderPass)); } } call_cmd!(gd, cmd_begin_render_pass2, "vkCmdBeginRenderPass2", |f| f( @@ -4665,8 +4549,7 @@ unsafe extern "C" fn gn_vkCmdBeginRenderPass( [0f32; 4] }; let slots = unsafe { fb_slots(gd, bi.framebuffer) }; - crate::logf!(gndrm_obf::obf!( - "x11 rpb {n}: {}x{} off=({},{}) fb={:#x} rp={:#x} clears={} clear0=({},{},{},{}) contents={contents} rpOps={} slots={slots:?}", + crate::logf!("x11 rpb {n}: {}x{} off=({},{}) fb={:#x} rp={:#x} clears={} clear0=({},{},{},{}) contents={contents} rpOps={} slots={slots:?}", bi.renderArea.extent.width, bi.renderArea.extent.height, bi.renderArea.offset.x, @@ -4675,8 +4558,7 @@ unsafe extern "C" fn gn_vkCmdBeginRenderPass( bi.renderPass as usize, bi.clearValueCount, c[0], c[1], c[2], c[3], - rp_ops_note(bi.renderPass) - )); + rp_ops_note(bi.renderPass)); } } call_cmd!(gd, cmd_begin_render_pass, "vkCmdBeginRenderPass", |f| f( @@ -4699,10 +4581,8 @@ unsafe extern "C" fn gn_vkCmdClearColorImage( static ANY: AtomicUsize = AtomicUsize::new(0); let n2 = ANY.fetch_add(1, Ordering::Relaxed); if n2 < 8 { - crate::logf!(gndrm_obf::obf!( - "x11 any clear: img={:#x} layout={layout}", - image as usize - )); + crate::logf!("x11 any clear: img={:#x} layout={layout}", + image as usize); } } if let Some((sc, i)) = unsafe { sc_slot_of(gd, image) } { @@ -4716,13 +4596,11 @@ unsafe extern "C" fn gn_vkCmdClearColorImage( cmd, &format!( "{}", - gndrm_obf::obf!( - "SLOT sc={sc:?} slot={i} layout={layout} n={n} clear=({},{},{},{})", + format_args!("SLOT sc={sc:?} slot={i} layout={layout} n={n} clear=({},{},{},{})", c[0], c[1], c[2], - c[3] - ) + c[3]) ), ); } @@ -4754,14 +4632,12 @@ unsafe extern "C" fn gn_vkCmdCopyImage( trace_sc_cmd( "vkCmdCopyImage", cmd, - &format!("{}", gndrm_obf::obf!( - "src={:#x}({}) dst={:#x}({}) srcLayout={src_layout} dstLayout={dst_layout} n={n} {}", + &format!("{}", format_args!("src={:#x}({}) dst={:#x}({}) srcLayout={src_layout} dstLayout={dst_layout} n={n} {}", src as usize, slot_note(s), dst as usize, slot_note(d), - copy_extent(n, regions) - )), + copy_extent(n, regions))), ); } } @@ -4779,8 +4655,7 @@ unsafe extern "C" fn gn_vkCmdCopyImage2(cmd: VkCommandBuffer, info: *const VkCop static ANY: AtomicUsize = AtomicUsize::new(0); let n2 = ANY.fetch_add(1, Ordering::Relaxed); if n2 < 12 { - crate::logf!(gndrm_obf::obf!( - "x11 any copyimg2: src={:#x} dst={:#x} {}x{}", + crate::logf!("x11 any copyimg2: src={:#x} dst={:#x} {}x{}", ci.srcImage as usize, ci.dstImage as usize, ci.regionCount, @@ -4788,8 +4663,7 @@ unsafe extern "C" fn gn_vkCmdCopyImage2(cmd: VkCommandBuffer, info: *const VkCop unsafe { (*ci.pRegions).extent.width } } else { 0 - } - )); + }); } } let s = unsafe { sc_slot_of(gd, ci.srcImage) }; @@ -4804,8 +4678,7 @@ unsafe extern "C" fn gn_vkCmdCopyImage2(cmd: VkCommandBuffer, info: *const VkCop cmd, &format!( "{}", - gndrm_obf::obf!( - "src={:#x}({}) dst={:#x}({}) srcLayout={} dstLayout={} n={} {}", + format_args!("src={:#x}({}) dst={:#x}({}) srcLayout={} dstLayout={} n={} {}", ci.srcImage as usize, slot_note(s), ci.dstImage as usize, @@ -4813,8 +4686,7 @@ unsafe extern "C" fn gn_vkCmdCopyImage2(cmd: VkCommandBuffer, info: *const VkCop ci.srcImageLayout, ci.dstImageLayout, ci.regionCount, - copy_extent2(ci.regionCount, ci.pRegions) - ) + copy_extent2(ci.regionCount, ci.pRegions)) ), ); } @@ -4845,14 +4717,12 @@ unsafe extern "C" fn gn_vkCmdBlitImage( trace_sc_cmd( "vkCmdBlitImage", cmd, - &format!("{}", gndrm_obf::obf!( - "src={:#x}({}) dst={:#x}({}) srcLayout={src_layout} dstLayout={dst_layout} n={n} filter={filter} {}", + &format!("{}", format_args!("src={:#x}({}) dst={:#x}({}) srcLayout={src_layout} dstLayout={dst_layout} n={n} filter={filter} {}", src as usize, slot_note(s), dst as usize, slot_note(d), - blit_extent(n, regions) - )), + blit_extent(n, regions))), ); } } @@ -4878,8 +4748,7 @@ unsafe extern "C" fn gn_vkCmdBlitImage2(cmd: VkCommandBuffer, info: *const VkBli cmd, &format!( "{}", - gndrm_obf::obf!( - "src={:#x}({}) dst={:#x}({}) srcLayout={} dstLayout={} n={} filter={}", + format_args!("src={:#x}({}) dst={:#x}({}) srcLayout={} dstLayout={} n={} filter={}", ci.srcImage as usize, slot_note(s), ci.dstImage as usize, @@ -4887,8 +4756,7 @@ unsafe extern "C" fn gn_vkCmdBlitImage2(cmd: VkCommandBuffer, info: *const VkBli ci.srcImageLayout, ci.dstImageLayout, ci.regionCount, - ci.filter - ) + ci.filter) ), ); } @@ -4910,22 +4778,18 @@ unsafe extern "C" fn gn_vkCmdPipelineBarrier2(cmd: VkCommandBuffer, dep: *const static ANY: AtomicUsize = AtomicUsize::new(0); let n2 = ANY.fetch_add(1, Ordering::Relaxed); if n2 < 12 { - crate::logf!(gndrm_obf::obf!( - "x11 any bar2: img={:#x} srcStage={:#x} dstStage={:#x}", + crate::logf!("x11 any bar2: img={:#x} srcStage={:#x} dstStage={:#x}", b.image as usize, b.srcStageMask, - b.dstStageMask - )); + b.dstStageMask); } } if let Some((sc, i)) = unsafe { sc_slot_of(gd, b.image) } { trace_sc_cmd( "vkCmdPipelineBarrier2(image)", cmd, - &format!("{}", gndrm_obf::obf!( - "SLOT sc={sc:?} slot={i} srcStage={:#x} srcAccess={:#x} dstStage={:#x} dstAccess={:#x}", - b.srcStageMask, b.srcAccessMask, b.dstStageMask, b.dstAccessMask - )), + &format!("{}", format_args!("SLOT sc={sc:?} slot={i} srcStage={:#x} srcAccess={:#x} dstStage={:#x} dstAccess={:#x}", + b.srcStageMask, b.srcAccessMask, b.dstStageMask, b.dstAccessMask)), ); } } @@ -4953,9 +4817,7 @@ unsafe extern "C" fn gn_vkCmdCopyBufferToImage( cmd, &format!( "{}", - gndrm_obf::obf!( - "buf={src_buffer:#x} -> SLOT sc={sc:?} slot={i} dstLayout={dst_layout} n={n}" - ) + format_args!("buf={src_buffer:#x} -> SLOT sc={sc:?} slot={i} dstLayout={dst_layout} n={n}") ), ); } @@ -4982,12 +4844,10 @@ unsafe extern "C" fn gn_vkCmdCopyBufferToImage2( cmd, &format!( "{}", - gndrm_obf::obf!( - "buf={:#x} -> SLOT sc={sc:?} slot={i} dstLayout={} n={}", + format_args!("buf={:#x} -> SLOT sc={sc:?} slot={i} dstLayout={} n={}", ci.srcBuffer as usize, ci.dstImageLayout, - ci.regionCount - ) + ci.regionCount) ), ); } @@ -5024,10 +4884,8 @@ unsafe extern "C" fn gn_vkCmdPipelineBarrier( trace_sc_cmd( "vkCmdPipelineBarrier(image)", cmd, - &format!("{}", gndrm_obf::obf!( - "SLOT sc={sc:?} slot={i} {}->{} srcStage={src_stage:#x} dstStage={dst_stage:#x}", - b.oldLayout, b.newLayout - )), + &format!("{}", format_args!("SLOT sc={sc:?} slot={i} {}->{} srcStage={src_stage:#x} dstStage={dst_stage:#x}", + b.oldLayout, b.newLayout)), ); } } @@ -5052,10 +4910,8 @@ unsafe extern "C" fn gn_vkCmdExecuteCommands( // secondary handles. Forwarding raw is what fed the driver wrapper // pointers before; dropping it is silent. Say it happened. loud("exec_cmds.miss", || { - format!("{}", gndrm_obf::obf!( - "proxy: vkCmdExecuteCommands CB MISS cmd={:#x} count={count} — secondaries not translated", - cmd as usize - )) + format!("{}", format_args!("proxy: vkCmdExecuteCommands CB MISS cmd={:#x} count={count} — secondaries not translated", + cmd as usize)) }); return; } @@ -6319,9 +6175,7 @@ pub fn note_instance_miss(name: &CStr, driver_has_none: bool) { if let Ok(mut missed) = GIPA_MISSED.lock() { let n = name.to_string_lossy().into_owned(); if missed.len() < 64 && !missed.contains(&n) { - crate::logf!(gndrm_obf::obf!( - "proxy: instance-path MISS (driver has no entry point): {n}" - )); + crate::logf!("proxy: instance-path MISS (driver has no entry point): {n}"); missed.push(n); } } @@ -6355,10 +6209,8 @@ unsafe extern "C" fn gn_vkGetDeviceProcAddr( // instead. Name every miss once per device. let n = name.to_string_lossy(); if GDPA_MISSED.first(device as usize, &n) { - crate::logf!(gndrm_obf::obf!( - "proxy: vkGetDeviceProcAddr MISS dev={:#x} (NULL to the app): {n}", - device as usize - )); + crate::logf!("proxy: vkGetDeviceProcAddr MISS dev={:#x} (NULL to the app): {n}", + device as usize); } } serve_unlisted(name, target, DispatchCtx::Device) @@ -6661,7 +6513,7 @@ mod tests { ]; for &(name, level, arg0) in cases { let d = classify(name) - .unwrap_or_else(|| panic!("{}", gndrm_obf::obf!("{name} missing from registry"))); + .unwrap_or_else(|| panic!("{}", format_args!("{name} missing from registry"))); assert_eq!(d.1, level, "{name} level"); assert_eq!(d.2, arg0, "{name} arg0"); } @@ -6851,7 +6703,7 @@ mod tests { // so the exact partner is not pinned — the round trip is. assert_eq!(alias_of(khr), Some(core), "alias_of({khr})"); let partner = alias_of(core) - .unwrap_or_else(|| panic!("{}", gndrm_obf::obf!("alias_of({core}) is empty"))); + .unwrap_or_else(|| panic!("{}", format_args!("alias_of({core}) is empty"))); assert_eq!(alias_of(partner), Some(core), "round trip from {core}"); } } @@ -8027,16 +7879,14 @@ fn dispatch_main() { } let err = unsafe { wlproto::wl_display_get_error(dpy) }; G_WL.lock().unwrap().failed = true; - crate::logf!(gndrm_obf::obf!( - "wayland dispatch thread exited: {}", + crate::logf!("wayland dispatch thread exited: {}", if err != 0 { std::io::Error::from_raw_os_error(err).to_string() } else if failed { std::io::Error::last_os_error().to_string() } else { "display closed".to_string() - } - )); + }); } fn wl_setup(dpy: *mut wl_display) -> bool { @@ -8049,9 +7899,7 @@ fn wl_setup(dpy: *mut wl_display) -> bool { let dpy = if dpy.is_null() { let c = wlproto::wl_display_connect(std::ptr::null()); if c.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy wayland connect failed (WAYLAND_DISPLAY unset?)" - )); + crate::logf!("proxy wayland connect failed (WAYLAND_DISPLAY unset?)"); (*wptr).failed = true; return false; } @@ -8071,9 +7919,7 @@ fn wl_setup(dpy: *mut wl_display) -> bool { } wlproto::wl_proxy_destroy(reg); if !(*wptr).failed && (*wptr).dmabuf.is_null() { - crate::logf!(gndrm_obf::obf!( - "compositor misses zwp_linux_dmabuf_v1 v3 — proxy cannot present" - )); + crate::logf!("compositor misses zwp_linux_dmabuf_v1 v3 — proxy cannot present"); (*wptr).failed = true; } if !(*wptr).failed { @@ -8081,7 +7927,7 @@ fn wl_setup(dpy: *mut wl_display) -> bool { .name("gn-wl-dispatch".into()) .spawn(dispatch_main); if spawned.is_err() { - crate::logf!(gndrm_obf::obf!("failed to start wayland dispatch thread")); + crate::logf!("failed to start wayland dispatch thread"); (*wptr).failed = true; } } @@ -8108,7 +7954,7 @@ extern "C" fn on_buffer_release(data: *mut c_void, _buf: *mut wl_proxy) { let sc = (*slot).owner; let logging = crate::vkshim_enabled(); if logging && LOG_RELEASE.fetch_add(1, Ordering::Relaxed) < LOG_FIRST_N { - crate::logf!(gndrm_obf::obf!("proxy release: slot={slot:?}")); + crate::logf!("proxy release: slot={slot:?}"); } // The target may have changed since this shim connected, and a push // from the daemon is read here because a release is the one event this @@ -8137,10 +7983,8 @@ extern "C" fn on_buffer_release(data: *mut c_void, _buf: *mut wl_proxy) { if logging { N_REL.fetch_add(1, Ordering::Relaxed); if rate_ok(&RATE_REL, RATE_EVERY) { - crate::logf!(gndrm_obf::obf!( - "gn-vkshim release: slot={slot:?} {}", - slot_flags(sc) - )); + crate::logf!("gn-vkshim release: slot={slot:?} {}", + slot_flags(sc)); } } } @@ -8271,7 +8115,7 @@ fn loud(site: &'static str, msg: impl FnOnce() -> String) { } } let line = msg(); - crate::logf!(gndrm_obf::obf!("{}", line)); + crate::logf!("{}", line); } /// A handle the shim could not resolve, against the wrapper table it searched, @@ -8279,10 +8123,8 @@ fn loud(site: &'static str, msg: impl FnOnce() -> String) { unsafe fn handle_note(found: bool, searched: usize, first_wrapper: usize, n: usize) -> String { format!( "{}", - gndrm_obf::obf!( - "found={found} searched={searched:#x} wrappers={n} first={first_wrapper:#x} pid={}", - std::process::id() - ) + format_args!("found={found} searched={searched:#x} wrappers={n} first={first_wrapper:#x} pid={}", + std::process::id()) ) } @@ -8328,9 +8170,7 @@ unsafe fn real_cmd(cmd: VkCommandBuffer) -> VkCommandBuffer { // wrapped is the driver's own. But say so when it *was* a wrapper — // that case hands the driver a shim pointer and faults inside it. if was_wrapper(cmd as usize) { - crate::logf!(gndrm_obf::obf!( - "proxy: BUG submit carries an untracked wrapper CB {cmd:?}" - )); + crate::logf!("proxy: BUG submit carries an untracked wrapper CB {cmd:?}"); } cmd } @@ -8503,9 +8343,7 @@ fn note_nested(name: &str, n: usize) { // the shim translated nested wrapper handles" is the fact that // settles whether the submit path is live, and the guest process // does not set GNDRM_LOG_VKSHIM. Bounded to one line per name. - crate::logf!(gndrm_obf::obf!( - "proxy nested translate: {name} ({n} handle(s))" - )); + crate::logf!("proxy nested translate: {name} ({n} handle(s))"); } } } @@ -8680,10 +8518,8 @@ pub(crate) unsafe fn gn_real_device_proc(gd: *mut GnDevice, name: &CStr) -> PFN_ || n.contains("SubresourceLayout")) && REAL_PROC_SEEN.first(gd as usize, &n) { - crate::logf!(gndrm_obf::obf!( - "proxy: real proc {n} via {via} dev={:#x}", - gd as usize - )); + crate::logf!("proxy: real proc {n} via {via} dev={:#x}", + gd as usize); } fnptr } @@ -8820,10 +8656,8 @@ fn import_mode(has: &dyn Fn(&CStr) -> bool, allow_ahb: bool) -> Option { if allow_ahb && AHB_EXTS.iter().all(|e| has(e)) { return Some(true); } - crate::log_reason!(gndrm_obf::obf!( - "proxy prereq: device lacks {}", - missing.to_str().unwrap() - )); + crate::log_reason!("proxy prereq: device lacks {}", + missing.to_str().unwrap()); None } @@ -8855,16 +8689,12 @@ fn dev_exts_satisfied( }; if device_api >= VK_API_VERSION_1_1 && !has(c"VK_KHR_external_memory") { EXTERNAL_MEMORY_CORE.store(true, Ordering::Relaxed); - crate::logi!(gndrm_obf::obf!( - "proxy prereq: VK_KHR_external_memory not listed, core in device api {}", - api_str(device_api) - )); + crate::logi!("proxy prereq: VK_KHR_external_memory not listed, core in device api {}", + api_str(device_api)); } match import_mode(&has, allow_ahb) { Some(true) => { - crate::logi!(gndrm_obf::obf!( - "proxy prereq: no dma-buf import, using AHardwareBuffer import" - )); + crate::logi!("proxy prereq: no dma-buf import, using AHardwareBuffer import"); true } Some(false) => true, @@ -8879,9 +8709,7 @@ pub fn device_prereqs(gipa: GipaFn, allow_ahb: bool) -> bool { let create_inst: Option = unsafe { std::mem::transmute(gipa(ptr::null_mut(), c"vkCreateInstance".as_ptr())) }; let Some(create_inst) = create_inst else { - crate::log_reason!(gndrm_obf::obf!( - "proxy prereq: driver exposes no vkCreateInstance" - )); + crate::log_reason!("proxy prereq: driver exposes no vkCreateInstance"); return false; }; let app = VkApplicationInfo { @@ -8905,14 +8733,10 @@ pub fn device_prereqs(gipa: GipaFn, allow_ahb: bool) -> bool { }; let mut inst: VkInstance = ptr::null_mut(); let res = unsafe { create_inst(&ci, ptr::null(), &mut inst) }; - crate::logi!(gndrm_obf::obf!( - "proxy prereq: probe vkCreateInstance api={} layers=[] exts=[] -> {res}", - api_str(app.apiVersion) - )); + crate::logi!("proxy prereq: probe vkCreateInstance api={} layers=[] exts=[] -> {res}", + api_str(app.apiVersion)); if res != VK_SUCCESS { - crate::log_reason!(gndrm_obf::obf!( - "proxy prereq: probe vkCreateInstance failed ({res})" - )); + crate::log_reason!("proxy prereq: probe vkCreateInstance failed ({res})"); return false; } // Instance-level procs must be fetched against a live instance: mesa @@ -8938,29 +8762,23 @@ pub fn device_prereqs(gipa: GipaFn, allow_ahb: bool) -> bool { let device_api = get_props.map_or(0, |f| unsafe { let mut p: VkPhysicalDeviceProperties = std::mem::zeroed(); f(pd, &mut p); - crate::logi!(gndrm_obf::obf!( - "proxy prereq: device '{}' api {} vendor {:#x} device {:#x} driver {:#x} ({n} physical devices)", + crate::logi!("proxy prereq: device '{}' api {} vendor {:#x} device {:#x} driver {:#x} ({n} physical devices)", CStr::from_ptr(p.deviceName.as_ptr()).to_string_lossy(), api_str(p.apiVersion), p.vendorID, p.deviceID, - p.driverVersion - )); + p.driverVersion); p.apiVersion }); ok = dev_exts_satisfied(enum_de, pd, device_api, allow_ahb); } else { - crate::log_reason!(gndrm_obf::obf!( - "proxy prereq: vkEnumeratePhysicalDevices failed ({r})" - )); + crate::log_reason!("proxy prereq: vkEnumeratePhysicalDevices failed ({r})"); } } else { - crate::log_reason!(gndrm_obf::obf!("proxy prereq: no physical devices")); + crate::log_reason!("proxy prereq: no physical devices"); } } - _ => crate::log_reason!(gndrm_obf::obf!( - "proxy prereq: instance-level procs unresolved" - )), + _ => crate::log_reason!("proxy prereq: instance-level procs unresolved"), } if let Some(destroy_inst) = destroy_inst { unsafe { destroy_inst(inst, ptr::null()) }; @@ -8968,14 +8786,12 @@ pub fn device_prereqs(gipa: GipaFn, allow_ahb: bool) -> bool { if ok { AHB_IMPORT_ALLOWED.store(allow_ahb, Ordering::Relaxed); } - crate::logi!(gndrm_obf::obf!( - "proxy prereq: {}", + crate::logi!("proxy prereq: {}", if ok { "passed".to_string() } else { format!("FAILED ({})", crate::reason()) - } - )); + }); ok } @@ -9077,29 +8893,19 @@ fn real_instance_layers(gipa: GipaFn) -> Option> { } fn log_real_instance_surface(gipa: GipaFn) { - crate::logi!(gndrm_obf::obf!( - "system loader: instance version {}", - api_str(real_instance_version(gipa)) - )); + crate::logi!("system loader: instance version {}", + api_str(real_instance_version(gipa))); match real_instance_exts(gipa) { - Some(e) => crate::logi!(gndrm_obf::obf!( - "system loader: {} instance extensions: {}", + Some(e) => crate::logi!("system loader: {} instance extensions: {}", e.len(), - join_names(&e) - )), - None => crate::logi!(gndrm_obf::obf!( - "system loader: instance extensions unreadable" - )), + join_names(&e)), + None => crate::logi!("system loader: instance extensions unreadable"), } match real_instance_layers(gipa) { - Some(l) => crate::logi!(gndrm_obf::obf!( - "system loader: {} instance layers: {}", + Some(l) => crate::logi!("system loader: {} instance layers: {}", l.len(), - join_names(&l) - )), - None => crate::logi!(gndrm_obf::obf!( - "system loader: instance layers unreadable" - )), + join_names(&l)), + None => crate::logi!("system loader: instance layers unreadable"), } } @@ -9171,13 +8977,11 @@ unsafe extern "C" fn gn_vkCreateInstance( let mut exts: Vec<*const c_char> = vec![ptr::null(); names.len() + 16]; let real_exts = real_instance_exts(gipa); if !WSI_INSTANCE_LOGGED.swap(true, Ordering::Relaxed) { - crate::logi!(gndrm_obf::obf!( - "proxy instance: WSI extensions hidden from the guest: [{}] requested and masked: [{}]", + crate::logi!("proxy instance: WSI extensions hidden from the guest: [{}] requested and masked: [{}]", crate::wsi_policy::hidden_names( real_exts.iter().flatten().map(|e| e.as_c_str()) ), - crate::wsi_policy::hidden_names(names.iter().map(|&o| unsafe { CStr::from_ptr(o) })) - )); + crate::wsi_policy::hidden_names(names.iter().map(|&o| unsafe { CStr::from_ptr(o) }))); } for &name in names { let n_ = unsafe { CStr::from_ptr(name) }; @@ -9238,22 +9042,18 @@ unsafe extern "C" fn gn_vkCreateInstance( ci2.pApplicationInfo = &app2; } if !dropped_exts.is_empty() || !dropped_layers.is_empty() { - crate::logi!(gndrm_obf::obf!( - "proxy instance create: dropping exts=[{}] layers=[{}] the system loader does not list", + crate::logi!("proxy instance create: dropping exts=[{}] layers=[{}] the system loader does not list", join_names(&dropped_exts), - join_names(&dropped_layers) - )); + join_names(&dropped_layers)); } - crate::logi!(gndrm_obf::obf!( - "proxy instance create: api={} (app {}, system loader {}) flags={:#x} layers=[{}] exts=[{}] pNext=[{}]", + crate::logi!("proxy instance create: api={} (app {}, system loader {}) flags={:#x} layers=[{}] exts=[{}] pNext=[{}]", api_str(fwd_api), api_str(app_api), api_str(loader_api), ci.flags, join_names(&fwd_layers), join_names(&fwd_exts), - unsafe { pnext_str(ci.pNext.cast()) } - )); + unsafe { pnext_str(ci.pNext.cast()) }); // Confine the loader's chain link to the hooks' namespace (see // G_CHAIN_INST_LINK). let mut p = ci2.pNext as *mut VkBaseOutStructure; @@ -9269,9 +9069,7 @@ unsafe extern "C" fn gn_vkCreateInstance( } } let res = unsafe { real_create(&ci2, alloc, out) }; - crate::logi!(gndrm_obf::obf!( - "proxy instance create: system loader returned {res}" - )); + crate::logi!("proxy instance create: system loader returned {res}"); if res != VK_SUCCESS { return res; } @@ -9317,17 +9115,13 @@ unsafe extern "C" fn gn_vkCreateInstance( g.instances = gi; } } - crate::logf!(gndrm_obf::obf!( - "proxy instance {:?} (headless WSI backing)", - unsafe { *out } - )); + crate::logf!("proxy instance {:?} (headless WSI backing)", + unsafe { *out }); if !LOUD_INSTANCE.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "proxy: instance created pid={} real={:?} npds={}", + crate::logf!("proxy: instance created pid={} real={:?} npds={}", std::process::id(), unsafe { *out }, - unsafe { (*gi).n_pds } - )); + unsafe { (*gi).n_pds }); } VK_SUCCESS } @@ -9507,9 +9301,7 @@ unsafe extern "C" fn gn_vkEnumerateDeviceExtensionProperties( continue; } if name == c"VK_EXT_physical_device_drm" && HIDE_DEVICE_DRM.load(Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "proxy: hiding VK_EXT_physical_device_drm from gamescope" - )); + crate::logf!("proxy: hiding VK_EXT_physical_device_drm from gamescope"); continue; } if name == c"VK_EXT_hdr_metadata" { @@ -9546,9 +9338,7 @@ unsafe extern "C" fn gn_vkEnumerateDeviceExtensionProperties( } buf[kept] = prop; kept += 1; - crate::logf!(gndrm_obf::obf!( - "proxy: advertised VK_EXT_hdr_metadata (driver does not list it)" - )); + crate::logf!("proxy: advertised VK_EXT_hdr_metadata (driver does not list it)"); } if !has_robustness2 && layer.is_null() && FAKE_ROBUSTNESS2.load(Ordering::Relaxed) { let mut prop = VkExtensionProperties { @@ -9562,9 +9352,7 @@ unsafe extern "C" fn gn_vkEnumerateDeviceExtensionProperties( buf[kept] = prop; kept += 1; if !ROBUSTNESS2_FAKED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "proxy: advertised VK_EXT_robustness2 (driver does not list it)" - )); + crate::logf!("proxy: advertised VK_EXT_robustness2 (driver does not list it)"); } } // Present ids, present waits and swapchain maintenance are served by the @@ -9635,15 +9423,11 @@ unsafe extern "C" fn gn_vkCreateWaylandSurfaceKHR( let ci = unsafe { &*ci }; let gi = unsafe { find_instance(instance) }; if gi.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy surface create FAILED: instance {instance:?} not one of ours" - )); + crate::logf!("proxy surface create FAILED: instance {instance:?} not one of ours"); return VK_ERROR_INITIALIZATION_FAILED; } if !wl_setup(ci.display.cast()) { - crate::logf!(gndrm_obf::obf!( - "proxy surface create FAILED: wayland setup failed" - )); + crate::logf!("proxy surface create FAILED: wayland setup failed"); return VK_ERROR_INITIALIZATION_FAILED; } let s = Box::new(GnSurface { @@ -9668,11 +9452,9 @@ unsafe extern "C" fn gn_vkCreateWaylandSurfaceKHR( } unsafe { *out = s as usize as VkSurfaceKHR; - crate::logf!(gndrm_obf::obf!( - "proxy surface {:?} (direct attach on wl_surface {:?})", + crate::logf!("proxy surface {:?} (direct attach on wl_surface {:?})", s, - ci.surface - )); + ci.surface); } VK_SUCCESS } @@ -9749,15 +9531,11 @@ unsafe fn xlib_override_surface( // `resolve_override_target` swaps a degenerate ancestor for the real, // painted window and leaves a legitimate one untouched (see x11.rs). let target = unsafe { crate::x11::resolve_override_target(window) }; - crate::logf!(gndrm_obf::obf!( - "override: XID {window:#x} -> gamescope override surface on {:#x}{} (default route; guest GDI/2D not composited)", + crate::logf!("override: XID {window:#x} -> gamescope override surface on {:#x}{} (default route; guest GDI/2D not composited)", target.window, - if target.provisional { ", provisional" } else { "" } - )); + if target.provisional { ", provisional" } else { "" }); if !wl_setup(ptr::null_mut()) { - crate::logf!(gndrm_obf::obf!( - "proxy xlib surface create FAILED: wayland setup failed" - )); + crate::logf!("proxy xlib surface create FAILED: wayland setup failed"); return VK_ERROR_INITIALIZATION_FAILED; } let (comp, factory, dpy) = { @@ -9765,18 +9543,14 @@ unsafe fn xlib_override_surface( (w.comp, w.swapchain_factory, w.dpy) }; if factory.is_null() { - crate::logf!(gndrm_obf::obf!( - "compositor misses gamescope_swapchain_factory_v2 — cannot bind XID" - )); + crate::logf!("compositor misses gamescope_swapchain_factory_v2 — cannot bind XID"); return VK_ERROR_INITIALIZATION_FAILED; } unsafe { let _sg = SEND_LOCK.lock().unwrap(); let surf = wlproto::compositor_create_surface(comp); if surf.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy xlib surface create FAILED: wl_surface create failed" - )); + crate::logf!("proxy xlib surface create FAILED: wl_surface create failed"); return VK_ERROR_INITIALIZATION_FAILED; } let scobj = wlproto::swapchain_factory_create_swapchain(factory, surf); @@ -9803,12 +9577,10 @@ unsafe fn xlib_override_surface( g.surfaces = s; } *out = s as usize as VkSurfaceKHR; - crate::logf!(gndrm_obf::obf!( - "override: proxy surface {:?} (own wl_surface {:?} for XID {:#x}, bound at its first present; Vulkan-only, guest GDI/2D not composited)", + crate::logf!("override: proxy surface {:?} (own wl_surface {:?} for XID {:#x}, bound at its first present; Vulkan-only, guest GDI/2D not composited)", s, surf, - window - )); + window); } VK_SUCCESS } @@ -9827,21 +9599,17 @@ unsafe fn x11_surface(gi: *mut GnInstance, window: u32, out: *mut VkSurfaceKHR) return unsafe { xlib_override_surface(gi, window, out) }; } let x11 = if window == 0 { - crate::logf!(gndrm_obf::obf!( - "x11 route: XID {:#x} unavailable ({})", + crate::logf!("x11 route: XID {:#x} unavailable ({})", window, - crate::x11::RouteUnavailable::NullXid.reason() - )); + crate::x11::RouteUnavailable::NullXid.reason()); ptr::null_mut() } else { match unsafe { crate::x11::X11Present::new(window) } { Ok(p) => Box::into_raw(Box::new(p)), Err(e) => { - crate::logf!(gndrm_obf::obf!( - "x11 route: XID {:#x} unavailable ({})", + crate::logf!("x11 route: XID {:#x} unavailable ({})", window, - e.reason() - )); + e.reason()); ptr::null_mut() } } @@ -9868,11 +9636,9 @@ unsafe fn x11_surface(gi: *mut GnInstance, window: u32, out: *mut VkSurfaceKHR) } unsafe { *out = s as usize as VkSurfaceKHR; - crate::logf!(gndrm_obf::obf!( - "proxy surface {:?} (X11 window {:#x}, DRI3+Present route)", + crate::logf!("proxy surface {:?} (X11 window {:#x}, DRI3+Present route)", s, - window - )); + window); } VK_SUCCESS } @@ -9886,9 +9652,7 @@ unsafe extern "C" fn gn_vkCreateXlibSurfaceKHR( let ci = unsafe { &*ci }; let gi = unsafe { find_instance(instance) }; if gi.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy xlib surface create FAILED: instance {instance:?} not one of ours" - )); + crate::logf!("proxy xlib surface create FAILED: instance {instance:?} not one of ours"); return VK_ERROR_INITIALIZATION_FAILED; } unsafe { x11_surface(gi, ci.window as u32, out) } @@ -9907,9 +9671,7 @@ unsafe extern "C" fn gn_vkCreateXcbSurfaceKHR( let ci = unsafe { &*ci }; let gi = unsafe { find_instance(instance) }; if gi.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy xcb surface create FAILED: instance {instance:?} not one of ours" - )); + crate::logf!("proxy xcb surface create FAILED: instance {instance:?} not one of ours"); return VK_ERROR_INITIALIZATION_FAILED; } unsafe { x11_surface(gi, ci.window, out) } @@ -10059,9 +9821,7 @@ unsafe extern "C" fn gn_vkGetPhysicalDeviceSurfaceCapabilitiesKHR( wsi_hb(); let s = unsafe { find_surface(surface) }; if s.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy surface caps query: {surface:#x} not one of ours" - )); + crate::logf!("proxy surface caps query: {surface:#x} not one of ours"); return VK_ERROR_SURFACE_LOST_KHR; } // The guest's own window size is what gamescope must see the presented @@ -10248,9 +10008,7 @@ unsafe extern "C" fn gn_vkGetPhysicalDeviceSurfaceFormatsKHR( HB_FMT.fetch_add(1, Ordering::Relaxed); wsi_hb(); if unsafe { find_surface(surface) }.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy surface formats query: {surface:#x} not one of ours" - )); + crate::logf!("proxy surface formats query: {surface:#x} not one of ours"); return VK_ERROR_SURFACE_LOST_KHR; } let served = served_surface_formats(crate::scanout::layout()); @@ -10292,7 +10050,7 @@ fn parse_present_mode_override(val: Option<&str>) -> Option { // every query. static SAID: AtomicBool = AtomicBool::new(false); if !SAID.swap(true, Ordering::Relaxed) { - crate::logi!(gndrm_obf::obf!("Invalid MESA_VK_WSI_PRESENT_MODE value!")); + crate::logi!("Invalid MESA_VK_WSI_PRESENT_MODE value!"); } return None; } @@ -10585,16 +10343,14 @@ unsafe fn mode_census(sc: *mut GnSwapchain) { let mut last = MODE_LINE.lock().unwrap_or_else(|e| e.into_inner()); if *last != Some(line) { *last = Some(line); - crate::logi!(gndrm_obf::obf!( - "present mode: declared={} requested={} source={} route={} cap={} gate={} lsfg={}", + crate::logi!("present mode: declared={} requested={} source={} route={} cap={} gate={} lsfg={}", mode_name(line.declared), mode_name(line.requested), line.source, if route { "gamescope" } else { "x11" }, line.cap, line.gate, - u8::from(line.lsfg), - )); + u8::from(line.lsfg),); } } if !crate::vkshim_enabled() || !rate_ok(&RATE_MODE, MODE_CENSUS_EVERY) { @@ -10604,8 +10360,7 @@ unsafe fn mode_census(sc: *mut GnSwapchain) { let (late, skipped) = crate::vsync_gate::late_counts(); // Since the last line, so each line reads one window's cadence. let gaps = COMMIT_GAPS.each_ref().map(|b| b.swap(0, Ordering::Relaxed)); - crate::logf!(gndrm_obf::obf!( - "present mode: declared={} requested={} source={} route={} cap={} gate={} lsfg={} acquires={} commits={} declared_fifo={} declared_other={} releases={} feedback={} presented={} discarded={} fallback={} at_queue={} gate_holds={} gate_late={} skipped={} slot_waits={} commit_lat_us={} spacing=[<15:{} 15-16.2:{} 16.2-17.2:{} 17.2-20:{} >20:{}]", + crate::logf!("present mode: declared={} requested={} source={} route={} cap={} gate={} lsfg={} acquires={} commits={} declared_fifo={} declared_other={} releases={} feedback={} presented={} discarded={} fallback={} at_queue={} gate_holds={} gate_late={} skipped={} slot_waits={} commit_lat_us={} spacing=[<15:{} 15-16.2:{} 16.2-17.2:{} 17.2-20:{} >20:{}]", mode_name(line.declared), mode_name(line.requested), line.source, @@ -10632,8 +10387,7 @@ unsafe fn mode_census(sc: *mut GnSwapchain) { gaps[1], gaps[2], gaps[3], - gaps[4], - )); + gaps[4],); } /// The wire value for `gamescope_swapchain.set_present_mode` that declares @@ -10674,9 +10428,7 @@ fn offered_present_modes( if served.contains(&m) { v.push(m); } else { - crate::logf!(gndrm_obf::obf!( - "Unsupported MESA_VK_WSI_PRESENT_MODE value!" - )); + crate::logf!("Unsupported MESA_VK_WSI_PRESENT_MODE value!"); } } for &m in served { @@ -10700,9 +10452,7 @@ unsafe extern "C" fn gn_vkGetPhysicalDeviceSurfacePresentModesKHR( wsi_hb(); let surf = unsafe { find_surface(surface) }; if surf.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy surface present-modes query: {surface:#x} not one of ours" - )); + crate::logf!("proxy surface present-modes query: {surface:#x} not one of ours"); return VK_ERROR_SURFACE_LOST_KHR; } // The env's mode leads the list, as in Mesa: it decides the mode on both @@ -10769,9 +10519,7 @@ unsafe extern "C" fn gn_vkSetHdrMetadataEXT( for i in 0..swapchain_count as usize { let sc = unsafe { *swapchains.add(i) }; if unsafe { find_swapchain(sc) }.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy setHdrMetadata: swapchain {sc:#x} not one of ours" - )); + crate::logf!("proxy setHdrMetadata: swapchain {sc:#x} not one of ours"); return VK_ERROR_INITIALIZATION_FAILED; } } @@ -10872,9 +10620,7 @@ unsafe extern "C" fn gn_vkGetPhysicalDeviceSurfaceFormats2KHR( } let surface = unsafe { (*info).surface }; if unsafe { find_surface(surface) }.is_null() { - crate::logf!(gndrm_obf::obf!( - "proxy surface formats2 query: {surface:#x} not one of ours" - )); + crate::logf!("proxy surface formats2 query: {surface:#x} not one of ours"); return VK_ERROR_SURFACE_LOST_KHR; } let served = served_surface_formats(crate::scanout::layout()); @@ -11029,10 +10775,8 @@ unsafe extern "C" fn gn_vkCreateDevice( let gi = unsafe { find_instance_by_pd(pd) }; if gi.is_null() || unsafe { (*gi).f.create_device.is_none() } { loud("create_device.noinst", || { - format!("{}", gndrm_obf::obf!( - "proxy: vkCreateDevice NO INSTANCE pd={:#x} gi={} — guest device will be driver-raw (wrong-handle class)", - pd as usize, gi.is_null() - )) + format!("{}", format_args!("proxy: vkCreateDevice NO INSTANCE pd={:#x} gi={} — guest device will be driver-raw (wrong-handle class)", + pd as usize, gi.is_null())) }); return VK_ERROR_INITIALIZATION_FAILED; } @@ -11043,9 +10787,7 @@ unsafe extern "C" fn gn_vkCreateDevice( && import_mode(&|e: &CStr| have.iter().any(|h| h.as_c_str() == e), AHB_IMPORT_ALLOWED.load(Ordering::Relaxed)) == Some(true); if import_ahb && !AHB_MODE_LOGGED.swap(true, Ordering::Relaxed) { - crate::logf!(gndrm_obf::obf!( - "proxy device: importing swapchain slots as AHardwareBuffers" - )); + crate::logf!("proxy device: importing swapchain slots as AHardwareBuffers"); } let add_exts: &[&CStr] = if import_ahb { &AHB_EXTS } else { &DMA_BUF_EXTS }; let mut n: usize = 0; @@ -11061,18 +10803,14 @@ unsafe extern "C" fn gn_vkCreateDevice( 0 => 1 << 22, v => v, }; - crate::logf!(gndrm_obf::obf!( - "proxy device: guest enables {} extensions api={}.{}", + crate::logf!("proxy device: guest enables {} extensions api={}.{}", names.len(), (api >> 22) & 0x7F, - (api >> 12) & 0x3FF - )); + (api >> 12) & 0x3FF); if !WSI_DEVICE_LOGGED.swap(true, Ordering::Relaxed) { - crate::logi!(gndrm_obf::obf!( - "proxy device: WSI extensions hidden from the guest: [{}] requested and masked: [{}]", + crate::logi!("proxy device: WSI extensions hidden from the guest: [{}] requested and masked: [{}]", crate::wsi_policy::hidden_names(have.iter().map(|h| h.as_c_str())), - crate::wsi_policy::hidden_names(names.iter().map(|&o| unsafe { CStr::from_ptr(o) })) - )); + crate::wsi_policy::hidden_names(names.iter().map(|&o| unsafe { CStr::from_ptr(o) }))); } for &name in names { // The guest must never enable a WSI extension the proxy cannot honour, @@ -11099,10 +10837,8 @@ unsafe extern "C" fn gn_vkCreateDevice( || (strip_robustness2 && n_ == c"VK_EXT_robustness2") || (crate::placed::faked() && n_ == crate::placed::EXT_NAME) { - crate::logf!(gndrm_obf::obf!( - "proxy device: masking {}", - n_.to_string_lossy() - )); + crate::logf!("proxy device: masking {}", + n_.to_string_lossy()); continue; } if n < exts.len() { @@ -11127,10 +10863,8 @@ unsafe extern "C" fn gn_vkCreateDevice( } } if !have.is_empty() && !have.iter().any(|h| h.as_c_str() == add) { - crate::logf!(gndrm_obf::obf!( - "proxy device: driver lacks {}, not adding it", - add.to_string_lossy() - )); + crate::logf!("proxy device: driver lacks {}, not adding it", + add.to_string_lossy()); continue; } if n < exts.len() { @@ -11153,10 +10887,8 @@ unsafe extern "C" fn gn_vkCreateDevice( let mut i = 0; while i < n { if unsafe { CStr::from_ptr(exts[i]) } == drop { - crate::logf!(gndrm_obf::obf!( - "proxy device: masking {}", - drop.to_string_lossy() - )); + crate::logf!("proxy device: masking {}", + drop.to_string_lossy()); for j in i..n - 1 { exts[j] = exts[j + 1]; } @@ -11230,10 +10962,8 @@ unsafe extern "C" fn gn_vkCreateDevice( } } if !chain.is_empty() { - crate::logf!(gndrm_obf::obf!( - "proxy device: create chain [{}]", - chain.join(" ") - )); + crate::logf!("proxy device: create chain [{}]", + chain.join(" ")); } } // The feature lift is advertised to the guest, not asked of the driver @@ -11297,9 +11027,7 @@ unsafe extern "C" fn gn_vkCreateDevice( // The guest's own log hides this behind a generic E_FAIL; the driver's // code names the cause (VK_ERROR_FEATURE_NOT_PRESENT, EXTENSION_NOT_PRESENT, // INITIALIZATION_FAILED). - crate::logf!(gndrm_obf::obf!( - "proxy device: driver create failed res={}", res - )); + crate::logf!("proxy device: driver create failed res={}", res); } for &(prev, p) in unlinked.iter().rev() { if !prev.is_null() { @@ -11450,11 +11178,9 @@ unsafe extern "C" fn gn_vkCreateDevice( // word must keep pointing at the hooks' dispatch table). unsafe { *out = gd.cast::(); - crate::logf!(gndrm_obf::obf!( - "proxy device {:?} (real {:?}, queue family {qf})", + crate::logf!("proxy device {:?} (real {:?}, queue family {qf})", gd, - (*gd).real - )); + (*gd).real); } VK_SUCCESS } @@ -11545,10 +11271,8 @@ unsafe extern "C" fn gn_vkGetDeviceQueue( loud("get_device_queue.miss", || { format!( "{}", - gndrm_obf::obf!( - "proxy: gn_vkGetDeviceQueue DEVICE MISS family={family} index={index} {}", - unsafe { handle_note(false, device as usize, first, n) } - ) + format_args!("proxy: gn_vkGetDeviceQueue DEVICE MISS family={family} index={index} {}", + unsafe { handle_note(false, device as usize, first, n) }) ) }); unsafe { *out = ptr::null_mut() }; @@ -11588,7 +11312,7 @@ unsafe extern "C" fn gn_vkGetDeviceQueue2( loud("get_device_queue2.miss", || { format!( "{}", - gndrm_obf::obf!("proxy: gn_vkGetDeviceQueue2 DEVICE MISS {}", unsafe { + format_args!("proxy: gn_vkGetDeviceQueue2 DEVICE MISS {}", unsafe { handle_note(false, device as usize, first, n) }) ) @@ -11766,10 +11490,8 @@ fn dma_heap_open() -> i32 { let path = CString::new("/dev/dma_heap/system").unwrap(); let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) }; if fd < 0 { - crate::logf!(gndrm_obf::obf!( - "proxy: /dev/dma_heap/system: {}", - std::io::Error::last_os_error() - )); + crate::logf!("proxy: /dev/dma_heap/system: {}", + std::io::Error::last_os_error()); } fd }) @@ -11801,10 +11523,8 @@ fn dma_heap_alloc(len: usize) -> i32 { heap_flags: 0, }; if unsafe { libc::ioctl(heap, DMA_HEAP_IOCTL_ALLOC as _, &mut data) } != 0 { - crate::logf!(gndrm_obf::obf!( - "proxy: dma_heap alloc({len}): {}", - std::io::Error::last_os_error() - )); + crate::logf!("proxy: dma_heap alloc({len}): {}", + std::io::Error::last_os_error()); return -1; } data.fd as i32 @@ -11861,10 +11581,8 @@ unsafe fn pnext_image_create_summary(mut p: *const c_void) -> String { let e = p.cast::(); out.push_str(&format!( "{}", - gndrm_obf::obf!( - "ExternalMemoryImageCreateInfo{{handleTypes={:#x}}}", - unsafe { (*e).handleTypes } - ) + format_args!("ExternalMemoryImageCreateInfo{{handleTypes={:#x}}}", + unsafe { (*e).handleTypes }) )); } VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT => { @@ -11873,18 +11591,14 @@ unsafe fn pnext_image_create_summary(mut p: *const c_void) -> String { let cnt = unsafe { (*e).drmFormatModifierPlaneCount }; let pl = unsafe { (*e).pPlaneLayouts }; if !pl.is_null() && cnt > 0 { - out.push_str(&format!("{}", gndrm_obf::obf!( - "ImageDrmFormatModifierExplicitCreateInfoEXT{{mod={m:#x}, planes={cnt}, plane0{{offset={}, rowPitch={}, size={}}}}}", + out.push_str(&format!("{}", format_args!("ImageDrmFormatModifierExplicitCreateInfoEXT{{mod={m:#x}, planes={cnt}, plane0{{offset={}, rowPitch={}, size={}}}}}", unsafe { (*pl).offset }, unsafe { (*pl).rowPitch }, - unsafe { (*pl).size } - ))); + unsafe { (*pl).size }))); } else { out.push_str(&format!( "{}", - gndrm_obf::obf!( - "ImageDrmFormatModifierExplicitCreateInfoEXT{{mod={m:#x}, planes={cnt}}}" - ) + format_args!("ImageDrmFormatModifierExplicitCreateInfoEXT{{mod={m:#x}, planes={cnt}}}") )); } } @@ -11892,13 +11606,11 @@ unsafe fn pnext_image_create_summary(mut p: *const c_void) -> String { let e = p.cast::(); out.push_str(&format!( "{}", - gndrm_obf::obf!( - "ImageDrmFormatModifierListCreateInfoEXT{{count={}}}", - unsafe { (*e).drmFormatModifierCount } - ) + format_args!("ImageDrmFormatModifierListCreateInfoEXT{{count={}}}", + unsafe { (*e).drmFormatModifierCount }) )); } - _ => out.push_str(&format!("{}", gndrm_obf::obf!("sType={st}"))), + _ => out.push_str(&format!("{}", format_args!("sType={st}"))), } p = unsafe { (*b).pNext as *const c_void }; n += 1; @@ -11913,8 +11625,7 @@ unsafe fn trace_image_create(ci: &VkImageCreateInfo, tag: &str, shot: &AtomicBoo return; } let pnext = unsafe { pnext_image_create_summary(ci.pNext) }; - crate::logf!(gndrm_obf::obf!( - "{tag}: vkCreateImage fmt={} {}x{}x{} mips={} layers={} samples={:#x} tiling={} usage={:#x} flags={:#x} pNext=[{pnext}]", + crate::logf!("{tag}: vkCreateImage fmt={} {}x{}x{} mips={} layers={} samples={:#x} tiling={} usage={:#x} flags={:#x} pNext=[{pnext}]", ci.format, ci.extent.width, ci.extent.height, @@ -11924,8 +11635,7 @@ unsafe fn trace_image_create(ci: &VkImageCreateInfo, tag: &str, shot: &AtomicBoo ci.samples, ci.tiling, ci.usage, - ci.flags - )); + ci.flags); } /// Pure informational `vkGetPhysicalDeviceImageFormatProperties2` with a @@ -11947,9 +11657,7 @@ unsafe fn query_linear_modifier_support( let pd = unsafe { (*gd).pd }; let raw = unsafe { gn_real_inst_proc(inst, c"vkGetPhysicalDeviceImageFormatProperties2") }; let Some(_) = raw else { - crate::logf!(gndrm_obf::obf!( - "modq: vkGetPhysicalDeviceImageFormatProperties2 unresolved (driver/loader)" - )); + crate::logf!("modq: vkGetPhysicalDeviceImageFormatProperties2 unresolved (driver/loader)"); return; }; let query: PFN_vkGetPhysicalDeviceImageFormatProperties2 = unsafe { std::mem::transmute(raw) }; @@ -11999,8 +11707,7 @@ unsafe fn query_linear_modifier_support( }; let res = unsafe { query(pd, &fmtinfo, &mut props) }; let ip = props.imageFormatProperties; - crate::logf!(gndrm_obf::obf!( - "modq: vkGetPhysicalDeviceImageFormatProperties2 fmt={format} type=2D tiling={tiling} usage={usage:#x} pNext=VkPhysicalDeviceImageDrmFormatModifierInfoEXT{{mod=LINEAR(0), sharing=EXCLUSIVE}} -> res={res} maxExtent={}x{}x{} maxMips={} maxLayers={} samples={:#x} maxRes={} modCount={} mod0={:#x} feat0={:#x} planes0={} [informational only: result not consulted]", + crate::logf!("modq: vkGetPhysicalDeviceImageFormatProperties2 fmt={format} type=2D tiling={tiling} usage={usage:#x} pNext=VkPhysicalDeviceImageDrmFormatModifierInfoEXT{{mod=LINEAR(0), sharing=EXCLUSIVE}} -> res={res} maxExtent={}x{}x{} maxMips={} maxLayers={} samples={:#x} maxRes={} modCount={} mod0={:#x} feat0={:#x} planes0={} [informational only: result not consulted]", ip.maxExtent.width, ip.maxExtent.height, ip.maxExtent.depth, @@ -12011,8 +11718,7 @@ unsafe fn query_linear_modifier_support( modlist.drmFormatModifierCount, mods[0].drmFormatModifier, mods[0].drmFormatModifierTilingFeatures, - mods[0].drmFormatModifierPlaneCount - )); + mods[0].drmFormatModifierPlaneCount); } } @@ -12044,16 +11750,14 @@ unsafe fn log_mem_props_once(pd: VkPhysicalDevice, mp: &VkPhysicalDeviceMemoryPr let t = mp.memoryTypes[i]; format!( "{}", - gndrm_obf::obf!( - "t{i}:heap{}:flags{:#x}{}", + format_args!("t{i}:heap{}:flags{:#x}{}", t.heapIndex, t.propertyFlags, if t.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT != 0 { ":LOCAL" } else { "" - } - ) + }) ) }) .collect(); @@ -12061,21 +11765,17 @@ unsafe fn log_mem_props_once(pd: VkPhysicalDevice, mp: &VkPhysicalDeviceMemoryPr .map(|i| { format!( "{}", - gndrm_obf::obf!( - "h{i}:{}B:flags{:#x}", + format_args!("h{i}:{}B:flags{:#x}", mp.memoryHeaps[i].size, - mp.memoryHeaps[i].flags - ) + mp.memoryHeaps[i].flags) ) }) .collect(); - crate::logf!(gndrm_obf::obf!( - "memprops: types={} [{}] heaps={} [{}]", + crate::logf!("memprops: types={} [{}] heaps={} [{}]", mp.memoryTypeCount, summary.join(" "), mp.memoryHeapCount, - heaps.join(" ") - )); + heaps.join(" ")); } /// Read-only description of a chosen `memoryTypeIndex` (heap + DEVICE_LOCAL). @@ -12086,20 +11786,16 @@ fn mem_type_desc(gd: *mut GnDevice, idx: u32) -> String { let local = t.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT != 0; format!( "{}", - gndrm_obf::obf!( - "mem_type {idx} heap {} flags {:#x} DEVICE_LOCAL={}", + format_args!("mem_type {idx} heap {} flags {:#x} DEVICE_LOCAL={}", t.heapIndex, t.propertyFlags, - if local { "yes" } else { "no" } - ) + if local { "yes" } else { "no" }) ) } else { format!( "{}", - gndrm_obf::obf!( - "mem_type {idx} (beyond memoryTypeCount {})", - mp.memoryTypeCount - ) + format_args!("mem_type {idx} (beyond memoryTypeCount {})", + mp.memoryTypeCount) ) } } @@ -12128,9 +11824,7 @@ unsafe fn slot_init_with_usage( && std::env::var_os("GNDRM_EXPORT_AHB").is_some_and(|v| v == "1") { SLOT_DMABUF_REFUSED.store(true, Ordering::Relaxed); - crate::logf!(gndrm_obf::obf!( - "proxy slot: GNDRM_EXPORT_AHB=1, importing pool buffers as AHardwareBuffers from the start" - )); + crate::logf!("proxy slot: GNDRM_EXPORT_AHB=1, importing pool buffers as AHardwareBuffers from the start"); } if unsafe { (*gd).import_ahb } || SLOT_DMABUF_REFUSED.load(Ordering::Relaxed) { return unsafe { slot_init_ahb(sc, s, usage) }; @@ -12160,12 +11854,10 @@ unsafe fn slot_init_with_usage( if buf.stride != 0 { (*s).stride = buf.stride; } - crate::logf!(gndrm_obf::obf!( - "proxy slot: pool buffer fd={} ino={} stride={}", + crate::logf!("proxy slot: pool buffer fd={} ino={} stride={}", buf.fd, buf.ino, - (*s).stride - )); + (*s).stride); } None => { // No daemon channel, or it refused: a local system-heap @@ -12237,13 +11929,11 @@ unsafe fn slot_init_with_usage( }; let r1 = res; res = unsafe { f.create_image.unwrap()(dev, &ici2, ptr::null(), &mut (*s).image) }; - crate::logf!(gndrm_obf::obf!( - "proxy import image: LINEAR tiling {r1}; explicit LINEAR modifier (pitch {}) {res}", - (*s).stride - )); + crate::logf!("proxy import image: LINEAR tiling {r1}; explicit LINEAR modifier (pitch {}) {res}", + (*s).stride); } if res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!("proxy import image create failed: {res}")); + crate::logf!("proxy import image create failed: {res}"); return res; } // A plain LINEAR image's row pitch is the driver's choice, and the pool @@ -12295,13 +11985,11 @@ unsafe fn slot_init_with_usage( }; let mut img2: VkImage = 0; let r2 = unsafe { f.create_image.unwrap()(dev, &ici2, ptr::null(), &mut img2) }; - crate::logf!(gndrm_obf::obf!( - "proxy slot: LINEAR pitch {} != pool stride {} for {}x{}; explicit LINEAR modifier at the pool stride: {r2}", + crate::logf!("proxy slot: LINEAR pitch {} != pool stride {} for {}x{}; explicit LINEAR modifier at the pool stride: {r2}", l.rowPitch, (*s).stride, (*sc).extent.width, - (*sc).extent.height - )); + (*sc).extent.height); if r2 == VK_SUCCESS && img2 != 0 { unsafe { if let Some(destroy) = f.destroy_image { @@ -12317,14 +12005,12 @@ unsafe fn slot_init_with_usage( gn_real_device_proc(gd, c"vkGetAndroidHardwareBufferPropertiesANDROID") } .is_some(); - crate::logf!(gndrm_obf::obf!( - "proxy slot: LINEAR pitch {} != pool stride {} for {}x{}; {}", + crate::logf!("proxy slot: LINEAR pitch {} != pool stride {} for {}x{}; {}", l.rowPitch, (*s).stride, (*sc).extent.width, (*sc).extent.height, - if can_ahb { "importing pool buffer as AHardwareBuffer" } else { "no AHardwareBuffer import on this driver, frames will shear" } - )); + if can_ahb { "importing pool buffer as AHardwareBuffer" } else { "no AHardwareBuffer import on this driver, frames will shear" }); if can_ahb { SLOT_DMABUF_REFUSED.store(true, Ordering::Relaxed); unsafe { @@ -12354,17 +12040,15 @@ unsafe fn slot_init_with_usage( } } if mem_type == u32::MAX { - crate::logf!(gndrm_obf::obf!("proxy import image: no memory type")); + crate::logf!("proxy import image: no memory type"); return VK_ERROR_INITIALIZATION_FAILED; } - crate::logf!(gndrm_obf::obf!( - "proxy slot: linear {}x{} reqs {} memTypeBits {:#x} {}", + crate::logf!("proxy slot: linear {}x{} reqs {} memTypeBits {:#x} {}", (*sc).extent.width, (*sc).extent.height, reqs.size, reqs.memoryTypeBits, - mem_type_desc(gd, mem_type) - )); + mem_type_desc(gd, mem_type)); let ded = VkMemoryDedicatedAllocateInfo { sType: VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, pNext: ptr::null(), @@ -12394,9 +12078,7 @@ unsafe fn slot_init_with_usage( if unsafe { gn_real_device_proc(gd, c"vkGetAndroidHardwareBufferPropertiesANDROID") } .is_some() { - crate::logf!(gndrm_obf::obf!( - "proxy slot: dma-buf import failed ({res}), importing pool buffer as AHardwareBuffer" - )); + crate::logf!("proxy slot: dma-buf import failed ({res}), importing pool buffer as AHardwareBuffer"); SLOT_DMABUF_REFUSED.store(true, Ordering::Relaxed); unsafe { if let Some(destroy) = f.destroy_image { @@ -12411,7 +12093,7 @@ unsafe fn slot_init_with_usage( } } if res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!("proxy import memory failed: {res}")); + crate::logf!("proxy import memory failed: {res}"); return res; } slot_init_sync(sc, s) @@ -12476,9 +12158,7 @@ unsafe fn slot_init_ahb( } let (width, height) = unsafe { ((*sc).extent.width, (*sc).extent.height) }; let Some(buf) = crate::scanout::allocate_ahb(width, height) else { - crate::logf!(gndrm_obf::obf!( - "proxy slot: no AHardwareBuffer from the daemon for {width}x{height}" - )); + crate::logf!("proxy slot: no AHardwareBuffer from the daemon for {width}x{height}"); return VK_ERROR_INITIALIZATION_FAILED; }; unsafe { @@ -12500,9 +12180,7 @@ unsafe fn slot_init_ahb( )) }; let Some(get_props) = get_props else { - crate::logf!(gndrm_obf::obf!( - "proxy slot: driver resolves no vkGetAndroidHardwareBufferPropertiesANDROID" - )); + crate::logf!("proxy slot: driver resolves no vkGetAndroidHardwareBufferPropertiesANDROID"); return VK_ERROR_INITIALIZATION_FAILED; }; let mut fmt = AhbFormatProperties { @@ -12521,16 +12199,14 @@ unsafe fn slot_init_ahb( memory_type_bits: 0, }; let res = unsafe { get_props(dev, buf.ahb, &mut props) }; - crate::logf!(gndrm_obf::obf!( - "proxy slot: AHB fd={} ino={} stride={} size {} memTypeBits {:#x} format {} (swapchain {}): {res}", + crate::logf!("proxy slot: AHB fd={} ino={} stride={} size {} memTypeBits {:#x} format {} (swapchain {}): {res}", buf.fd, buf.ino, unsafe { (*s).stride }, props.allocation_size, props.memory_type_bits, fmt.format, - unsafe { (*sc).format } - )); + unsafe { (*sc).format }); if res != VK_SUCCESS || props.memory_type_bits == 0 { return if res != VK_SUCCESS { res } else { VK_ERROR_INITIALIZATION_FAILED }; } @@ -12562,7 +12238,7 @@ unsafe fn slot_init_ahb( }; let res = unsafe { f.create_image.unwrap()(dev, &ici, ptr::null(), &mut (*s).image) }; if res != VK_SUCCESS { - crate::logf!(gndrm_obf::obf!("proxy import image (AHB) create failed: {res}")); + crate::logf!("proxy import image (AHB) create failed: {res}"); return res; } let mem_type = (0..32u32) @@ -12594,11 +12270,9 @@ unsafe fn slot_init_ahb( if res == VK_SUCCESS { res = unsafe { f.bind_mem.unwrap()(dev, (*s).image, (*s).mem, 0) }; } - crate::logf!(gndrm_obf::obf!( - "proxy slot: AHB import {width}x{height} type {} {}: {res}", + crate::logf!("proxy slot: AHB import {width}x{height} type {} {}: {res}", mem_type, - mem_type_desc(gd, mem_type) - )); + mem_type_desc(gd, mem_type)); if res != VK_SUCCESS { return res; } diff --git a/icd_shim/src/resolve_probe.rs b/icd_shim/src/resolve_probe.rs index 9d171a2..30db15e 100644 --- a/icd_shim/src/resolve_probe.rs +++ b/icd_shim/src/resolve_probe.rs @@ -241,7 +241,7 @@ pub unsafe fn for_pd(pd: VkPhysicalDevice) -> Option> { let driver_api = props.apiVersion; let instance_api = unsafe { (*gi).forwarded_api }; let outcome = if let Some(why) = skip_reason(driver_api, instance_api) { - crate::logi!(gndrm_obf::obf!("proxy pd: resolve probe: skipped ({why})")); + crate::logi!("proxy pd: resolve probe: skipped ({why})"); Outcome::default() } else { let t = Instant::now(); @@ -250,17 +250,13 @@ pub unsafe fn for_pd(pd: VkPhysicalDevice) -> Option> { match r { Ok(v) => { let o = Outcome::from_verdict(&v, driver_api); - crate::logi!(gndrm_obf::obf!( - "proxy pd: resolve probe: {} ({ms:.1} ms)", - o.describe(driver_api) - )); + crate::logi!("proxy pd: resolve probe: {} ({ms:.1} ms)", + o.describe(driver_api)); o } Err(why) => { - crate::logi!(gndrm_obf::obf!( - "proxy pd: resolve probe: did not run ({why}); core version {} kept ({ms:.1} ms)", - ver(driver_api) - )); + crate::logi!("proxy pd: resolve probe: did not run ({why}); core version {} kept ({ms:.1} ms)", + ver(driver_api)); Outcome::default() } } diff --git a/icd_shim/src/scanout.rs b/icd_shim/src/scanout.rs index e2d39ac..e478cb7 100644 --- a/icd_shim/src/scanout.rs +++ b/icd_shim/src/scanout.rs @@ -150,11 +150,9 @@ fn apply_note(note: FrameCapNote) { CAP_FPS.store(note.fps, Ordering::Relaxed); // 0 while frame generation paces the session: log what is actually in force // now that the note is adopted, not what it carried. - crate::logf!(gndrm_obf::obf!( - "scanout frame cap: fps={} effective={}", + crate::logf!("scanout frame cap: fps={} effective={}", note.fps, - target_fps() - )); + target_fps()); } /// The target in force, [`FPS_UNCAPPED`] when none has: read by the shim's @@ -585,9 +583,7 @@ fn exchange_req(fd: RawFd, req: ScanoutAllocReq) -> Result let got = ahb_recv_api() .map_or(-1, |api| (api.recv)(fd, &mut ahb)); if got != 0 || ahb.is_null() { - crate::logf!(gndrm_obf::obf!( - "scan-out: AHardwareBuffer handle not received ({got})" - )); + crate::logf!("scan-out: AHardwareBuffer handle not received ({got})"); libc::close(recv_fd); return Err(Failure::Dead); } @@ -626,11 +622,9 @@ fn note_pool_fd_kind(fd: RawFd, ino: u64) { let size = if libc::fstat(fd, &mut st) == 0 { st.st_size as u64 } else { 0 }; (magic, size) }; - crate::logf!(gndrm_obf::obf!( - "scan-out: pool fd ino={ino} size={size} fs={magic:#x} dma-buf={} link={}", + crate::logf!("scan-out: pool fd ino={ino} size={size} fs={magic:#x} dma-buf={} link={}", magic == 0x444d_4142, - fd_link(fd) - )); + fd_link(fd)); } /// The `/proc/self/fd` link of `fd` (`/dmabuf:…` for a dma-buf), empty when it @@ -795,7 +789,7 @@ mod tests { let mut buf = [0u8; FrameCapSubscribe::LEN]; let n = libc::recv(conn, buf.as_mut_ptr().cast(), buf.len(), 0); assert_eq!(n as usize, FrameCapSubscribe::LEN); - let sub = FrameCapSubscribe::decode(&buf).expect(&gndrm_obf::obf!("subscribe frame")); + let sub = FrameCapSubscribe::decode(&buf).expect("subscribe frame"); assert_eq!(sub.caps & CAP_FRAME_CAP, CAP_FRAME_CAP); } } @@ -816,7 +810,7 @@ mod tests { /// with a `/dev/null` descriptor, which is all the transport needs. #[test] fn connect_and_exchange_receive_a_pool_buffer() { - let name = format!("{}", gndrm_obf::obf!("gndrm-icdsc-{}", std::process::id())); + let name = format!("{}", format_args!("gndrm-icdsc-{}", std::process::id())); let listener = listen(&name); let server = std::thread::spawn(move || { // SAFETY: accept on the listener created above, then recv/send on @@ -833,7 +827,7 @@ mod tests { let mut buf = [0u8; ScanoutAllocReq::LEN]; let n = libc::recv(conn, buf.as_mut_ptr().cast(), buf.len(), 0); assert_eq!(n as usize, ScanoutAllocReq::LEN); - let req = ScanoutAllocReq::decode(&buf).expect(&gndrm_obf::obf!("request frame")); + let req = ScanoutAllocReq::decode(&buf).expect("request frame"); assert_eq!((req.width, req.height), (1280, 960)); assert_eq!(req.format, scanout_ahb_format(ScanoutLayout::Bgra8888)); assert_eq!(req.len, 1280 * 960 * 4); @@ -859,7 +853,7 @@ mod tests { assert!(fd >= 0, "connect: {}", std::io::Error::last_os_error()); let got = exchange(fd, 1280, 960) .ok() - .expect(&gndrm_obf::obf!("exchange")); + .expect("exchange"); assert_eq!(got.stride, 5120); // The received descriptor is the one the daemon sent, and the reply's // identity is that descriptor's inode — the registration key. @@ -871,7 +865,7 @@ mod tests { libc::close(got.fd); libc::close(fd); } - server.join().expect(&gndrm_obf::obf!("server thread")); + server.join().expect("server thread"); } /// The frame-cap note stands ahead of the hand-out reply, where the shim @@ -879,7 +873,7 @@ mod tests { /// magic, so the target is adopted and the reply is still the reply. #[test] fn exchange_sorts_the_frame_cap_note_from_the_reply() { - let name = format!("{}", gndrm_obf::obf!("gndrm-icdcap-{}", std::process::id())); + let name = format!("{}", format_args!("gndrm-icdcap-{}", std::process::id())); let listener = listen(&name); let server = std::thread::spawn(move || { // SAFETY: accept on the listener created above; every frame is a @@ -924,8 +918,8 @@ mod tests { assert!(fd >= 0, "connect: {}", std::io::Error::last_os_error()); let got = exchange(fd, 1280, 960) .ok() - .expect(&gndrm_obf::obf!("exchange")); - let ino = server.join().expect(&gndrm_obf::obf!("server thread")); + .expect("exchange"); + let ino = server.join().expect("server thread"); assert_eq!(got.ino, ino); // The note ahead of the reply set the target. assert_eq!(target_fps(), 120); diff --git a/icd_shim/src/segv.rs b/icd_shim/src/segv.rs index bc3da7a..809794b 100644 --- a/icd_shim/src/segv.rs +++ b/icd_shim/src/segv.rs @@ -53,9 +53,7 @@ pub fn install() { #[cfg(target_arch = "aarch64")] imp::install(); #[cfg(not(target_arch = "aarch64"))] - crate::logf!(gndrm_obf::obf!( - "segv: register dump is aarch64-only; inert on this build" - )); + crate::logf!("segv: register dump is aarch64-only; inert on this build"); } #[cfg(target_arch = "aarch64")] @@ -97,7 +95,7 @@ mod imp { // Escape hatch: GN_VKSHIM_SEGV=0 keeps the handler out entirely. if let Some(v) = std::env::var_os("GN_VKSHIM_SEGV") { if v == "0" || v.is_empty() { - crate::logf!(gndrm_obf::obf!("segv: dump disabled by GN_VKSHIM_SEGV")); + crate::logf!("segv: dump disabled by GN_VKSHIM_SEGV"); return; } } @@ -120,9 +118,7 @@ mod imp { core::ptr::addr_of_mut!(PREV_BUS).cast::(), ); } - crate::logf!(gndrm_obf::obf!( - "segv: chaining dump installed (segv per-pc {PER_PC}, {NPCS} pcs, max {MAX_TOTAL}; sigbus sampled {MAX_BUS})" - )); + crate::logf!("segv: chaining dump installed (segv per-pc {PER_PC}, {NPCS} pcs, max {MAX_TOTAL}; sigbus sampled {MAX_BUS})"); } /// Bounded, per-PC rate limit. Async-signal-safe (atomics only). diff --git a/icd_shim/src/thunk.rs b/icd_shim/src/thunk.rs index 9bce4b2..34d04e2 100644 --- a/icd_shim/src/thunk.rs +++ b/icd_shim/src/thunk.rs @@ -173,10 +173,8 @@ pub fn thunk_for(name: &str, target: PFN_vkVoidFunction) -> PFN_vkVoidFunction { libc::mprotect(st.page.cast(), PAGE, libc::PROT_READ | libc::PROT_EXEC) }; if ret != 0 { - crate::logf!(gndrm_obf::obf!( - "proxy: thunk page mprotect failed: {}", - errno_str() - )); + crate::logf!("proxy: thunk page mprotect failed: {}", + errno_str()); } } let fnptr = Some(f); @@ -187,19 +185,15 @@ pub fn thunk_for(name: &str, target: PFN_vkVoidFunction) -> PFN_vkVoidFunction { drop(guard); log_retarget(name, served, addr); if cached.is_none() || served == Served::First { - crate::logf!(gndrm_obf::obf!( - "proxy: thunk -> {name} = {addr:#x} {}", - describe(addr) - )); + crate::logf!("proxy: thunk -> {name} = {addr:#x} {}", + describe(addr)); } fnptr } fn log_retarget(name: &str, served: Served, addr: usize) { if let Served::Retarget(old) = served { - crate::logf!(gndrm_obf::obf!( - "proxy: thunk retarget {name}: {old:#x} -> {addr:#x}" - )); + crate::logf!("proxy: thunk retarget {name}: {old:#x} -> {addr:#x}"); } } @@ -209,15 +203,15 @@ fn describe(addr: usize) -> String { let mut info: libc::Dl_info = unsafe { std::mem::zeroed() }; let found = unsafe { libc::dladdr(addr as *const libc::c_void, &raw mut info) }; if found == 0 || info.dli_fname.is_null() { - return gndrm_obf::obf!("anon").to_string(); + return "anon".to_string(); } let lib = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) }.to_string_lossy(); if info.dli_sname.is_null() { let off = addr.wrapping_sub(info.dli_fbase as usize); - return format!("{}", gndrm_obf::obf!("{lib}+{off:#x}")); + return format!("{}", format_args!("{lib}+{off:#x}")); } let sym = unsafe { std::ffi::CStr::from_ptr(info.dli_sname) }.to_string_lossy(); - format!("{}", gndrm_obf::obf!("{sym} ({lib})")) + format!("{}", format_args!("{sym} ({lib})")) } pub fn errno_str() -> String { diff --git a/icd_shim/src/x11.rs b/icd_shim/src/x11.rs index 5ff4f33..9b9eca2 100644 --- a/icd_shim/src/x11.rs +++ b/icd_shim/src/x11.rs @@ -678,9 +678,7 @@ unsafe fn resolve_override_target_on(conn: *mut xcb_connection_t, named: u32) -> let ancestor = resolved.window; let (aw, ah) = unsafe { window_size(conn, ancestor) }; if !is_degenerate(aw, ah) { - crate::logf!(gndrm_obf::obf!( - "override target: named=0x{named:x} ancestor=0x{ancestor:x} {aw}x{ah} -> 0x{ancestor:x} (legitimate; unchanged)" - )); + crate::logf!("override target: named=0x{named:x} ancestor=0x{ancestor:x} {aw}x{ah} -> 0x{ancestor:x} (legitimate; unchanged)"); return OverrideTarget { window: ancestor, provisional: false }; } @@ -742,12 +740,10 @@ unsafe fn resolve_override_target_on(conn: *mut xcb_connection_t, named: u32) -> let cstr = String::from_utf8_lossy(&ccls[..cn]); report.push_str(&format!( "{}", - gndrm_obf::obf!( - " 0x{c:x} {w}x{h} pid={cpid} class=\"{cstr}\"{}{}{}", + format_args!(" 0x{c:x} {w}x{h} pid={cpid} class=\"{cstr}\"{}{}{}", if c == focus { " " } else { "" }, if c == active { " " } else { "" }, - if matched { " " } else { "" }, - ) + if matched { " " } else { "" },) )); } if matched { @@ -769,10 +765,8 @@ unsafe fn resolve_override_target_on(conn: *mut xcb_connection_t, named: u32) -> } else { (ancestor, "no-candidate") }; - crate::logf!(gndrm_obf::obf!( - "override target: named=0x{named:x} ancestor=0x{ancestor:x} {aw}x{ah} -> 0x{chosen:x} ({why}; self_pid={self_pid} named_pid={named_pid} named_class=\"{}\"; root_children:{report})", - String::from_utf8_lossy(&named_cls[..named_cls_len]) - )); + crate::logf!("override target: named=0x{named:x} ancestor=0x{ancestor:x} {aw}x{ah} -> 0x{chosen:x} ({why}; self_pid={self_pid} named_pid={named_pid} named_class=\"{}\"; root_children:{report})", + String::from_utf8_lossy(&named_cls[..named_cls_len])); // Every answer from this half of the rule came out of the fallback, so the // target is a reading of the tree as it is now: the guest has not committed // a frame yet, and the window it will render into may not even be mapped. @@ -970,9 +964,7 @@ impl X11Present { ) }; if attr.is_null() { - crate::logf!(gndrm_obf::obf!( - "x11 window: 0x{w:x} attributes unavailable at level {level}" - )); + crate::logf!("x11 window: 0x{w:x} attributes unavailable at level {level}"); return; } let (map, or, class) = @@ -993,9 +985,7 @@ impl X11Present { 1 => "IsUnviewable", _ => "IsViewable", }; - crate::logf!(gndrm_obf::obf!( - "x11 window: level={level} id=0x{w:x} map={ms} override={or} class={class} {gw}x{gh}" - )); + crate::logf!("x11 window: level={level} id=0x{w:x} map={ms} override={or} class={class} {gw}x{gh}"); let tree = unsafe { xcb_query_tree_reply(self.conn, xcb_query_tree(self.conn, w), ptr::null_mut()) }; @@ -1012,18 +1002,14 @@ impl X11Present { // The outcome the presenter depends on: the root child the present // lands in. Named once, unconditionally. if self.window == origin { - crate::logf!(gndrm_obf::obf!( - "x11 present target: 0x{:x} (named window is already a root child)", - self.window - )); + crate::logf!("x11 present target: 0x{:x} (named window is already a root child)", + self.window); } else { - crate::logf!(gndrm_obf::obf!( - "x11 present target: 0x{:x} offset=({},{}) (root child of named window 0x{:x})", + crate::logf!("x11 present target: 0x{:x} offset=({},{}) (root child of named window 0x{:x})", self.window, self.x_off, self.y_off, - origin - )); + origin); } } @@ -1060,10 +1046,8 @@ impl X11Present { // The dup is what libxcb closes; the slot keeps `fd`. let import_fd = unsafe { libc::dup(fd) }; if import_fd < 0 { - crate::logf!(gndrm_obf::obf!( - "x11: dup of slot fd failed: {} - frame dropped", - std::io::Error::last_os_error() - )); + crate::logf!("x11: dup of slot fd failed: {} - frame dropped", + std::io::Error::last_os_error()); return None; } let pixmap = unsafe { xcb_generate_id(self.conn) }; @@ -1095,9 +1079,7 @@ impl X11Present { match unsafe { check_err(self.conn, cookie) } { None => Some(pixmap), Some(code) => { - crate::logf!(gndrm_obf::obf!( - "x11: {width}x{height} stride={stride} modifier={modifier:#x} pixmap_from_buffers failed (X error {code}) - frame dropped" - )); + crate::logf!("x11: {width}x{height} stride={stride} modifier={modifier:#x} pixmap_from_buffers failed (X error {code}) - frame dropped"); None } } @@ -1120,9 +1102,7 @@ impl X11Present { match unsafe { check_err(self.conn, cookie) } { None => Some(fence), Some(code) => { - crate::logf!(gndrm_obf::obf!( - "x11: sync fence create failed (X error {code}) - frame dropped" - )); + crate::logf!("x11: sync fence create failed (X error {code}) - frame dropped"); None } } @@ -1174,9 +1154,7 @@ impl X11Present { ) }; if let Some(code) = unsafe { check_err(self.conn, cookie) } { - crate::logf!(gndrm_obf::obf!( - "x11: present of pixmap {pixmap} failed (X error {code}) - frame dropped" - )); + crate::logf!("x11: present of pixmap {pixmap} failed (X error {code}) - frame dropped"); return None; } Some(serial) @@ -1314,16 +1292,14 @@ mod tests { let conn = unsafe { xcb_connect(ptr::null(), ptr::null_mut()) }; if conn.is_null() || unsafe { xcb_connection_has_error(conn) } != 0 { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (DISPLAY unreachable)") + "skip: no X server (DISPLAY unreachable)" ); return; } let screen = unsafe { host_root(conn) }; let Some((root, depth)) = screen else { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (no screen in setup)") + "skip: no X server (no screen in setup)" ); unsafe { xcb_disconnect(conn) }; return; @@ -1379,11 +1355,9 @@ mod tests { }), "a nested client window resolves to its root-child ancestor with its offset" ); - eprintln!("{}", gndrm_obf::obf!( - "DEBUG root={root:#x} depth={depth} top={top:#x} client={client:#x} from_client={:?} from_top={:?}", + eprintln!("{}", format_args!("DEBUG root={root:#x} depth={depth} top={top:#x} client={client:#x} from_client={:?} from_top={:?}", unsafe { resolve_target(conn, client) }, - unsafe { resolve_target(conn, top) } - )); + unsafe { resolve_target(conn, top) })); assert_eq!( unsafe { resolve_target(conn, top) }, Some(PresentTarget { @@ -1415,16 +1389,14 @@ mod tests { let conn = unsafe { xcb_connect(ptr::null(), ptr::null_mut()) }; if conn.is_null() || unsafe { xcb_connection_has_error(conn) } != 0 { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (DISPLAY unreachable)") + "skip: no X server (DISPLAY unreachable)" ); return; } let screen = unsafe { host_root(conn) }; let Some((root, depth)) = screen else { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (no screen in setup)") + "skip: no X server (no screen in setup)" ); unsafe { xcb_disconnect(conn) }; return; @@ -1519,8 +1491,7 @@ mod tests { let game_attr = unsafe { window_attr(conn, game) }; if game_attr.map(|(m, _, _)| m) != Some(MAP_STATE_VIEWABLE) { eprintln!( - "{}", - gndrm_obf::obf!("skip: test window not viewable (host WM interference)") + "skip: test window not viewable (host WM interference)" ); unsafe { xcb_destroy_window(conn, named); @@ -1574,16 +1545,14 @@ mod tests { let conn = unsafe { xcb_connect(ptr::null(), ptr::null_mut()) }; if conn.is_null() || unsafe { xcb_connection_has_error(conn) } != 0 { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (DISPLAY unreachable)") + "skip: no X server (DISPLAY unreachable)" ); return; } let screen = unsafe { host_root(conn) }; let Some((root, depth)) = screen else { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (no screen in setup)") + "skip: no X server (no screen in setup)" ); unsafe { xcb_disconnect(conn) }; return; @@ -1615,7 +1584,7 @@ mod tests { Err(why) => { eprintln!( "{}", - gndrm_obf::obf!("skip: host X server has no DRI3/Present ({})", why.reason()) + format_args!("skip: host X server has no DRI3/Present ({})", why.reason()) ); unsafe { xcb_destroy_window(conn, window); @@ -1629,7 +1598,7 @@ mod tests { // regardless of whether the server accepts the buffer, so the slot's // ownership is what is under test, not the payload. let file = - std::fs::File::open("/etc/hostname").expect(&gndrm_obf::obf!("open /etc/hostname")); + std::fs::File::open("/etc/hostname").expect("open /etc/hostname"); let fd = file.as_raw_fd(); assert!( unsafe { libc::fcntl(fd, libc::F_GETFD) } >= 0, @@ -1653,7 +1622,7 @@ mod tests { fn open_fd_count() -> usize { std::fs::read_dir("/proc/self/fd") - .expect(&gndrm_obf::obf!("/proc/self/fd")) + .expect("/proc/self/fd") .count() } @@ -1669,15 +1638,13 @@ mod tests { let conn = unsafe { xcb_connect(ptr::null(), ptr::null_mut()) }; if conn.is_null() || unsafe { xcb_connection_has_error(conn) } != 0 { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (DISPLAY unreachable)") + "skip: no X server (DISPLAY unreachable)" ); return; } let Some((root, depth)) = (unsafe { host_root(conn) }) else { eprintln!( - "{}", - gndrm_obf::obf!("skip: no X server (no screen in setup)") + "skip: no X server (no screen in setup)" ); unsafe { xcb_disconnect(conn) }; return; @@ -1706,7 +1673,7 @@ mod tests { Err(why) => { eprintln!( "{}", - gndrm_obf::obf!("skip: host X server has no DRI3/Present ({})", why.reason()) + format_args!("skip: host X server has no DRI3/Present ({})", why.reason()) ); unsafe { xcb_destroy_window(conn, window); @@ -1760,9 +1727,7 @@ mod tests { } } let after = open_fd_count(); - eprintln!("{}", gndrm_obf::obf!( - "DEBUG present-loop: fds before={before} after={after} N={N} xpix={xpix} xfence={xfence}" - )); + eprintln!("{}", format_args!("DEBUG present-loop: fds before={before} after={after} N={N} xpix={xpix} xfence={xfence}")); assert!( after <= before + 1, "the present path acquired descriptors per frame: {before} -> {after} over {N} frames" diff --git a/modules/gndrm-android/Cargo.toml b/modules/gndrm-android/Cargo.toml index 24f7fc6..5762cb2 100644 --- a/modules/gndrm-android/Cargo.toml +++ b/modules/gndrm-android/Cargo.toml @@ -11,11 +11,6 @@ authors.workspace = true name = "gamenative_drm" crate-type = ["cdylib"] -# `gndrm-obf` is target-independent (pure std) and used by the Android cdylib -# and by the host integration tests that include `src/*.rs` verbatim. -[dependencies] -gndrm-obf = { path = "../gndrm-obf" } - # Everything Android-specific is an android-only dependency: on the host the # crate compiles to an empty stub so workspace-wide fmt/clippy/test stay green # (real verification of this module is `tools/build-android.sh` + on-device). diff --git a/modules/gndrm-android/src/asc.rs b/modules/gndrm-android/src/asc.rs index 8caae19..aa14bc1 100644 --- a/modules/gndrm-android/src/asc.rs +++ b/modules/gndrm-android/src/asc.rs @@ -130,8 +130,7 @@ static DUMP_DIR: OnceLock> = OnceLock::new(); /// Daemon diagnostics are opt-in per session (`GNDRM_LOG_DAEMON`, set by the /// launcher in this process): the daemon shares the app's address space, so a /// container's `GNDRM_LOG_*` cannot reach it, and a shipped session must not -/// describe the presenter in logcat. Every message is also `obf!`-encoded, so -/// the shipped binary does not carry the text either. +/// describe the presenter in logcat. macro_rules! asc_log { ($($arg:tt)*) => { if gndrm_daemon::verbose_logging() { @@ -690,9 +689,7 @@ impl ScanoutPool { /// A fresh completion mailbox for one registration, with the reuse gate /// the completion callback publishes into. fn new_ctx(&self) -> (*mut ReleaseCtx, Arc) { - let api = self.api.expect(&gndrm_obf::obf!( - "a slot is only committed when the presenter is enabled" - )); + let api = self.api.expect(&"a slot is only committed when the presenter is enabled"); new_release_ctx(&api) } @@ -736,12 +733,10 @@ impl ScanoutPool { // resolves to this geometry. Idempotent: the length index keeps the // first geometry noted for a (length, format) pair. self.cache.note_geometry(geom, buffer.size); - log_info!("{}", gndrm_obf::obf!( - "asc: scan-out {width}x{height} {origin} (ino={}, stride={}, pool={}/{MAX_SCANOUT_POOL})", + log_info!("{}", format_args!("asc: scan-out {width}x{height} {origin} (ino={}, stride={}, pool={}/{MAX_SCANOUT_POOL})", buffer.ino, buffer.stride, - self.owned() - )); + self.owned())); replaced } @@ -1079,24 +1074,16 @@ impl AscState { }); if loaded.is_none() { log_warn!( - "{}", - gndrm_obf::obf!( - "asc: SurfaceControl API unavailable (pre-API-29?); publishing disabled" - ) + "asc: SurfaceControl API unavailable (pre-API-29?); publishing disabled" ); } else if sc.is_null() { log_warn!( - "{}", - gndrm_obf::obf!( - "asc: ASurfaceControl_createFromWindow failed; publishing disabled" - ) + "asc: ASurfaceControl_createFromWindow failed; publishing disabled" ); } else { log_info!( "{}", - gndrm_obf::obf!( - "asc: SurfaceControl layer created (mode {mode_w}x{mode_h} in a {win_w}x{win_h} window)" - ) + format_args!("asc: SurfaceControl layer created (mode {mode_w}x{mode_h} in a {win_w}x{win_h} window)") ); } // The `ALooper` is deliberately *not* prepared here. This function runs @@ -1198,13 +1185,11 @@ impl AscState { if !PUBLISH_SEEN.swap(true, Ordering::Relaxed) { asc_log!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: publish entry fb={} ino_set={} api_set={} sc_set={}", + format_args!("gndrm-daemon: publish entry fb={} ino_set={} api_set={} sc_set={}", fb.id, ino.is_some(), self.api.is_some(), - !self.sc.is_null() - ) + !self.sc.is_null()) ); } } @@ -1279,7 +1264,7 @@ impl AscState { self.last_rect_log = Some(key); asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc layer rect src=({},{})-({},{}) dst=({},{})-({},{}) mode={}x{} window={}x{} band left={} top={} right={} bottom={} drawable={}",key.0, + format_args!("gndrm-daemon: asc layer rect src=({},{})-({},{}) dst=({},{})-({},{}) mode={}x{} window={}x{} band left={} top={} right={} bottom={} drawable={}",key.0, key.1, key.2, key.3, @@ -1363,11 +1348,11 @@ impl AscState { self.logged_unregistered.push(ino); asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc DROPPED frame: no AHardwareBuffer for dma-buf ino {ino} (misses={misses})") + format_args!("gndrm-daemon: asc DROPPED frame: no AHardwareBuffer for dma-buf ino {ino} (misses={misses})") ); asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc dropped framebuffer: {}x{} fmt={:#x} pitch={} (ino {ino})",fb.width, + format_args!("gndrm-daemon: asc dropped framebuffer: {}x{} fmt={:#x} pitch={} (ino {ino})",fb.width, fb.height, fb.pixel_format, fb.pitches[0]) @@ -1426,9 +1411,7 @@ impl AscState { if pending >= 0 { if wait_fence(pending) && !self.warned_fence_timeout { self.warned_fence_timeout = true; - log_warn!("{}", gndrm_obf::obf!( - "asc: previous release fence timed out; reusing buffer anyway (logged once)" - )); + log_warn!("{}", "asc: previous release fence timed out; reusing buffer anyway (logged once)"); } // SAFETY: `pending` is a valid descriptor owned by this call. unsafe { libc::close(pending) }; @@ -1439,7 +1422,7 @@ impl AscState { if copy_failed { asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc DROPPED frame: foreign dma-buf ino {ino} could not be copied (misses={misses})") + format_args!("gndrm-daemon: asc DROPPED frame: foreign dma-buf ino {ino} could not be copied (misses={misses})") ); close_fence(fence); } else if drawable { @@ -1456,11 +1439,11 @@ impl AscState { self.logged_stale.push(ino); asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc STALE re-publish: no AHardwareBuffer for dma-buf ino {ino}; re-publishing ino {published_ino} (misses={misses})") + format_args!("gndrm-daemon: asc STALE re-publish: no AHardwareBuffer for dma-buf ino {ino}; re-publishing ino {published_ino} (misses={misses})") ); asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc stale framebuffer: {}x{} fmt={:#x} pitch={} (ino {ino})",fb.width, + format_args!("gndrm-daemon: asc stale framebuffer: {}x{} fmt={:#x} pitch={} (ino {ino})",fb.width, fb.height, fb.pixel_format, fb.pitches[0]) @@ -1535,7 +1518,7 @@ impl AscState { }; asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc hdr decision n={} fb={} ino={} {} fmt={:#x} buffer10={} conn_hdr={} dataspace={:#x}",publish_n, + format_args!("gndrm-daemon: asc hdr decision n={} fb={} ino={} {} fmt={:#x} buffer10={} conn_hdr={} dataspace={:#x}",publish_n, fb.id, published_ino, sample, @@ -1560,7 +1543,7 @@ impl AscState { self.hidden = false; asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc layer shown again fb={} dst=({},{})-({},{}) mode={}x{} window={}x{}",fb.id, + format_args!("gndrm-daemon: asc layer shown again fb={} dst=({},{})-({},{}) mode={}x{} window={}x{}",fb.id, dst.left, dst.top, dst.right, @@ -1613,7 +1596,7 @@ impl AscState { self.hidden = true; asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc layer HIDDEN (plane not drawable) fb={} src=({},{})-({},{}) dst=({},{})-({},{}) mode={}x{} window={}x{}",fb.id, + format_args!("gndrm-daemon: asc layer HIDDEN (plane not drawable) fb={} src=({},{})-({},{}) dst=({},{})-({},{}) mode={}x{} window={}x{}",fb.id, src.left, src.top, src.right, @@ -1715,13 +1698,11 @@ impl AscState { self.foreign_logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: foreign dma-buf ino={ino} {}x{} fourcc={} pitch={} -> copied into pool (reason: not pool-backed)", + format_args!("gndrm-daemon: foreign dma-buf ino={ino} {}x{} fourcc={} pitch={} -> copied into pool (reason: not pool-backed)", fb.width, fb.height, gndrm_daemon::foreign::fourcc_name(fb.pixel_format), - fb.pitches[0] - ) + fb.pitches[0]) ); } true @@ -1743,9 +1724,7 @@ impl AscState { self.foreign_logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: foreign dma-buf ino={ino} {layout} copy FAILED ({reason}); frames dropped" - ) + format_args!("gndrm-daemon: foreign dma-buf ino={ino} {layout} copy FAILED ({reason}); frames dropped") ); } } @@ -1843,7 +1822,7 @@ impl AscState { if rc != 0 || base.is_null() { crate::log::daemon_info(&format!( "{}", - gndrm_obf::obf!("dump {n}: AHardwareBuffer_lock failed (rc={rc})") + format_args!("dump {n}: AHardwareBuffer_lock failed (rc={rc})") )); return; } @@ -1864,14 +1843,12 @@ impl AscState { match std::fs::write(&path, &ppm) { Ok(()) => crate::log::daemon_info(&format!( "{}", - gndrm_obf::obf!( - "dump {n}: {width}x{height} stride={stride} wrote {}", - path.display() - ) + format_args!("dump {n}: {width}x{height} stride={stride} wrote {}", + path.display()) )), Err(e) => crate::log::daemon_info(&format!( "{}", - gndrm_obf::obf!("dump {n}: write failed: {e}") + format_args!("dump {n}: write failed: {e}") )), } } @@ -1917,15 +1894,13 @@ impl AscState { // cycle), never per frame. asc_log!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc re-published retained ino {} onto a mode {}x{} in a {}x{} window (frames={})", + format_args!("gndrm-daemon: asc re-published retained ino {} onto a mode {}x{} in a {}x{} window (frames={})", lp.ino, self.mode_w, self.mode_h, self.win_w, self.win_h, - self.frames - ) + self.frames) ); } @@ -1954,10 +1929,7 @@ impl AscState { let new_sc = unsafe { (api.sc_create_from_window)(window, SC_DEBUG_NAME.as_ptr()) }; if new_sc.is_null() { log_warn!( - "{}", - gndrm_obf::obf!( "asc: retarget: ASurfaceControl_createFromWindow failed; keeping the current layer" - ) ); return false; } @@ -1987,7 +1959,7 @@ impl AscState { } log_info!( "{}", - gndrm_obf::obf!("asc: retargeted to the new window ({win_w}x{win_h})") + format_args!("asc: retargeted to the new window ({win_w}x{win_h})") ); // A layer with no buffer set composites nothing (the app's background // shows through as a blank panel), so the retained frame goes straight @@ -2061,12 +2033,10 @@ impl AscState { self.cursor.logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc cursor image fb={} ino={ino} {} -> cursor layer (images={})", + format_args!("gndrm-daemon: asc cursor image fb={} ino={ino} {} -> cursor layer (images={})", fb.id, layout, - self.cursor.images - ) + self.cursor.images) ); } } @@ -2160,16 +2130,14 @@ impl AscState { self.cursor.stage_logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc cursor {} rot={rot} ({}) transform={transform} src=({},{})-({},{}) dst=({},{})-({},{}) plane_src={}x{} plane_dst={}x{} window={}x{} natural={}", + format_args!("gndrm-daemon: asc cursor {} rot={rot} ({}) transform={transform} src=({},{})-({},{}) dst=({},{})-({},{}) plane_src={}x{} plane_dst={}x{} window={}x{} natural={}", if shown_as.is_some() { "staged" } else { "padded" }, if rot_override.is_some() { "override" } else { "derived" }, src.left, src.top, src.right, src.bottom, dst.left, dst.top, dst.right, dst.bottom, plane.0, plane.1, plane.2, plane.3, self.win_w, self.win_h, - if natural_landscape() { "landscape" } else { "portrait" } - ) + if natural_landscape() { "landscape" } else { "portrait" }) ); } // SAFETY: one transaction, applied and deleted below; `sc` and `ahb` @@ -2202,8 +2170,7 @@ impl AscState { self.cursor.logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc cursor layer shown dst=({},{})-({},{}) mode={}x{} window={}x{}", + format_args!("gndrm-daemon: asc cursor layer shown dst=({},{})-({},{}) mode={}x{} window={}x{}", dst.left, dst.top, dst.right, @@ -2211,8 +2178,7 @@ impl AscState { self.mode_w, self.mode_h, self.win_w, - self.win_h - ) + self.win_h) ); } } else { @@ -2282,9 +2248,7 @@ impl AscState { self.cursor.stage_logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc cursor stage FAILED ({reason}); showing the padded buffer" - ) + format_args!("gndrm-daemon: asc cursor stage FAILED ({reason}); showing the padded buffer") ); } None @@ -2319,9 +2283,7 @@ impl AscState { self.cursor.logged += 1; log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc cursor image ino={ino} {layout} copy FAILED ({reason}); cursor hidden" - ) + format_args!("gndrm-daemon: asc cursor image ino={ino} {layout} copy FAILED ({reason}); cursor hidden") ); } } @@ -2344,7 +2306,7 @@ impl Drop for AscState { // and this is the last line the presenter can print. asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: asc teardown frames_published={} hidden={} last_publish_ino={} last_dst=({},{})-({},{}) mode={}x{} window={}x{}",self.frames, + format_args!("gndrm-daemon: asc teardown frames_published={} hidden={} last_publish_ino={} last_dst=({},{})-({},{}) mode={}x{} window={}x{}",self.frames, self.hidden, self.last_publish.map_or(0, |lp| lp.ino), self.last_publish.map_or(0, |lp| lp.dst.left), @@ -2365,24 +2327,20 @@ impl Drop for AscState { if self.foreign_buffers > 0 || self.foreign_failures > 0 { log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: foreign dma-buf summary: copied_frames={} buffers={} failures={}", + format_args!("gndrm-daemon: foreign dma-buf summary: copied_frames={} buffers={} failures={}", self.foreign_frames, self.foreign_buffers, - self.foreign_failures - ) + self.foreign_failures) ); } if self.cursor.images > 0 || self.cursor.failures > 0 { log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc cursor summary images={} moves={} hides={} failures={}", + format_args!("gndrm-daemon: asc cursor summary images={} moves={} hides={} failures={}", self.cursor.images, self.cursor.moves, self.cursor.hides, - self.cursor.failures - ) + self.cursor.failures) ); } self.cursor.slot = None; @@ -2488,7 +2446,7 @@ fn log_first_non_request_frame(frame: &[u8]) { .map_or(0, |m| u32::from_le_bytes([m[0], m[1], m[2], m[3]])); asc_log!( "{}", - gndrm_obf::obf!("gndrm-daemon: scan-out channel non-request frame magic={magic:#010x}") + format_args!("gndrm-daemon: scan-out channel non-request frame magic={magic:#010x}") ); } @@ -2590,7 +2548,7 @@ pub fn serve_scanout( if e.raw_os_error() == Some(libc::EINTR) { continue; } - log_info!("{}", gndrm_obf::obf!("asc: scan-out channel poll: {e}")); + log_info!("{}", format_args!("asc: scan-out channel poll: {e}")); return ScanoutChannel::Closed; } if pfds[2].revents != 0 { @@ -2644,9 +2602,7 @@ pub fn serve_scanout( // and must be closed before the acceptor serves the newest one. log_info!( "{}", - gndrm_obf::obf!( - "asc: scan-out channel superseded (fd={fd}); adopting the newest connection" - ) + format_args!("asc: scan-out channel superseded (fd={fd}); adopting the newest connection") ); return ScanoutChannel::Superseded; } @@ -2659,11 +2615,9 @@ pub fn serve_scanout( Err(e) => { log_info!( "{}", - gndrm_obf::obf!( - "asc: scan-out channel recv: {e} (requests={} replies={})", + format_args!("asc: scan-out channel recv: {e} (requests={} replies={})", d.requests_seen(), - d.replies_sent() - ) + d.replies_sent()) ); return ScanoutChannel::Closed; } @@ -2676,11 +2630,9 @@ pub fn serve_scanout( if n == 0 { log_info!( "{}", - gndrm_obf::obf!( - "asc: scan-out channel closed by peer (requests={} replies={})", + format_args!("asc: scan-out channel closed by peer (requests={} replies={})", d.requests_seen(), - d.replies_sent() - ) + d.replies_sent()) ); return ScanoutChannel::Closed; } @@ -2738,10 +2690,8 @@ pub fn serve_scanout( } log_info!( "{}", - gndrm_obf::obf!( - "asc: scan-out channel frame-cap subscribe (caps={:#x})", - sub.caps - ) + format_args!("asc: scan-out channel frame-cap subscribe (caps={:#x})", + sub.caps) ); continue; } @@ -2766,7 +2716,7 @@ pub fn serve_scanout( log_first_non_request_frame(&buf[..n]); log_warn!( "{}", - gndrm_obf::obf!("asc: unrecognised scan-out channel frame ({n} bytes); ignored") + format_args!("asc: unrecognised scan-out channel frame ({n} bytes); ignored") ); continue; }; @@ -2790,14 +2740,12 @@ pub fn serve_scanout( if d.receipt_allowed() { log_info!( "{}", - gndrm_obf::obf!( - "asc: scan-out request {}x{} len={} fmt={:#x} received (seq={})", + format_args!("asc: scan-out request {}x{} len={} fmt={:#x} received (seq={})", req.width, req.height, req.len, req.format, - d.requests_seen() - ) + d.requests_seen()) ); } d.note_stage(Stage::Read, read_started.elapsed().as_millis() as u64); @@ -2887,9 +2835,7 @@ pub fn serve_scanout( // identity actually handed out so the next commit for // this buffer still resolves. if ino != cached_ino { - log_warn!("{}", gndrm_obf::obf!( - "asc: scan-out reuse ino moved ({cached_ino} -> {ino}); the free-list identity is stale, re-registering" - )); + log_warn!("{}", format_args!("asc: scan-out reuse ino moved ({cached_ino} -> {ino}); the free-list identity is stale, re-registering")); } let buffer = ScanoutBuffer { fd, @@ -2903,7 +2849,7 @@ pub fn serve_scanout( &buffer, payload.ahb, false, - &gndrm_obf::obf!("reused"), + &"reused", ); if let Some(old) = replaced { release_retired(core::slice::from_ref(&retire_buf(old))); @@ -2951,7 +2897,7 @@ pub fn serve_scanout( &warm.buffer, warm.ahb, false, - &gndrm_obf::obf!("from spare"), + &"from spare", ); if let Some(old) = replaced { release_retired(core::slice::from_ref(&retire_buf(old))); @@ -3010,7 +2956,7 @@ pub fn serve_scanout( &buffer, ahb, true, - &gndrm_obf::obf!("allocated"), + &"allocated", ); if let Some(old) = replaced { release_retired(core::slice::from_ref(&retire_buf(old))); @@ -3056,9 +3002,9 @@ pub fn serve_scanout( let elapsed_ms = d.request_elapsed_ms(); let send_failed = sent.is_err(); let diag_line = if send_failed { - Some(d.snapshot(&gndrm_obf::obf!("reply-write-failed"))) + Some(d.snapshot(&"reply-write-failed")) } else if elapsed_ms >= diag::STALL_WARN_MS && d.slow_report_allowed() { - Some(d.snapshot(&gndrm_obf::obf!("slow-reply"))) + Some(d.snapshot(&"slow-reply")) } else { None }; @@ -3070,7 +3016,7 @@ pub fn serve_scanout( if let Some(line) = diag_line { log_warn!( "{}", - gndrm_obf::obf!("asc: scan-out request {total_ms} ms: {line}") + format_args!("asc: scan-out request {total_ms} ms: {line}") ); } // The daemon's copy of the descriptor is closed on both paths. @@ -3095,7 +3041,7 @@ pub fn serve_scanout( discard_returned(removed); } } - log_warn!("{}", gndrm_obf::obf!("asc: scan-out channel send: {e}")); + log_warn!("{}", format_args!("asc: scan-out channel send: {e}")); return ScanoutChannel::Closed; } // The handle follows its reply directly: this thread is the channel's @@ -3107,7 +3053,7 @@ pub fn serve_scanout( if r != 0 { log_warn!( "{}", - gndrm_obf::obf!("asc: scan-out AHardwareBuffer handle send failed ({r})") + format_args!("asc: scan-out AHardwareBuffer handle send failed ({r})") ); return ScanoutChannel::Closed; } @@ -3160,14 +3106,12 @@ fn serve_lookup(fd: RawFd, req: ScanoutAllocReq, pool: &Arc]) -> Vec { Removed::Kept { ino, geom, payload } => { log_info!( "{}", - gndrm_obf::obf!( - "asc: dma-buf ino {ino} retired; retained for reuse ({}x{})", + format_args!("asc: dma-buf ino {ino} retired; retained for reuse ({}x{})", geom.width, - geom.height - ) + geom.height) ); let fd = ctx_release_fd(payload); if fd >= 0 { @@ -3232,9 +3174,7 @@ fn retire_to_release(removed: &[Removed]) -> Vec { Removed::Released { ino, payload } => { log_info!( "{}", - gndrm_obf::obf!( - "asc: dma-buf ino {ino} retired; releasing its AHardwareBuffer" - ) + format_args!("asc: dma-buf ino {ino} retired; releasing its AHardwareBuffer") ); out.push(retire_buf(*payload)); } @@ -3250,7 +3190,7 @@ fn discard_returned(removed: Removed) { Removed::Kept { ino, payload, .. } => { log_info!( "{}", - gndrm_obf::obf!("asc: dma-buf ino {ino} returned; retained for reuse") + format_args!("asc: dma-buf ino {ino} returned; retained for reuse") ); let fd = ctx_release_fd(&payload); if fd >= 0 { @@ -3261,7 +3201,7 @@ fn discard_returned(removed: Removed) { Removed::Released { ino, payload } => { log_info!( "{}", - gndrm_obf::obf!("asc: dma-buf ino {ino} returned; releasing its AHardwareBuffer") + format_args!("asc: dma-buf ino {ino} returned; releasing its AHardwareBuffer") ); release_retired(core::slice::from_ref(&retire_buf(payload))); } @@ -3289,15 +3229,13 @@ fn refuse_scanout( // A length-only request has no geometry to name (it failed to resolve, or // resolved and then failed); report the length it carried instead. let what = if req.is_length_only() { - format!("{}", gndrm_obf::obf!("len={} (unresolved)", req.len)) + format!("{}", format_args!("len={} (unresolved)", req.len)) } else { - format!("{}", gndrm_obf::obf!("{}x{}", req.width, req.height)) + format!("{}", format_args!("{}x{}", req.width, req.height)) }; - log_warn!("{}", gndrm_obf::obf!( - "asc: scan-out alloc {what} refused: {} (errno {errno}, waited {waited_ms} ms for the pool lock, pool={owned}/{MAX_SCANOUT_POOL} live={live} free={free}) {}", + log_warn!("{}", format_args!("asc: scan-out alloc {what} refused: {} (errno {errno}, waited {waited_ms} ms for the pool lock, pool={owned}/{MAX_SCANOUT_POOL} live={live} free={free}) {}", refusal_reason(errno), - d.snapshot(&gndrm_obf::obf!("refused")) - )); + d.snapshot("refused"))); ( ScanoutAllocResp { ret: -errno, @@ -3424,10 +3362,8 @@ fn check_request_format(format: u32) -> io::Result<()> { if FORMAT_MISMATCH_LOGGED.fetch_add(1, Ordering::Relaxed) < FORMAT_MISMATCH_LOG_BUDGET { log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: scan-out request format {format} refused, session layout is {want} ({})", - gndrm_daemon::scanout_layout().as_env_value() - ) + format_args!("gndrm-daemon: scan-out request format {format} refused, session layout is {want} ({})", + gndrm_daemon::scanout_layout().as_env_value()) ); } Err(io::Error::from_raw_os_error(libc::EINVAL)) @@ -3480,7 +3416,7 @@ fn allocate_buffer( // shim's side ("daemon allocated no buffer"). log_warn!( "{}", - gndrm_obf::obf!("asc: AHardwareBuffer_allocate {width}x{height} failed (rc={rc})") + format_args!("asc: AHardwareBuffer_allocate {width}x{height} failed (rc={rc})") ); return Err(if rc != 0 { -rc } else { libc::ENOMEM }); } @@ -3531,14 +3467,14 @@ fn release_warm(warm: Warm) { } /// Human label for a refusal, so the shim's bare "daemon allocated no buffer" -/// can be traced back to the actual fault in the daemon log. The literals are -/// obfuscated, so this returns an owned label (cold path: only on a refusal). +/// can be traced back to the actual fault in the daemon log. Owned, because it +/// is composed into the caller's line (cold path: only on a refusal). fn refusal_reason(errno: i32) -> String { match errno { - libc::ENOSPC => gndrm_obf::obf!("pool exhausted").to_string(), - libc::ENOSYS => gndrm_obf::obf!("presenter disabled (no publish API)").to_string(), - libc::EINVAL => gndrm_obf::obf!("unsupported geometry or format").to_string(), - _ => gndrm_obf::obf!("AHardwareBuffer allocation failed").to_string(), + libc::ENOSPC => "pool exhausted".to_string(), + libc::ENOSYS => "presenter disabled (no publish API)".to_string(), + libc::EINVAL => "unsupported geometry or format".to_string(), + _ => "AHardwareBuffer allocation failed".to_string(), } } @@ -3624,12 +3560,10 @@ fn build_show( if !ONCE.swap(true, core::sync::atomic::Ordering::Relaxed) { asc_log!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: asc hdr metadata cta861_3={} smpte2086={} cap={}", + format_args!("gndrm-daemon: asc hdr metadata cta861_3={} smpte2086={} cap={}", api.st_set_hdr_metadata_cta861_3.is_some(), api.st_set_hdr_metadata_smpte2086.is_some(), - gndrm_daemon::hdr_output_capability().is_some() - ) + gndrm_daemon::hdr_output_capability().is_some()) ); } if let Some(cap) = gndrm_daemon::hdr_output_capability() { @@ -3810,10 +3744,8 @@ unsafe fn scanout_dmabuf_fd(nh: *const ffi::NativeHandle) -> Option { .join(" "); log_always!( "{}", - gndrm_obf::obf!( - "asc: scan-out handle descriptors [{table}]; handing out fd {}", - pick.0 - ) + format_args!("asc: scan-out handle descriptors [{table}]; handing out fd {}", + pick.0) ); } Some(pick.1) @@ -3964,7 +3896,7 @@ pub(crate) fn note_produced(acq: FrameAcquired) { if previous == 0 && acq.count != 0 { log_info!( "{}", - gndrm_obf::obf!("asc: acquire counter connected (count={})", acq.count) + format_args!("asc: acquire counter connected (count={})", acq.count) ); // The frames behind this first total were already counted by the // publish path while no reports flowed; counting them again here would @@ -3986,7 +3918,7 @@ pub(crate) fn note_produced(acq: FrameAcquired) { if produced > ones { log_warn!( "{}", - gndrm_obf::obf!("asc: produced delta {produced} clamped to {ones} for the frame ring") + format_args!("asc: produced delta {produced} clamped to {ones} for the frame ring") ); } } diff --git a/modules/gndrm-android/src/choreographer.rs b/modules/gndrm-android/src/choreographer.rs index d8abb32..7912d9c 100644 --- a/modules/gndrm-android/src/choreographer.rs +++ b/modules/gndrm-android/src/choreographer.rs @@ -172,10 +172,7 @@ pub(crate) fn stop() { fn run() { let Some(api) = Api::load() else { crate::log_always!( - "{}", - gndrm_obf::obf!( - "vsync: no Choreographer vsync callback here; flip events follow the latch grid" - ) + "vsync: no Choreographer vsync callback here; flip events follow the latch grid" ); return; }; @@ -186,8 +183,7 @@ fn run() { let ch = unsafe { (api.get_instance)() }; if looper.is_null() || ch.is_null() { crate::log_always!( - "{}", - gndrm_obf::obf!("vsync: Choreographer unavailable; flip events follow the latch grid") + "vsync: Choreographer unavailable; flip events follow the latch grid" ); return; } @@ -240,10 +236,7 @@ fn run() { if !logged_lost { logged_lost = true; crate::log_always!( - "{}", - gndrm_obf::obf!( - "vsync: no Choreographer callback for 1 s; posting again, flip events follow the latch grid meanwhile" - ) + "vsync: no Choreographer callback for 1 s; posting again, flip events follow the latch grid meanwhile" ); } OUTSTANDING.store(false, Ordering::Relaxed); @@ -291,13 +284,11 @@ fn feed(vsync_ns: u64, deadline_ns: Option) { if let Some((fit, mode)) = vblank::take_rejected_fit() { crate::log_always!( "{}", - gndrm_obf::obf!( - "vsync: measured period {}.{:03}us is more than 2% from the mode's {}.{:03}us; kept the previous period", + format_args!("vsync: measured period {}.{:03}us is more than 2% from the mode's {}.{:03}us; kept the previous period", fit / 1000, fit % 1000, mode / 1000, - mode % 1000 - ) + mode % 1000) ); } } @@ -310,13 +301,12 @@ fn log_lock(lock: &VsyncLock) { let mode_mhz = crate::panel_refresh_mhz(); let rate_mhz = 1_000_000_000_000 / p.max(1); let offset = match lock.latch_offset_ns { - Some(o) => gndrm_obf::obf!("{:+}us", o / 1000).to_string(), - None => gndrm_obf::obf!("none yet").to_string(), + Some(o) => format_args!("{:+}us", o / 1000).to_string(), + None => "none yet".to_string(), }; crate::log_always!( "{}", - gndrm_obf::obf!( - "vsync: flip events on the display's vsync: source={} period={}.{:03}us ({}.{:03} Hz, mode {}.{:03} Hz) latch-vs-grid={}", + format_args!("vsync: flip events on the display's vsync: source={} period={}.{:03}us ({}.{:03} Hz, mode {}.{:03} Hz) latch-vs-grid={}", lock.grid.source.name(), p / 1000, p % 1000, @@ -324,8 +314,7 @@ fn log_lock(lock: &VsyncLock) { rate_mhz % 1000, mode_mhz / 1000, mode_mhz % 1000, - offset - ) + offset) ); } @@ -333,7 +322,7 @@ fn log_lock(lock: &VsyncLock) { fn ms(ns: i64) -> String { let sign = if ns < 0 { '-' } else { '+' }; let a = ns.unsigned_abs(); - gndrm_obf::obf!("{sign}{}.{:03}ms", a / 1_000_000, (a / 1000) % 1000).to_string() + format_args!("{sign}{}.{:03}ms", a / 1_000_000, (a / 1000) % 1000).to_string() } /// The cross-check, once per 10 s while publishes complete (see @@ -344,12 +333,11 @@ pub(crate) fn log_report(r: &VsyncReport) { let rate_mhz = 1_000_000_000_000 / p.max(1); let lad = match r.latch_after_deadline_ns { Some(d) => ms(d), - None => gndrm_obf::obf!("n/a").to_string(), + None => "n/a".to_string(), }; crate::log_always!( "{}", - gndrm_obf::obf!( - "vsync: check source={} period={}.{:03}us ({}.{:03} Hz) publishes={} vsyncs={} late={} pushed={} margin p10/p50/p90={}/{}/{} lead={} latch-after-deadline={}", + format_args!("vsync: check source={} period={}.{:03}us ({}.{:03} Hz) publishes={} vsyncs={} late={} pushed={} margin p10/p50/p90={}/{}/{} lead={} latch-after-deadline={}", r.source.map_or("none", |s| s.name()), p / 1000, p % 1000, @@ -363,7 +351,6 @@ pub(crate) fn log_report(r: &VsyncReport) { ms(r.margin_ns[1]), ms(r.margin_ns[2]), ms(r.lead_ns as i64), - lad - ) + lad) ); } diff --git a/modules/gndrm-android/src/dump.rs b/modules/gndrm-android/src/dump.rs index 33461e1..c22d368 100644 --- a/modules/gndrm-android/src/dump.rs +++ b/modules/gndrm-android/src/dump.rs @@ -29,7 +29,7 @@ pub(crate) fn ppm( ScanoutLayout::Bgra8888 => (2, 0), }; let mut out = Vec::with_capacity(width * height * 3 + 16); - out.extend_from_slice(format!("{}", gndrm_obf::obf!("P6\n{width} {height}\n255\n")).as_bytes()); + out.extend_from_slice(format!("{}", format_args!("P6\n{width} {height}\n255\n")).as_bytes()); for row in src.chunks(stride).take(height) { for x in 0..width { let px = &row[x * BPP..]; diff --git a/modules/gndrm-android/src/foreign.rs b/modules/gndrm-android/src/foreign.rs index 213ba4f..d8e7bbf 100644 --- a/modules/gndrm-android/src/foreign.rs +++ b/modules/gndrm-android/src/foreign.rs @@ -86,14 +86,14 @@ impl ForeignCopy { pub(crate) fn new(fb: &Framebuffer, src_fd: RawFd) -> Result { let len = source_len(src_fd); if len == 0 { - return Err(gndrm_obf::obf!("dma-buf length unknown").to_string()); + return Err("dma-buf length unknown".to_string()); } let layout = gndrm_daemon::scanout_layout(); let plan = plan_copy(fb, len, layout).map_err(|r| r.to_string())?; // SAFETY: fcntl on a descriptor the caller keeps open for this call. let fd = unsafe { libc::fcntl(src_fd, libc::F_DUPFD_CLOEXEC, 0) }; if fd < 0 { - return Err(gndrm_obf::obf!("dup failed (errno {})", errno()).to_string()); + return Err(format_args!("dup failed (errno {})", errno()).to_string()); } // SAFETY: a fresh shared read-only mapping of the whole dma-buf. let map = unsafe { @@ -110,7 +110,7 @@ impl ForeignCopy { let e = errno(); // SAFETY: `fd` is owned here. unsafe { libc::close(fd) }; - return Err(gndrm_obf::obf!("mmap of {len} bytes failed (errno {e})").to_string()); + return Err(format_args!("mmap of {len} bytes failed (errno {e})").to_string()); } let format = if plan.ten_bit { ffi::AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM @@ -134,7 +134,7 @@ impl ForeignCopy { libc::munmap(map, len as usize); libc::close(fd); } - return Err(gndrm_obf::obf!("AHardwareBuffer_allocate failed (rc={rc})").to_string()); + return Err(format_args!("AHardwareBuffer_allocate failed (rc={rc})").to_string()); } let mut real = ffi::AHardwareBufferDesc::default(); // SAFETY: `ahb` is a live buffer owned here. @@ -161,7 +161,7 @@ impl ForeignCopy { let dst_pitch = self.stride as usize; if dst_pitch < self.plan.row_bytes { return Err( - gndrm_obf::obf!("target stride {dst_pitch} shorter than a row").to_string(), + format_args!("target stride {dst_pitch} shorter than a row").to_string(), ); } let mut addr: *mut c_void = ptr::null_mut(); @@ -176,7 +176,7 @@ impl ForeignCopy { ) }; if rc != 0 || addr.is_null() { - return Err(gndrm_obf::obf!("AHardwareBuffer_lock failed (rc={rc})").to_string()); + return Err(format_args!("AHardwareBuffer_lock failed (rc={rc})").to_string()); } sync(self.src_fd, DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ); // SAFETY: the mapping covers `map_len` bytes for the life of `self`; @@ -247,7 +247,7 @@ impl CursorStage { // SAFETY: `desc` is a live stack value; `ahb` receives one reference. let rc = unsafe { ffi::AHardwareBuffer_allocate(&desc, &mut ahb) }; if rc != 0 || ahb.is_null() { - return Err(gndrm_obf::obf!("AHardwareBuffer_allocate failed (rc={rc})").to_string()); + return Err(format_args!("AHardwareBuffer_allocate failed (rc={rc})").to_string()); } let stage = Self { ahb, width, height }; let mut real = ffi::AHardwareBufferDesc::default(); @@ -267,7 +267,7 @@ impl CursorStage { ) }; if rc != 0 || addr.is_null() { - return Err(gndrm_obf::obf!("AHardwareBuffer_lock failed (rc={rc})").to_string()); + return Err(format_args!("AHardwareBuffer_lock failed (rc={rc})").to_string()); } // SAFETY: the locked buffer covers `dst_pitch * height` bytes. unsafe { diff --git a/modules/gndrm-android/src/injector.rs b/modules/gndrm-android/src/injector.rs index a3d6077..f4f3cfc 100644 --- a/modules/gndrm-android/src/injector.rs +++ b/modules/gndrm-android/src/injector.rs @@ -196,11 +196,11 @@ pub fn start(runtime_dir: String, display: String) -> i32 { stop, thread: Some(t), }); - log_info!("{}", gndrm_obf::obf!("injector started (target {path})")); + log_info!("{}", format_args!("injector started (target {path})")); 0 } Err(e) => { - log_error!("{}", gndrm_obf::obf!("injector spawn: {e}")); + log_error!("{}", format_args!("injector spawn: {e}")); -5 } } @@ -244,11 +244,11 @@ pub fn stop() { } else { log_warn!( "{}", - gndrm_obf::obf!("injector thread parked past {JOIN_TIMEOUT:?}; detached") + format_args!("injector thread parked past {JOIN_TIMEOUT:?}; detached") ); } } - log_info!("{}", gndrm_obf::obf!("injector stopped")); + log_info!("{}", "injector stopped"); } fn post(ev: InputEvent) { @@ -418,11 +418,9 @@ pub fn display_and_features() -> String { .join(","); format!( "{}", - gndrm_obf::obf!( - "features=0x{features:X};connector={};display_flags=0x{:X};rates={rates}", + format_args!("features=0x{features:X};connector={};display_flags=0x{:X};rates={rates}", info.connector, - info.flags - ) + info.flags) ) } @@ -524,7 +522,7 @@ impl Dispatch for State { ) { // The protocol has one event today, so the match is exhaustive. let GsReshadeEvent::EffectReady { effect_path } = event; - log_info!("{}", gndrm_obf::obf!("reshade effect ready: {effect_path}")); + log_info!("{}", format_args!("reshade effect ready: {effect_path}")); } } @@ -597,10 +595,10 @@ fn run(path: &str, rx: &mpsc::Receiver, stop: &AtomicBool) { Ok(()) => return, // stop requested Err(e) => { if !logged_wait { - log_info!("{}", gndrm_obf::obf!("injector waiting for {path}: {e}")); + log_info!("{}", format_args!("injector waiting for {path}: {e}")); logged_wait = true; } else { - log_warn!("{}", gndrm_obf::obf!("injector reconnecting: {e}")); + log_warn!("{}", format_args!("injector reconnecting: {e}")); } // Drain stale input while disconnected, then wait. while rx.try_recv().is_ok() {} @@ -618,7 +616,7 @@ fn connect_and_run( ) -> Result<(), String> { let stream = UnixStream::connect(path).map_err(|e| e.to_string())?; let conn = Connection::from_socket(stream) - .map_err(|e| format!("{}", gndrm_obf::obf!("from_socket: {e}")))?; + .map_err(|e| format!("{}", format_args!("from_socket: {e}")))?; let mut event_queue = conn.new_event_queue::(); let qh = event_queue.handle(); @@ -636,18 +634,16 @@ fn connect_and_run( }; event_queue .roundtrip(&mut state) - .map_err(|e| format!("{}", gndrm_obf::obf!("registry roundtrip: {e}")))?; + .map_err(|e| format!("{}", format_args!("registry roundtrip: {e}")))?; let (Some(seat), Some(ptr_mgr), Some(kbd_mgr)) = (&state.seat, &state.ptr_mgr, &state.kbd_mgr) else { return Err(format!( "{}", - gndrm_obf::obf!( - "missing globals (seat={} ptr={} kbd={})", + format_args!("missing globals (seat={} ptr={} kbd={})", state.seat.is_some(), state.ptr_mgr.is_some(), - state.kbd_mgr.is_some() - ) + state.kbd_mgr.is_some()) )); }; @@ -656,19 +652,17 @@ fn connect_and_run( let keyboard = state .keyboard .as_ref() - .expect(&gndrm_obf::obf!("keyboard just created")); + .expect(&"keyboard just created"); upload_keymap(keyboard); if state.gs_control.is_none() { log_warn!( - "{}", - gndrm_obf::obf!("gamescope_control not offered; fps cap unavailable") + "gamescope_control not offered; fps cap unavailable" ); } conn.flush() - .map_err(|e| format!("{}", gndrm_obf::obf!("flush: {e}")))?; + .map_err(|e| format!("{}", format_args!("flush: {e}")))?; log_info!( - "{}", - gndrm_obf::obf!("injector connected: virtual pointer + keyboard created") + "injector connected: virtual pointer + keyboard created" ); // Main loop: apply queued input, apply a pending fps cap, flush, drain @@ -728,12 +722,12 @@ fn connect_and_run( } } conn.flush() - .map_err(|e| format!("{}", gndrm_obf::obf!("flush: {e}")))?; + .map_err(|e| format!("{}", format_args!("flush: {e}")))?; // Keep the read side drained and detect server death promptly. if last_roundtrip.elapsed() >= Duration::from_millis(500) { event_queue .roundtrip(&mut state) - .map_err(|e| format!("{}", gndrm_obf::obf!("roundtrip: {e}")))?; + .map_err(|e| format!("{}", format_args!("roundtrip: {e}")))?; last_roundtrip = std::time::Instant::now(); } } @@ -818,17 +812,15 @@ fn upload_keymap(keyboard: &ZwpVirtualKeyboardV1) { if fd < 0 { log_error!( "{}", - gndrm_obf::obf!( - "keymap memfd_create failed: {}", - std::io::Error::last_os_error() - ) + format_args!("keymap memfd_create failed: {}", + std::io::Error::last_os_error()) ); return; } // SAFETY: fd is valid; bytes outlive the call. let written = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) }; if written != bytes.len() as isize { - log_error!("{}", gndrm_obf::obf!("keymap write short: {written}")); + log_error!("{}", format_args!("keymap write short: {written}")); // SAFETY: owned fd. unsafe { libc::close(fd) }; return; diff --git a/modules/gndrm-android/src/layout.rs b/modules/gndrm-android/src/layout.rs index 3bacbff..c9e01d4 100644 --- a/modules/gndrm-android/src/layout.rs +++ b/modules/gndrm-android/src/layout.rs @@ -76,11 +76,11 @@ impl core::fmt::Display for Decision { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let layout = self.layout.as_env_value(); match self.source { - Source::Env => write!(f, "{}", gndrm_obf::obf!("{layout} (env)")), + Source::Env => write!(f, "{}", format_args!("{layout} (env)")), Source::Rule { sdk, re } => write!( f, "{}", - gndrm_obf::obf!("{layout} (rule: sdk={sdk} re={})", re.name()) + format_args!("{layout} (rule: sdk={sdk} re={})", re.name()) ), } } @@ -250,7 +250,7 @@ mod device { } let (sdk, re) = device_state(); let d = decide(gndrm_daemon::scanout_layout_from_env(), sdk, re); - crate::log_always!("{}", gndrm_obf::obf!("gndrm-daemon: scan-out layout {d}")); + crate::log_always!("{}", format_args!("gndrm-daemon: scan-out layout {d}")); *slot = Some(d); d.layout } diff --git a/modules/gndrm-android/src/lib.rs b/modules/gndrm-android/src/lib.rs index 46eb32a..ea98503 100644 --- a/modules/gndrm-android/src/lib.rs +++ b/modules/gndrm-android/src/lib.rs @@ -221,9 +221,7 @@ fn scanout_geometry(win_w: u16, win_h: u16) -> (u16, u16) { } else { log_info!( "{}", - gndrm_obf::obf!( - "scan-out geometry {want_w}x{want_h} does not fit the {win_w}x{win_h} window; the mode is the window" - ) + format_args!("scan-out geometry {want_w}x{want_h} does not fit the {win_w}x{win_h} window; the mode is the window") ); (win_w, win_h) } @@ -248,30 +246,29 @@ fn cache_java_vm(env: &mut JNIEnv) { match env.get_java_vm() { Ok(vm) => { if JAVA_VM.set(vm).is_ok() { - log_info!("{}", gndrm_obf::obf!("cached JavaVM for JNI callbacks")); + log_info!("{}", "cached JavaVM for JNI callbacks"); } } - Err(e) => log_warn!("{}", gndrm_obf::obf!("get_java_vm failed: {e}")), + Err(e) => log_warn!("{}", format_args!("get_java_vm failed: {e}")), } match env.find_class("app/gamenative/display/GameNativeDrm") { Ok(class) => match env.new_global_ref(class) { Ok(global) => { if CALLBACK_CLASS.set(global).is_ok() { log_info!( - "{}", - gndrm_obf::obf!("cached GameNativeDrm class for JNI callbacks") + "cached GameNativeDrm class for JNI callbacks" ); } } Err(e) => log_warn!( "{}", - gndrm_obf::obf!("new_global_ref(GameNativeDrm) failed: {e}") + format_args!("new_global_ref(GameNativeDrm) failed: {e}") ), }, Err(e) => { log_warn!( "{}", - gndrm_obf::obf!("find_class(GameNativeDrm) failed: {e}") + format_args!("find_class(GameNativeDrm) failed: {e}") ); let _ = env.exception_clear(); } @@ -293,10 +290,8 @@ pub(crate) fn clear_booting_splash() { if !LOGGED.swap(true, Ordering::Relaxed) && (failed || gndrm_daemon::verbose_logging()) { crate::log_always!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: splash-clear upcall clearBootingSplash outcome={}", - if failed { "failed" } else { "ok" } - ) + format_args!("gndrm-daemon: splash-clear upcall clearBootingSplash outcome={}", + if failed { "failed" } else { "ok" }) ); } } @@ -391,14 +386,14 @@ fn call_app_static(method: &str) -> AppCall { let Some(vm) = JAVA_VM.get() else { log_warn!( "{}", - gndrm_obf::obf!("{method}: no cached JavaVM; call skipped") + format_args!("{method}: no cached JavaVM; call skipped") ); return AppCall::Failed; }; let Some(class) = CALLBACK_CLASS.get() else { log_warn!( "{}", - gndrm_obf::obf!("{method}: GameNativeDrm class not cached; call skipped") + format_args!("{method}: GameNativeDrm class not cached; call skipped") ); return AppCall::Failed; }; @@ -407,13 +402,13 @@ fn call_app_static(method: &str) -> AppCall { Err(e) => { log_warn!( "{}", - gndrm_obf::obf!("{method}: attach_current_thread failed: {e}") + format_args!("{method}: attach_current_thread failed: {e}") ); return AppCall::Failed; } }; let Some(method_id) = static_method_id(&mut env, class, method) else { - log_warn!("{}", gndrm_obf::obf!("{method}: no static id for ()V")); + log_warn!("{}", format_args!("{method}: no static id for ()V")); return AppCall::Failed; }; // SAFETY: `method_id` was resolved from this same cached class and ids stay @@ -436,14 +431,14 @@ fn call_app_static(method: &str) -> AppCall { if let Ok(true) = env.exception_check() { let _ = env.exception_describe(); let _ = env.exception_clear(); - log_warn!("{}", gndrm_obf::obf!("{method}: threw; exception cleared")); + log_warn!("{}", format_args!("{method}: threw; exception cleared")); return AppCall::Failed; } - log_info!("{}", gndrm_obf::obf!("{method}: called")); + log_info!("{}", format_args!("{method}: called")); AppCall::Ok } Err(e) => { - log_warn!("{}", gndrm_obf::obf!("{method}: call failed: {e}")); + log_warn!("{}", format_args!("{method}: call failed: {e}")); // Never leave a pending exception on this thread. let _ = env.exception_clear(); AppCall::Failed @@ -507,7 +502,7 @@ fn report_panic(subsystem: &str, payload: &(dyn std::any::Any + Send)) { .unwrap_or(""); log_error!( "{}", - gndrm_obf::obf!("{subsystem}: PANICKED: {msg}; subsystem stopped, app continues") + format_args!("{subsystem}: PANICKED: {msg}; subsystem stopped, app continues") ); } @@ -563,25 +558,25 @@ fn server_thread_inner( Err(e) => { log_warn!( "{}", - gndrm_obf::obf!("accept(rpc): {e} (stopped before client?)") + format_args!("accept(rpc): {e} (stopped before client?)") ); return; } }; - fds.lock().expect(&gndrm_obf::obf!("fds poisoned")).rpc = rpc; + fds.lock().expect(&"fds poisoned").rpc = rpc; let event = match server::accept(listener) { Ok(fd) => fd, Err(e) => { - log_warn!("{}", gndrm_obf::obf!("accept(event): {e}")); + log_warn!("{}", format_args!("accept(event): {e}")); // SAFETY: rpc is owned by this thread. unsafe { libc::close(rpc) }; return; } }; - fds.lock().expect(&gndrm_obf::obf!("fds poisoned")).event = event; + fds.lock().expect(&"fds poisoned").event = event; log_info!( "{}", - gndrm_obf::obf!("client connected (rpc={rpc} event={event})") + format_args!("client connected (rpc={rpc} event={event})") ); // 3. Third and later connections: the scan-out allocator channel (see @@ -600,8 +595,7 @@ fn server_thread_inner( fd if fd >= 0 => Some(fd), _ => { log_warn!( - "{}", - gndrm_obf::obf!("eventfd for the scan-out acceptor failed; no client allocator") + "eventfd for the scan-out acceptor failed; no client allocator" ); None } @@ -618,10 +612,7 @@ fn server_thread_inner( } _ => { log_warn!( - "{}", - gndrm_obf::obf!( - "eventfd for the frame-cap push failed; a target change reaches the shim only when it reconnects" - ) + "eventfd for the frame-cap push failed; a target change reaches the shim only when it reconnects" ); -1 } @@ -631,7 +622,7 @@ fn server_thread_inner( // holds across its blocking SurfaceFlinger round-trip. let pool = asc_state .lock() - .expect(&gndrm_obf::obf!("asc state poisoned")) + .expect(&"asc state poisoned") .pool(); // The scan-out thread takes the pool Arc below, so the ADDFB2 geometry // sink installed further down needs its own clone. @@ -713,11 +704,11 @@ fn server_thread_inner( if e.raw_os_error() == Some(libc::EINTR) { continue; } - log_info!("{}", gndrm_obf::obf!("scan-out acceptor poll: {e}")); + log_info!("{}", format_args!("scan-out acceptor poll: {e}")); return; } if pfds[1].revents != 0 { - log_info!("{}", gndrm_obf::obf!("scan-out acceptor stopping")); + log_info!("{}", "scan-out acceptor stopping"); return; } // A push owes nothing to the allocator: it goes out @@ -747,15 +738,15 @@ fn server_thread_inner( Err(e) => { log_info!( "{}", - gndrm_obf::obf!("accept(scanout): {e}; acceptor stopping") + format_args!("accept(scanout): {e}; acceptor stopping") ); return; } }; - fds.lock().expect(&gndrm_obf::obf!("fds poisoned")).scanout = fd; + fds.lock().expect(&"fds poisoned").scanout = fd; log_info!( "{}", - gndrm_obf::obf!("scan-out channel connected (fd={fd})") + format_args!("scan-out channel connected (fd={fd})") ); let outcome = asc::serve_scanout(fd, listener, signal, cap_fd, &pool, &doorbell); @@ -770,7 +761,7 @@ fn server_thread_inner( guard.scanout = -1; } } - log_info!("{}", gndrm_obf::obf!("scan-out channel closed (fd={fd})")); + log_info!("{}", format_args!("scan-out channel closed (fd={fd})")); // A connection that asked for pushes keeps its // registration when it only lost the allocator role: the // cap, the grid and the frame-generation settings are @@ -786,9 +777,7 @@ fn server_thread_inner( { log_info!( "{}", - gndrm_obf::obf!( - "scan-out channel {fd} keeps its push subscription" - ) + format_args!("scan-out channel {fd} keeps its push subscription") ); } else { let _ = gndrm_daemon::pushes::forget(fd); @@ -796,7 +785,7 @@ fn server_thread_inner( unsafe { libc::close(fd) }; } if matches!(outcome, asc::ScanoutChannel::Stop) { - log_info!("{}", gndrm_obf::obf!("scan-out acceptor stopping")); + log_info!("{}", "scan-out acceptor stopping"); return; } // Closed or Superseded: loop and adopt the newest connection @@ -827,7 +816,7 @@ fn server_thread_inner( break; } if let Some(line) = d.maybe_stall_dump(diag::STALL_WARN_MS) { - log_warn!("{}", gndrm_obf::obf!("asc: {line}")); + log_warn!("{}", format_args!("asc: {line}")); } } })) { @@ -863,14 +852,14 @@ fn server_thread_inner( if addfb_logged.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { log_info!( "{}", - gndrm_obf::obf!("asc: addfb geometry {width}x{height} alloc_len={alloc_len}") + format_args!("asc: addfb geometry {width}x{height} alloc_len={alloc_len}") ); } addfb_pool .lock(diag::Role::Commit) .note_framebuffer(width, height, alloc_len); })); - let log = |msg: &str| crate::log::daemon_info(&format!("{}", gndrm_obf::obf!("server: {msg}"))); + let log = |msg: &str| crate::log::daemon_info(&format!("{}", format_args!("server: {msg}"))); server::serve(&mut dev, rpc, event, &log); // 5. Teardown. Wake and join the scan-out acceptor first (it may be parked @@ -925,7 +914,7 @@ fn server_thread_inner( if let Ok(state) = asc_state.lock() { log_info!( "{}", - gndrm_obf::obf!("asc: {} frames published", state.frames_presented()) + format_args!("asc: {} frames published", state.frames_presented()) ); } // SAFETY: this thread owns both descriptors; nothing else uses them. @@ -933,7 +922,7 @@ fn server_thread_inner( libc::close(rpc); libc::close(event); } - log_info!("{}", gndrm_obf::obf!("server thread exit")); + log_info!("{}", "server thread exit"); } fn start( @@ -964,13 +953,13 @@ fn start( Err(_) => return E_INVAL, }; if width < 64 || height < 64 { - log_error!("{}", gndrm_obf::obf!("bad geometry {width}x{height}")); + log_error!("{}", format_args!("bad geometry {width}x{height}")); return E_INVAL; } - let mut slot = RUNTIME.lock().expect(&gndrm_obf::obf!("runtime poisoned")); + let mut slot = RUNTIME.lock().expect(&"runtime poisoned"); if slot.is_some() { - log_warn!("{}", gndrm_obf::obf!("nativeStart while running")); + log_warn!("{}", "nativeStart while running"); return E_BUSY; } @@ -980,8 +969,7 @@ fn start( unsafe { ffi::ANativeWindow_fromSurface(env.get_native_interface(), surface.as_raw()) }; if raw_window.is_null() { log_error!( - "{}", - gndrm_obf::obf!("ANativeWindow_fromSurface returned null") + "ANativeWindow_fromSurface returned null" ); return E_INVAL; } @@ -990,7 +978,7 @@ fn start( let listener = match server::listen_seqpacket(&name) { Ok(fd) => fd, Err(e) => { - log_error!("{}", gndrm_obf::obf!("listen({name}): {e}")); + log_error!("{}", format_args!("listen({name}): {e}")); // SAFETY: window was acquired above and nothing else holds it. unsafe { ffi::ANativeWindow_release(window.0) }; return E_IO; @@ -1006,7 +994,7 @@ fn start( let render_listener = match server::listen_seqpacket(&render_name) { Ok(fd) => fd, Err(e) => { - log_error!("{}", gndrm_obf::obf!("listen({render_name}): {e}")); + log_error!("{}", format_args!("listen({render_name}): {e}")); // SAFETY: listener/window acquired above; nothing else holds them. unsafe { libc::close(listener); @@ -1018,7 +1006,7 @@ fn start( let render_stop = match server::new_stop_eventfd() { Ok(fd) => fd, Err(e) => { - log_error!("{}", gndrm_obf::obf!("render stop eventfd: {e}")); + log_error!("{}", format_args!("render stop eventfd: {e}")); // SAFETY: listener/render_listener/window acquired above. unsafe { libc::close(listener); @@ -1081,7 +1069,7 @@ fn start( let render_handle = match render_handle { Ok(h) => h, Err(e) => { - log_error!("{}", gndrm_obf::obf!("render thread spawn: {e}")); + log_error!("{}", format_args!("render thread spawn: {e}")); // SAFETY: nothing else can own these now. unsafe { libc::close(listener); @@ -1101,7 +1089,7 @@ fn start( let handle = match handle { Ok(h) => h, Err(e) => { - log_error!("{}", gndrm_obf::obf!("spawn: {e}")); + log_error!("{}", format_args!("spawn: {e}")); // Stop the render thread already started above, then reclaim. server::signal_stop(render_stop); // SAFETY: nothing else can own these now. @@ -1125,7 +1113,7 @@ fn start( Ok(Ok(asc)) => asc, other => { if let Ok(Err(e)) = other { - log_error!("{}", gndrm_obf::obf!("server thread init: {e}")); + log_error!("{}", format_args!("server thread init: {e}")); } // Thread already exited (or is exiting); reclaim everything. let _ = handle.join(); @@ -1146,13 +1134,10 @@ fn start( log_info!( "{}", - gndrm_obf::obf!("started: socket={name} {panel_w}x{panel_h} into {win_w}x{win_h}") + format_args!("started: socket={name} {panel_w}x{panel_h} into {win_w}x{win_h}") ); log_info!( - "{}", - gndrm_obf::obf!( - "gndrm build 20260926-1: ADDFB2_MODIFIERS + IN_FORMATS (LINEAR) on both planes" - ) + "gndrm build 20260926-1: ADDFB2_MODIFIERS + IN_FORMATS (LINEAR) on both planes" ); let asc = Arc::downgrade(&asc); *slot = Some(Runtime { @@ -1175,10 +1160,10 @@ fn start( fn stop() { let rt = RUNTIME .lock() - .expect(&gndrm_obf::obf!("runtime poisoned")) + .expect(&"runtime poisoned") .take(); let Some(mut rt) = rt else { return }; - log_info!("{}", gndrm_obf::obf!("stopping ({})", rt.name)); + log_info!("{}", format_args!("stopping ({})", rt.name)); choreographer::stop(); // Unblock accept()/recvmsg() regardless of which phase the thread is in. // SAFETY: fds are valid or -1; shutdown only unblocks, the thread @@ -1198,7 +1183,7 @@ fn stop() { } if let Some(t) = rt.render_thread.take() { if t.join().is_err() { - log_error!("{}", gndrm_obf::obf!("render thread panicked")); + log_error!("{}", "render thread panicked"); } } // SAFETY: the render thread is joined; nothing else uses these now. @@ -1223,7 +1208,7 @@ fn stop() { } if let Some(t) = rt.thread.take() { if t.join().is_err() { - log_error!("{}", gndrm_obf::obf!("server thread panicked")); + log_error!("{}", "server thread panicked"); } } // The presenter is down (dropped on the joined thread); the window is ours @@ -1231,7 +1216,7 @@ fn stop() { // SAFETY: presenter no longer references the window. unsafe { ffi::ANativeWindow_release(rt.window.0) }; FIRST_FRAME_COMMITTED.store(false, Ordering::Relaxed); - log_info!("{}", gndrm_obf::obf!("stopped")); + log_info!("{}", "stopped"); } /// Adopt a new display window for a RUNNING session: rebuild the publish layer @@ -1248,21 +1233,20 @@ fn retarget(env: &mut JNIEnv, surface: &JObject, width: jint, height: jint) -> j if width < 64 || height < 64 { log_error!( "{}", - gndrm_obf::obf!("bad retarget geometry {width}x{height}") + format_args!("bad retarget geometry {width}x{height}") ); return E_INVAL; } - let mut slot = RUNTIME.lock().expect(&gndrm_obf::obf!("runtime poisoned")); + let mut slot = RUNTIME.lock().expect(&"runtime poisoned"); let Some(rt) = slot.as_mut() else { - log_info!("{}", gndrm_obf::obf!("retarget: no running session")); + log_info!("{}", "retarget: no running session"); return E_NOENT; }; // The presenter owns the session's strong reference to the shared state, so // a failed upgrade means the session is already shutting down. let Some(state) = rt.asc.upgrade() else { log_warn!( - "{}", - gndrm_obf::obf!("retarget: the presenter is shutting down; no layer to rebuild") + "retarget: the presenter is shutting down; no layer to rebuild" ); return E_NOENT; }; @@ -1272,8 +1256,7 @@ fn retarget(env: &mut JNIEnv, surface: &JObject, width: jint, height: jint) -> j unsafe { ffi::ANativeWindow_fromSurface(env.get_native_interface(), surface.as_raw()) }; if raw.is_null() { log_error!( - "{}", - gndrm_obf::obf!("retarget: ANativeWindow_fromSurface returned null") + "retarget: ANativeWindow_fromSurface returned null" ); return E_INVAL; } @@ -1309,10 +1292,7 @@ fn retarget(env: &mut JNIEnv, surface: &JObject, width: jint, height: jint) -> j .retarget(raw, win_w, win_h); if !rebuilt { log_error!( - "{}", - gndrm_obf::obf!( - "retarget: the publish layer could not be rebuilt; keeping the current window" - ) + "retarget: the publish layer could not be rebuilt; keeping the current window" ); // SAFETY: `raw` is the extra reference this call acquired. unsafe { ffi::ANativeWindow_release(raw) }; @@ -1329,7 +1309,7 @@ fn retarget(env: &mut JNIEnv, surface: &JObject, width: jint, height: jint) -> j let _ = injector::gamescope_command("debug_force_repaint"); log_info!( "{}", - gndrm_obf::obf!("retarget: adopted the new window {win_w}x{win_h}") + format_args!("retarget: adopted the new window {win_w}x{win_h}") ); 0 } @@ -1483,7 +1463,7 @@ fn set_scanout_geometry(width: jint, height: jint) { if width < 64 || height < 64 { log_warn!( "{}", - gndrm_obf::obf!("scan-out geometry {width}x{height} below 64x64; ignored") + format_args!("scan-out geometry {width}x{height} below 64x64; ignored") ); return; } @@ -1502,7 +1482,7 @@ fn set_panel_refresh_hz(refresh_hz: jint) { if !(1..=1000).contains(&refresh_hz) { log_warn!( "{}", - gndrm_obf::obf!("panel refresh {refresh_hz} Hz out of range 1..=1000; ignored") + format_args!("panel refresh {refresh_hz} Hz out of range 1..=1000; ignored") ); return; } diff --git a/modules/gndrm-android/src/log.rs b/modules/gndrm-android/src/log.rs index d21227d..bcbc875 100644 --- a/modules/gndrm-android/src/log.rs +++ b/modules/gndrm-android/src/log.rs @@ -6,9 +6,7 @@ //! call returns before formatting; cold paths only — the per-frame hot path //! never logs. //! -//! The logcat tag is decoded at runtime from an obfuscated literal -//! ([`gndrm_obf::obfc`]), so the shipped library's tag strings are not -//! recoverable with `strings`. +//! The logcat tag is a C string literal chosen by the gate. use std::fmt; @@ -41,21 +39,20 @@ fn emit(prio: i32, gate: Gate, text: &str) { let c = std::ffi::CString::new(text) .unwrap_or_else(|_| std::ffi::CString::new("").unwrap()); macro_rules! tag { - ($t:literal) => {{ - let t = gndrm_obf::obfc!($t); - // SAFETY: `t` and `c` are NUL-terminated and outlive the call. + ($t:expr) => {{ + // SAFETY: `$t` and `c` are NUL-terminated and outlive the call. unsafe { - crate::ffi::__android_log_write(prio, t.as_cstr().as_ptr(), c.as_ptr()); + crate::ffi::__android_log_write(prio, $t.as_ptr(), c.as_ptr()); } }}; } match gate { - Gate::Daemon => tag!("gndrm-daemon"), - Gate::Asc => tag!("gndrm-asc"), - Gate::Input => tag!("gndrm-input"), - Gate::Vkshim => tag!("gn-vkshim"), - Gate::Shim => tag!("gndrm-shim"), - Gate::Fallback => tag!("gndrm"), + Gate::Daemon => tag!(c"gndrm-daemon"), + Gate::Asc => tag!(c"gndrm-asc"), + Gate::Input => tag!(c"gndrm-input"), + Gate::Vkshim => tag!(c"gn-vkshim"), + Gate::Shim => tag!(c"gndrm-shim"), + Gate::Fallback => tag!(c"gndrm"), } } @@ -84,10 +81,9 @@ pub(crate) fn daemon_always(text: &str) { /// call site's module path is classified at compile time (`const`), so it is /// never stored in the binary. /// -/// The gate is tested *before* `format_args!`: an `obf!` literal at the call -/// site is a stack decode, so a disabled line must not build the arguments at -/// all. `write` re-checks (it is also the entry for the daemon's forwarded -/// lines); this only short-circuits the decode. +/// The gate is tested *before* `format_args!`, so a disabled line never builds +/// its arguments. `write` re-checks (it is also the entry for the daemon's +/// forwarded lines); this only short-circuits the formatting. #[macro_export] macro_rules! alog { ($prio:expr, $($arg:tt)*) => {{ diff --git a/modules/gndrm-android/src/vsync.rs b/modules/gndrm-android/src/vsync.rs index d41ec57..9b72cce 100644 --- a/modules/gndrm-android/src/vsync.rs +++ b/modules/gndrm-android/src/vsync.rs @@ -265,10 +265,8 @@ pub(crate) fn sample(latch_ns: u64, applied_ns: u64) { if first && note.is_some() { log_info!( "{}", - gndrm_obf::obf!( - "vsync: panel latch grid period={}us; pushing it to the presenter", - period / 1000 - ) + format_args!("vsync: panel latch grid period={}us; pushing it to the presenter", + period / 1000) ); } note diff --git a/modules/gndrm-daemon/Cargo.toml b/modules/gndrm-daemon/Cargo.toml index 56d207e..53d74a8 100644 --- a/modules/gndrm-daemon/Cargo.toml +++ b/modules/gndrm-daemon/Cargo.toml @@ -7,7 +7,6 @@ license.workspace = true authors.workspace = true [dependencies] -gndrm-obf = { path = "../gndrm-obf" } gndrm-uapi = { path = "../gndrm-uapi" } libc = "0.2" diff --git a/modules/gndrm-daemon/src/bin/gndrm-hostd.rs b/modules/gndrm-daemon/src/bin/gndrm-hostd.rs index 8c17d15..7cd3dc1 100644 --- a/modules/gndrm-daemon/src/bin/gndrm-hostd.rs +++ b/modules/gndrm-daemon/src/bin/gndrm-hostd.rs @@ -24,7 +24,7 @@ use gndrm_daemon::{Device, NullPresenter, PanelDesc}; fn main() { let name = std::env::args() .nth(1) - .expect(&gndrm_obf::obf!("usage: gndrm-hostd ")); + .expect("usage: gndrm-hostd "); if name.starts_with('/') { let _ = std::fs::remove_file(&name); } @@ -43,7 +43,7 @@ fn main() { // Render-node clients on their own listener: the device-side path, one // Device per RPC/event pair, on the same code `libgamenative_drm.so` runs. let render_log = Arc::clone(&log); - let stop_fd = server::new_stop_eventfd().expect(&gndrm_obf::obf!("stop eventfd")); + let stop_fd = server::new_stop_eventfd().expect("stop eventfd"); thread::Builder::new() .name("gndrm-hostd-render".into()) .spawn(move || { @@ -54,7 +54,7 @@ fn main() { render_log, ); }) - .expect(&gndrm_obf::obf!("render listener thread")); + .expect("render listener thread"); // First connection = RPC, second = events (wire contract). let rpc = server::accept(listener).unwrap(); diff --git a/modules/gndrm-daemon/src/commit.rs b/modules/gndrm-daemon/src/commit.rs index c27f080..2079af9 100644 --- a/modules/gndrm-daemon/src/commit.rs +++ b/modules/gndrm-daemon/src/commit.rs @@ -64,11 +64,9 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject EINVAL unknown flags=0x{:x} reserved=0x{:x}", + format_args!("atomic: reject EINVAL unknown flags=0x{:x} reserved=0x{:x}", a.flags, - a.reserved - ) + a.reserved) ) }); return DispatchResult::err(errno::EINVAL); @@ -106,11 +104,9 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject EINVAL fence mismatch wants={} got={}", + format_args!("atomic: reject EINVAL fence mismatch wants={} got={}", parsed.wants_fence, - fd_in.is_some() - ) + fd_in.is_some()) ) }); return DispatchResult::err(errno::EINVAL); @@ -155,12 +151,10 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: first commit queued (primary fb={}, {} props, flags=0x{:x})", + format_args!("atomic: first commit queued (primary fb={}, {} props, flags=0x{:x})", self.primary_state().fb_id, parsed.sets.len(), - parsed.flags - ) + parsed.flags) ) }); } @@ -204,18 +198,15 @@ impl Device { self.always_log(|| { format!( "{}", - gndrm_obf::obf!( - "gndrm-daemon: commit #{} fb={} prev_fb={} crtc_on={} fbs={}", + format_args!("gndrm-daemon: commit #{} fb={} prev_fb={} crtc_on={} fbs={}", self.commit_count, p.fb_id, prev_primary_fb, self.crtc_state().active, - self.stores.fbs.len() - ) + self.stores.fbs.len()) ) }); - self.diag(|| format!("{}", gndrm_obf::obf!( - "atomic #{}: fb={} {}x{} fmt={:#010x} pitch={} src=({},{}) {}x{} crtc=({},{}) {}x{}", + self.diag(|| format!("{}", format_args!("atomic #{}: fb={} {}x{} fmt={:#010x} pitch={} src=({},{}) {}x{} crtc=({},{}) {}x{}", self.commit_count, p.fb_id, w, @@ -229,8 +220,7 @@ impl Device { p.crtc_x, p.crtc_y, p.crtc_w, - p.crtc_h, - ))); + p.crtc_h,))); } // Plane census: the full plane set, on the same rate policy as the // `atomic #N:` line, plus every change at once — a plane that only @@ -248,7 +238,7 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!("planes #{}: {}", self.commit_count, census) + format_args!("planes #{}: {}", self.commit_count, census) ) }); } @@ -271,10 +261,9 @@ impl Device { .iter() .map(|(id, ty, p)| { if p.fb_id == 0 { - format!("{}", gndrm_obf::obf!("[{ty} id={id} fb=0 crtc={} zpos=- alpha=- **]", p.crtc_id)) + format!("{}", format_args!("[{ty} id={id} fb=0 crtc={} zpos=- alpha=- **]", p.crtc_id)) } else { - format!("{}", gndrm_obf::obf!( - "[{ty} id={id} fb={} crtc={} zpos=- alpha=- src={}x{}+({},{}) crtc={}x{}+({},{})]", + format!("{}", format_args!("[{ty} id={id} fb={} crtc={} zpos=- alpha=- src={}x{}+({},{}) crtc={}x{}+({},{})]", p.fb_id, p.crtc_id, p.src_w >> 16, @@ -284,14 +273,13 @@ impl Device { p.crtc_w, p.crtc_h, p.crtc_x, - p.crtc_y, - )) + p.crtc_y,)) } }) .collect(); format!( "{}", - gndrm_obf::obf!("count={} {}", planes.len(), parts.join(" ")) + format_args!("count={} {}", planes.len(), parts.join(" ")) ) } @@ -368,9 +356,7 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject ENOENT unresolved prop obj={obj_id} prop=0x{prop_id:x}" - ) + format_args!("atomic: reject ENOENT unresolved prop obj={obj_id} prop=0x{prop_id:x}") ) }); return Err(DispatchResult::err(errno::ENOENT)); @@ -402,11 +388,9 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject EPERM immutable prop {} (idx {})", + format_args!("atomic: reject EPERM immutable prop {} (idx {})", props::PROPS[s.prop_index].0, - s.prop_index - ) + s.prop_index) ) }); return Err(errno::EPERM); @@ -430,13 +414,11 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject errno={} invalid prop {} (idx {}) value={}", + format_args!("atomic: reject errno={} invalid prop {} (idx {}) value={}", e, props::PROPS[s.prop_index].0, s.prop_index, - s.value - ) + s.value) ) }); return Err(e); @@ -459,11 +441,9 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject EINVAL fb={} without crtc (crtc_id={})", + format_args!("atomic: reject EINVAL fb={} without crtc (crtc_id={})", plane.fb_id, - plane.crtc_id - ) + plane.crtc_id) ) }); return Err(errno::EINVAL); @@ -490,8 +470,7 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "atomic: reject EINVAL cursor fb={} {}x{} src={}x{} crtc={}x{} exceeds {}x{}", + format_args!("atomic: reject EINVAL cursor fb={} {}x{} src={}x{} crtc={}x{} exceeds {}x{}", cursor.fb_id, fb_dims.0, fb_dims.1, @@ -500,8 +479,7 @@ impl Device { cursor.crtc_w, cursor.crtc_h, limit, - limit - ) + limit) ) }); return Err(errno::EINVAL); diff --git a/modules/gndrm-daemon/src/foreign.rs b/modules/gndrm-daemon/src/foreign.rs index 827deec..2ca1668 100644 --- a/modules/gndrm-daemon/src/foreign.rs +++ b/modules/gndrm-daemon/src/foreign.rs @@ -62,17 +62,17 @@ pub enum CopyRefusal { impl core::fmt::Display for CopyRefusal { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { - Self::Modifier(m) => write!(f, "{}", gndrm_obf::obf!("modifier {m:#x} is not linear")), + Self::Modifier(m) => write!(f, "{}", format_args!("modifier {m:#x} is not linear")), Self::Format(fourcc) => write!( f, "{}", - gndrm_obf::obf!("format {} is not 32 bpp", fourcc_name(*fourcc)) + format_args!("format {} is not 32 bpp", fourcc_name(*fourcc)) ), - Self::Geometry => write!(f, "{}", gndrm_obf::obf!("unsupported plane geometry")), + Self::Geometry => write!(f, "unsupported plane geometry"), Self::OutOfBounds { need, have } => write!( f, "{}", - gndrm_obf::obf!("rows need {need} bytes, dma-buf has {have}") + format_args!("rows need {need} bytes, dma-buf has {have}") ), } } diff --git a/modules/gndrm-daemon/src/lib.rs b/modules/gndrm-daemon/src/lib.rs index 3bfcf31..a016c83 100644 --- a/modules/gndrm-daemon/src/lib.rs +++ b/modules/gndrm-daemon/src/lib.rs @@ -706,7 +706,7 @@ impl Device { // Infallible: a fresh store has the whole blob space free. let in_formats_blob = stores .alloc_blob() - .expect(&gndrm_obf::obf!("in_formats blob id")); + .expect("in_formats blob id"); stores.blobs.insert( in_formats_blob, Blob { @@ -716,7 +716,7 @@ impl Device { ); let cursor_in_formats_blob = stores .alloc_blob() - .expect(&gndrm_obf::obf!("in_formats blob id")); + .expect("in_formats blob id"); stores.blobs.insert( cursor_in_formats_blob, Blob { @@ -727,7 +727,7 @@ impl Device { // The EDID tells gamescope whether this display is HDR10. Built once // per session from the capability the launcher passes in, so an SDR // panel gets no HDR static metadata block and gamescope stays in SDR. - let edid_blob = stores.alloc_blob().expect(&gndrm_obf::obf!("edid blob id")); + let edid_blob = stores.alloc_blob().expect("edid blob id"); stores.blobs.insert( edid_blob, Blob { @@ -737,12 +737,12 @@ impl Device { ); let (commit_tx, commit_rx) = mpsc::channel(); let flip_queue = Arc::new(Mutex::new(VecDeque::new())); - let flip_event_fd = new_eventfd(0).expect(&gndrm_obf::obf!("flip eventfd")); + let flip_event_fd = new_eventfd(0).expect("flip eventfd"); let in_flight = Arc::new(Mutex::new(HashSet::new())); let shutdown = Arc::new(AtomicBool::new(false)); let logger: Arc>> = Arc::new(Mutex::new(None)); // The worker owns the presenter and signals a dup of the flip eventfd. - let worker_fd = dup_fd(flip_event_fd, 0).expect(&gndrm_obf::obf!("dup flip eventfd")); + let worker_fd = dup_fd(flip_event_fd, 0).expect("dup flip eventfd"); // The event clock is shared with the commit worker, which re-stamps a // page-flip event when it emits it (see `commit_worker_loop`). let clock: SharedClock = Arc::new(Mutex::new(Box::new(monotonic_now))); @@ -819,9 +819,8 @@ impl Device { /// Emit the commit probe through the ungated sink, if one is installed. /// - /// `msg` is a thunk so the message (and any `obf!` literal in it, which is a - /// stack decode) is built only at the probe's own rate limit, never per - /// frame. See [`Device::set_always_logger`]. + /// `msg` is a thunk so the message is built only at the probe's own rate + /// limit, never per frame. See [`Device::set_always_logger`]. pub(crate) fn always_log(&self, msg: impl FnOnce() -> String) { if let Some(log) = &self.always_logger { log(&msg()); @@ -871,19 +870,16 @@ impl Device { fn note_exhausted(&mut self, space: &'static str) -> i32 { if !self.logged_exhaustion.contains(&space) { self.logged_exhaustion.push(space); - self.diag(|| format!("{}", gndrm_obf::obf!( - "resource: {space} exhausted; returning ENOSPC (display path degraded, app continues)" - ))); + self.diag(|| format!("{}", format_args!("resource: {space} exhausted; returning ENOSPC (display path degraded, app continues)"))); } errno::ENOSPC } /// Emit a diagnostic through the installed logger, if any. /// - /// `msg` is a thunk: the message (and any `obf!` literal in it, which is a - /// stack decode) is built only when a logger is installed. The app installs - /// the logger only when `GNDRM_LOG_DAEMON` is on, so a disabled daemon never - /// decodes a line it would drop. + /// `msg` is a thunk: the message is built only when a logger is installed. + /// The app installs the logger only when `GNDRM_LOG_DAEMON` is on, so a + /// disabled daemon never formats a line it would drop. pub(crate) fn diag(&self, msg: impl FnOnce() -> String) { if let Some(log) = self .logger @@ -1070,7 +1066,7 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!("ioctl: first {} (0x{ioctl_nr:08x})", ioctl_name(ioctl_nr)) + format_args!("ioctl: first {} (0x{ioctl_nr:08x})", ioctl_name(ioctl_nr)) ) }); } @@ -1081,10 +1077,8 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "render node: refused {} (0x{ioctl_nr:08x})", - ioctl_name(ioctl_nr) - ) + format_args!("render node: refused {} (0x{ioctl_nr:08x})", + ioctl_name(ioctl_nr)) ) }); DispatchResult::err(errno::EACCES) @@ -1212,12 +1206,10 @@ impl Device { self.always_log(|| { format!( "{}", - gndrm_obf::obf!( - "cursor: cursor layer {} (max {}x{})", + format_args!("cursor: cursor layer {} (max {}x{})", if on { "on" } else { "off" }, self.cursor_limit(), - self.cursor_limit() - ) + self.cursor_limit()) ) }); } @@ -1974,10 +1966,8 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "addfb2: refused {}x{} pitch={} offset={}: buffer ino {ino} is {gem_size} bytes, the image needs {need}", - cmd.width, cmd.height, cmd.pitches[0], cmd.offsets[0] - ) + format_args!("addfb2: refused {}x{} pitch={} offset={}: buffer ino {ino} is {gem_size} bytes, the image needs {need}", + cmd.width, cmd.height, cmd.pitches[0], cmd.offsets[0]) ) }); } @@ -2027,10 +2017,8 @@ impl Device { self.diag(|| { format!( "{}", - gndrm_obf::obf!( - "addfb2: fb {}x{} fmt={:#x} gem={} modifier={:#x} registered into the length index", - cmd.width, cmd.height, cmd.pixel_format, gem_size, modifier - ) + format_args!("addfb2: fb {}x{} fmt={:#x} gem={} modifier={:#x} registered into the length index", + cmd.width, cmd.height, cmd.pixel_format, gem_size, modifier) ) }); } @@ -2657,7 +2645,7 @@ mod tests { }; let r = dev.dispatch(DRM_IOCTL_GET_CAP, &body_of(&c), None); assert_eq!(r.ret, 0, "GET_CAP 0x{cap:x} failed"); - c = pod_read::(&r.body).expect(&gndrm_obf::obf!("GET_CAP body")); + c = pod_read::(&r.body).expect("GET_CAP body"); c.value } @@ -2681,7 +2669,7 @@ mod tests { }; let r = d.dispatch(DRM_IOCTL_VERSION, &body_of(&v), None); assert_eq!(r.ret, 0); - v = pod_read::(&r.body).expect(&gndrm_obf::obf!("VERSION body")); + v = pod_read::(&r.body).expect("VERSION body"); assert_eq!(v.version_major, DRIVER_VERSION.0); assert!(v.name_len > 0); @@ -2740,7 +2728,7 @@ mod tests { }; let r = d.dispatch(DRM_IOCTL_GEM_CREATE, &body_of(&req), None); assert_eq!(r.ret, 0, "GEM_CREATE failed"); - let created = pod_read::(&r.body).expect(&gndrm_obf::obf!("GEM_CREATE body")); + let created = pod_read::(&r.body).expect("GEM_CREATE body"); assert!(created.handle > 0, "GEM_CREATE must return a handle"); assert_eq!(created.size, 4096); @@ -2753,7 +2741,7 @@ mod tests { }; let r = d.dispatch(DRM_IOCTL_GEM_MMAP, &body_of(&m), None); assert_eq!(r.ret, 0, "GEM_MMAP failed"); - m = pod_read::(&r.body).expect(&gndrm_obf::obf!("GEM_MMAP body")); + m = pod_read::(&r.body).expect("GEM_MMAP body"); assert_eq!(m.size, 4096); assert_eq!(m.offset & GEM_MMAP_OFFSET_BASE, GEM_MMAP_OFFSET_BASE); assert_eq!(m.offset & GEM_MMAP_HANDLE_MASK, u64::from(created.handle)); @@ -2768,7 +2756,7 @@ mod tests { assert_eq!(r.ret, 0, "PRIME_HANDLE_TO_FD failed"); let exported = r .fd_out - .expect(&gndrm_obf::obf!("export must attach an fd")); + .expect("export must attach an fd"); assert!(exported >= 0); // It is a real, sized file: fstat succeeds and reports the size. assert_eq!(fstat_fd(exported).map(|(_, sz)| sz), Some(4096)); diff --git a/modules/gndrm-daemon/src/objects.rs b/modules/gndrm-daemon/src/objects.rs index 801313d..1063063 100644 --- a/modules/gndrm-daemon/src/objects.rs +++ b/modules/gndrm-daemon/src/objects.rs @@ -108,7 +108,7 @@ impl PanelDesc { let clock = (u64::from(htotal) * u64::from(vtotal) * u64::from(refresh_mhz) / 1_000_000) as u32; let mut name = [0u8; DRM_DISPLAY_MODE_LEN]; - let label = format!("{}", gndrm_obf::obf!("{}x{}", self.width, self.height)); + let label = format!("{}", format_args!("{}x{}", self.width, self.height)); name[..label.len()].copy_from_slice(label.as_bytes()); DrmModeModeinfo { clock, diff --git a/modules/gndrm-daemon/src/scanout.rs b/modules/gndrm-daemon/src/scanout.rs index 0915d6c..f5c0ee0 100644 --- a/modules/gndrm-daemon/src/scanout.rs +++ b/modules/gndrm-daemon/src/scanout.rs @@ -596,7 +596,7 @@ mod tests { let (payload, cold) = match pool.begin(g) { Reservation::Reuse { payload, .. } => (payload, false), Reservation::Cold { .. } => (cold_id, true), - Reservation::Full => panic!("{}", gndrm_obf::obf!("pool reported full at {g:?}")), + Reservation::Full => panic!("{}", format_args!("pool reported full at {g:?}")), }; pool.commit(id, g, payload, Arc::clone(&latch), cold); latch @@ -654,10 +654,8 @@ mod tests { } => {} other => panic!( "{}", - gndrm_obf::obf!( - "expected the retired buffer to be handed back out, got {}", - describe(&other) - ) + format_args!("expected the retired buffer to be handed back out, got {}", + describe(&other)) ), } assert_eq!(pool.free_len(), 0, "the reused buffer left the free list"); @@ -683,7 +681,7 @@ mod tests { Reservation::Reuse { ino, payload } => (ino, payload), other => panic!( "{}", - gndrm_obf::obf!("expected reuse, got {}", describe(&other)) + format_args!("expected reuse, got {}", describe(&other)) ), }; assert_eq!(reserved, (42, 42), "the free-list entry kept its ino"); @@ -717,7 +715,7 @@ mod tests { Reservation::Reuse { ino, payload } => (ino, payload), other => panic!( "{}", - gndrm_obf::obf!("expected reuse, got {}", describe(&other)) + format_args!("expected reuse, got {}", describe(&other)) ), }; assert_eq!(ino, 7, "the retained identity is stable across cycles"); @@ -778,10 +776,8 @@ mod tests { Reservation::Cold { evicted: None } => {} other => panic!( "{}", - gndrm_obf::obf!( - "expected a cold allocation while the buffer is in flight, got {}", - describe(&other) - ) + format_args!("expected a cold allocation while the buffer is in flight, got {}", + describe(&other)) ), } } @@ -812,7 +808,7 @@ mod tests { } other => panic!( "{}", - gndrm_obf::obf!("expected an eviction, got {}", describe(&other)) + format_args!("expected an eviction, got {}", describe(&other)) ), } assert_eq!(pool.free_len(), 1, "exactly one buffer was evicted"); @@ -839,7 +835,7 @@ mod tests { } Reservation::Full => panic!( "{}", - gndrm_obf::obf!("pool unexpectedly full at frame {frame}") + format_args!("pool unexpectedly full at frame {frame}") ), }; let latch = Arc::new(AtomicBool::new(false)); @@ -923,9 +919,9 @@ mod tests { Some(Reservation::Cold { evicted: None }) => {} Some(other) => panic!( "{}", - gndrm_obf::obf!("expected a cold reservation, got {}", describe(&other)) + format_args!("expected a cold reservation, got {}", describe(&other)) ), - None => panic!("{}", gndrm_obf::obf!("a known geometry must resolve")), + None => panic!("{}", "a known geometry must resolve"), } assert_eq!( pool.resolve_len(4096, 5), @@ -1095,7 +1091,7 @@ mod tests { for g in geoms { let reservation = pool .begin_len(g.alloc_len(), g.format) - .expect(&gndrm_obf::obf!("known geometry")); + .expect("known geometry"); let (id, cold) = match reservation { Reservation::Reuse { payload, .. } => (payload, false), Reservation::Cold { evicted: None } => { @@ -1106,10 +1102,10 @@ mod tests { Reservation::Cold { evicted: Some(_) } => { panic!( "{}", - gndrm_obf::obf!("pool thrashed: evicted a free buffer at cap {CAP}") + format_args!("pool thrashed: evicted a free buffer at cap {CAP}") ) } - Reservation::Full => panic!("{}", gndrm_obf::obf!("pool wedged at cap {CAP}")), + Reservation::Full => panic!("{}", format_args!("pool wedged at cap {CAP}")), }; let latch = Arc::new(AtomicBool::new(false)); pool.commit(id, g, id, Arc::clone(&latch), cold); @@ -1134,7 +1130,7 @@ mod tests { } } - let settled = settled_at.expect(&gndrm_obf::obf!("round 5 ran")); + let settled = settled_at.expect("round 5 ran"); assert_eq!( allocations, settled, "allocations must stop once every geometry's working set is warm" diff --git a/modules/gndrm-daemon/src/server.rs b/modules/gndrm-daemon/src/server.rs index 5021039..7318f8f 100644 --- a/modules/gndrm-daemon/src/server.rs +++ b/modules/gndrm-daemon/src/server.rs @@ -58,7 +58,7 @@ pub type SharedLog = Arc; /// card listener's scan-out allocator. #[must_use] pub fn render_socket_name(main: &str) -> String { - format!("{}", gndrm_obf::obf!("{main}-render")) + format!("{}", format_args!("{main}-render")) } /// Resolve `name` into a bound + listening `SOCK_SEQPACKET` fd. @@ -262,11 +262,11 @@ pub fn serve_render_listener( if e.raw_os_error() == Some(libc::EINTR) { continue; } - log(&format!("{}", gndrm_obf::obf!("render listener poll: {e}"))); + log(&format!("{}", format_args!("render listener poll: {e}"))); break; } if pfds[1].revents != 0 { - log(&gndrm_obf::obf!("render listener stopping")); + log("render listener stopping"); break; } if pfds[0].revents == 0 { @@ -277,7 +277,7 @@ pub fn serve_render_listener( Err(e) => { log(&format!( "{}", - gndrm_obf::obf!("render listener accept: {e}") + format_args!("render listener accept: {e}") )); break; } @@ -288,7 +288,7 @@ pub fn serve_render_listener( // Second half of this client: its event channel. Serve the pair. log(&format!( "{}", - gndrm_obf::obf!("render client paired (pid {pid})") + format_args!("render client paired (pid {pid})") )); clients .lock() @@ -297,7 +297,7 @@ pub fn serve_render_listener( let make_device = Arc::clone(&make_device); let thread_log = Arc::clone(&log); let thread_clients = Arc::clone(&clients); - let name = format!("{}", gndrm_obf::obf!("gndrm-rn{next_id}")); + let name = format!("{}", format_args!("gndrm-rn{next_id}")); next_id += 1; let spawned = thread::Builder::new().name(name).spawn(move || { let mut dev = make_device(); @@ -319,7 +319,7 @@ pub fn serve_render_listener( match spawned { Ok(h) => handles.push(h), Err(e) => { - log(&format!("{}", gndrm_obf::obf!("render client spawn: {e}"))); + log(&format!("{}", format_args!("render client spawn: {e}"))); if let Ok(mut c) = clients.lock() { c.retain(|(r, ev)| !(*r == rpc && *ev == fd)); } @@ -341,9 +341,7 @@ pub fn serve_render_listener( // the daemon half of that handshake. log(&format!( "{}", - gndrm_obf::obf!( - "render client rpc accepted (pid {pid}), awaiting event channel" - ) + format_args!("render client rpc accepted (pid {pid}), awaiting event channel") )); pending.insert(pid, fd); } @@ -405,7 +403,7 @@ pub fn serve(dev: &mut Device, rpc_fd: RawFd, event_fd: RawFd, log: Log) { if e.raw_os_error() == Some(libc::EINTR) { continue; } - log(&format!("{}", gndrm_obf::obf!("poll: {e}"))); + log(&format!("{}", format_args!("poll: {e}"))); return; } // Flip events are ready: write them to the client's event channel in @@ -415,7 +413,7 @@ pub fn serve(dev: &mut Device, rpc_fd: RawFd, event_fd: RawFd, log: Log) { let mut bytes = Vec::new(); pod_write(&mut bytes, &ev); if let Err(e) = send_frame(event_fd, &bytes, None) { - log(&format!("{}", gndrm_obf::obf!("event send failed: {e}"))); + log(&format!("{}", format_args!("event send failed: {e}"))); return; } } @@ -426,16 +424,16 @@ pub fn serve(dev: &mut Device, rpc_fd: RawFd, event_fd: RawFd, log: Log) { let (n, fd_in) = match recv_frame(rpc_fd, &mut buf) { Ok(v) => v, Err(e) => { - log(&format!("{}", gndrm_obf::obf!("recv: {e}"))); + log(&format!("{}", format_args!("recv: {e}"))); return; } }; if n == 0 { - log(&gndrm_obf::obf!("peer closed")); + log("peer closed"); return; } let Ok(hdr) = ReqHdr::decode(&buf[..n]) else { - log(&gndrm_obf::obf!("bad request header, dropping")); + log("bad request header, dropping"); return; }; let payload = &buf[REQ_HDR_LEN..hdr.total_len as usize]; @@ -459,7 +457,7 @@ pub fn serve(dev: &mut Device, rpc_fd: RawFd, event_fd: RawFd, log: Log) { close_fd(fd); } if let Err(e) = sent { - log(&format!("{}", gndrm_obf::obf!("send failed: {e}"))); + log(&format!("{}", format_args!("send failed: {e}"))); return; } } @@ -577,11 +575,9 @@ mod tests { static N: AtomicU32 = AtomicU32::new(0); format!( "{}", - gndrm_obf::obf!( - "gndrm-srv-{}-{}", + format_args!("gndrm-srv-{}-{}", std::process::id(), - N.fetch_add(1, Ordering::Relaxed) - ) + N.fetch_add(1, Ordering::Relaxed)) ) } @@ -592,11 +588,11 @@ mod tests { #[test] fn accept_newest_adopts_the_latest_and_drops_the_superseded() { let name = unique_name(); - let listener = listen_seqpacket(&name).expect(&gndrm_obf::obf!("listen")); + let listener = listen_seqpacket(&name).expect("listen"); let old = client_connect(&name); let new = client_connect(&name); - let adopted = accept_newest(listener).expect(&gndrm_obf::obf!("accept_newest")); + let adopted = accept_newest(listener).expect("accept_newest"); // The adopted fd is the newest client: a byte it sends is readable here. let marker = [0xA5u8]; @@ -631,10 +627,10 @@ mod tests { #[test] fn accept_newest_adopts_a_lone_connection() { let name = unique_name(); - let listener = listen_seqpacket(&name).expect(&gndrm_obf::obf!("listen")); + let listener = listen_seqpacket(&name).expect("listen"); let client = client_connect(&name); - let adopted = accept_newest(listener).expect(&gndrm_obf::obf!("accept_newest")); + let adopted = accept_newest(listener).expect("accept_newest"); let marker = [0x11u8]; // SAFETY: valid sockets and a one-byte buffer. @@ -681,7 +677,7 @@ mod tests { let n = unsafe { libc::recv(fd, buf.as_mut_ptr().cast(), buf.len(), 0) }; assert!(n > 0, "recv: {}", io::Error::last_os_error()); let n = n as usize; - let hdr = RespHdr::decode(&buf[..n]).expect(&gndrm_obf::obf!("response header")); + let hdr = RespHdr::decode(&buf[..n]).expect("response header"); (hdr.ret, buf[RESP_HDR_LEN..n].to_vec()) } @@ -699,8 +695,8 @@ mod tests { use gndrm_uapi::wire::errno; let name = unique_name(); - let listener = listen_seqpacket(&name).expect(&gndrm_obf::obf!("listen")); - let stop_fd = new_stop_eventfd().expect(&gndrm_obf::obf!("stop eventfd")); + let listener = listen_seqpacket(&name).expect("listen"); + let stop_fd = new_stop_eventfd().expect("stop eventfd"); let log: SharedLog = Arc::new(|_| {}); let acceptor = thread::spawn(move || { serve_render_listener( @@ -740,7 +736,7 @@ mod tests { ); let (ret, out) = exchange(rpc, &req(DRM_IOCTL_GEM_CREATE, &body, 2)); assert_eq!(ret, 0, "GEM_CREATE on a render node"); - let created: DrmGemCreate = pod_read(&out).expect(&gndrm_obf::obf!("GEM_CREATE body")); + let created: DrmGemCreate = pod_read(&out).expect("GEM_CREATE body"); assert!(created.handle > 0, "GEM_CREATE returned a handle"); // Modesetting is refused on a render node (DRM_RENDER_ALLOW gate). @@ -761,7 +757,7 @@ mod tests { signal_stop(stop_fd); acceptor .join() - .expect(&gndrm_obf::obf!("render acceptor thread")); + .expect("render acceptor thread"); } /// The render listener name the shim and the daemon must agree on. diff --git a/modules/gndrm-lsfg/Cargo.toml b/modules/gndrm-lsfg/Cargo.toml index c385763..bab9692 100644 --- a/modules/gndrm-lsfg/Cargo.toml +++ b/modules/gndrm-lsfg/Cargo.toml @@ -16,6 +16,3 @@ crate-type = ["rlib"] [dependencies] libc = "0.2" -# The shim's log gate prefixes every diagnostic; literals stay obfuscated so a -# shipped binary's strings do not spell out the engine's internals. -gndrm-obf = { path = "../gndrm-obf" } diff --git a/modules/gndrm-lsfg/src/cache.rs b/modules/gndrm-lsfg/src/cache.rs index a017740..b0346c9 100644 --- a/modules/gndrm-lsfg/src/cache.rs +++ b/modules/gndrm-lsfg/src/cache.rs @@ -376,11 +376,9 @@ pub fn build(dll_path: &Path, cache_path: &Path, prefer_fp16: bool) -> LsfgStatu _ => None, }; let Some(words) = words else { - log!(::gndrm_obf::obf!( - "lsfg: shader {} failed ({})", + log!(format_args!("lsfg: shader {} failed ({})", id, - if translating { "dxbc" } else { "spirv" } - )); + if translating { "dxbc" } else { "spirv" })); return LsfgStatus::TranslationFailed; }; modules.push(Module { id, words }); @@ -397,11 +395,9 @@ pub fn build(dll_path: &Path, cache_path: &Path, prefer_fp16: bool) -> LsfgStatu if !write_atomic(cache_path, &encoded) { return LsfgStatus::CacheUnusable; } - log!(::gndrm_obf::obf!( - "lsfg: cached {} modules (source={})", + log!(format_args!("lsfg: cached {} modules (source={})", modules.len(), - header.variant.name() - )); + header.variant.name())); LsfgStatus::Ok } diff --git a/modules/gndrm-lsfg/src/lib.rs b/modules/gndrm-lsfg/src/lib.rs index 2570c9e..02445f0 100644 --- a/modules/gndrm-lsfg/src/lib.rs +++ b/modules/gndrm-lsfg/src/lib.rs @@ -24,7 +24,7 @@ use std::path::{Path, PathBuf}; macro_rules! log { ($e:expr) => { if $crate::logging() { - eprintln!("{} {}", ::gndrm_obf::obf!("gn-vkshim:"), $e); + eprintln!("{} {}", "gn-vkshim:", $e); } }; } diff --git a/modules/gndrm-obf-macros/Cargo.toml b/modules/gndrm-obf-macros/Cargo.toml deleted file mode 100644 index a537c1f..0000000 --- a/modules/gndrm-obf-macros/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -# gndrm-obf-macros — the `obf!`/`obfc!` proc macros backing `gndrm-obf`. -# -# `syn` parses the input literal and argument expressions (correct Rust string -# un-escaping and format placeholder handling — the crux of the transform); -# `quote` emits the decode-byte array and the `write!` call. - -[package] -name = "gndrm-obf-macros" -description = "obf!/obfc! proc macros: XOR-encode literals, emit stack decode + format_args" -version.workspace = true -edition.workspace = true -license.workspace = true -authors.workspace = true - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1" -quote = "1" -syn = { version = "2", default-features = false, features = ["parsing", "printing", "proc-macro", "full"] } diff --git a/modules/gndrm-obf-macros/src/lib.rs b/modules/gndrm-obf-macros/src/lib.rs deleted file mode 100644 index 2cd46d8..0000000 --- a/modules/gndrm-obf-macros/src/lib.rs +++ /dev/null @@ -1,245 +0,0 @@ -//! `obf!` / `obfc!` — compile-time string obfuscation. -//! -//! `obf!("...")` expands to a stack-decoded string value ([`gndrm_obf::Obf`]). -//! `obf!("literal {arg:spec}", args...)` additionally reproduces `format_args!` -//! semantics: the literal text is decoded at runtime and the arguments are -//! formatted in place, so the message never lands in `.rodata`. -//! `obfc!("...")` produces a NUL-terminated decoded value for C string use. -//! -//! Load-bearing strings (env names, Vulkan names, socket names, runtime-compared -//! paths) are deliberately left as plain literals by the call sites. - -use proc_macro::TokenStream; -use proc_macro2::Literal; -use quote::quote; -use syn::{ - parse::{Parse, ParseStream}, - parse_macro_input, Expr, LitStr, Token, -}; - -/// Parse `"fmt", arg, arg, ...`. -struct Input { - fmt: LitStr, - args: Vec, -} - -impl Parse for Input { - fn parse(input: ParseStream<'_>) -> syn::Result { - let fmt: LitStr = input.parse()?; - let mut args = Vec::new(); - while input.peek(Token![,]) { - input.parse::()?; - if input.is_empty() { - break; - } - args.push(input.parse::()?); - } - Ok(Input { fmt, args }) - } -} - -/// A parsed format string: literal runs and placeholders, in order. -enum Seg { - Text(String), - Place { name: Option, spec: String }, -} - -/// Split a Rust format string into text runs and placeholders. -fn parse_fmt(s: &str) -> syn::Result> { - let mut segs = Vec::new(); - let mut text = String::new(); - let mut it = s.chars().peekable(); - while let Some(c) = it.next() { - match c { - '{' => { - if it.peek() == Some(&'{') { - it.next(); - text.push('{'); - continue; - } - if !text.is_empty() { - segs.push(Seg::Text(std::mem::take(&mut text))); - } - let mut inner = String::new(); - loop { - match it.next() { - Some('}') => break, - Some('{') => { - return Err(syn::Error::new( - proc_macro2::Span::call_site(), - "obf!: nested format placeholders are unsupported", - )) - } - Some(ch) => inner.push(ch), - None => { - return Err(syn::Error::new( - proc_macro2::Span::call_site(), - "obf!: unterminated format placeholder", - )) - } - } - } - let (name, spec) = match inner.split_once(':') { - Some((n, sp)) => (n.to_string(), format!(":{sp}")), - None => (inner, String::new()), - }; - let name = if name.is_empty() { None } else { Some(name) }; - segs.push(Seg::Place { name, spec }); - } - '}' => { - if it.peek() == Some(&'}') { - it.next(); - } - text.push('}'); - } - other => text.push(other), - } - } - if !text.is_empty() { - segs.push(Seg::Text(text)); - } - Ok(segs) -} - -/// Per-literal XOR key: FNV-1a over the bytes, low 8 bits. -fn key_for(bytes: &[u8]) -> u8 { - let mut h: u32 = 0x811c_dc35; - for &b in bytes { - h ^= u32::from(b); - h = h.wrapping_mul(0x0100_0193); - } - h as u8 -} - -/// Encode `bytes` under `key` (inverse of `gndrm_obf::Obf::new`). -fn encode(bytes: &[u8], key: u8) -> Vec { - bytes - .iter() - .enumerate() - .map(|(i, &b)| b ^ key.wrapping_add(i as u8)) - .collect() -} - -/// Emit `::gndrm_obf::Obf::::new([..], K)` for `text`. -fn obf_tokens(text: &str) -> proc_macro2::TokenStream { - let bytes = text.as_bytes(); - let n = bytes.len(); - let key = key_for(bytes); - let enc = encode(bytes, key); - let elems = enc.iter().map(|b| Literal::u8_unsuffixed(*b)); - quote! { ::gndrm_obf::Obf::<#n>::new([#(#elems),*], #key) } -} - -/// `obfc!("literal")` — a NUL-terminated decoded C string. -#[proc_macro] -pub fn obfc(input: TokenStream) -> TokenStream { - let lit = parse_macro_input!(input as LitStr); - let mut bytes = lit.value().into_bytes(); - bytes.push(0); - let n = bytes.len(); - let key = key_for(&bytes); - let enc = encode(&bytes, key); - let elems = enc.iter().map(|b| Literal::u8_unsuffixed(*b)); - quote! { ::gndrm_obf::ObfC::<#n>::new([#(#elems),*], #key) }.into() -} - -/// `obf!("literal {arg:spec}", args...)`. -#[proc_macro] -pub fn obf(input: TokenStream) -> TokenStream { - let Input { fmt, args } = parse_macro_input!(input as Input); - let segs = match parse_fmt(&fmt.value()) { - Ok(s) => s, - Err(e) => return e.to_compile_error().into(), - }; - - // Named args (`name = expr`), if any; the rest stay positional. Expressions - // are carried as token streams (syn::Expr is not `Clone`). - let mut named: Vec<(String, proc_macro2::TokenStream)> = Vec::new(); - let mut positional: Vec = Vec::new(); - for a in args { - match a { - Expr::Assign(asn) => { - if let Expr::Path(p) = asn.left.as_ref() { - if let Some(id) = p.path.get_ident() { - named.push((id.to_string(), quote::ToTokens::to_token_stream(&asn.right))); - continue; - } - } - positional.push(quote::ToTokens::to_token_stream(&Expr::Assign(asn))); - } - other => positional.push(quote::ToTokens::to_token_stream(&other)), - } - } - - let mut fmt_out = String::new(); - let mut emit: Vec = Vec::new(); - let mut next_pos = 0usize; - let mut saw_place = false; - - for seg in segs { - match seg { - Seg::Text(t) => { - fmt_out.push_str("{}"); - emit.push(obf_tokens(&t)); - } - Seg::Place { name, spec } => { - saw_place = true; - fmt_out.push('{'); - fmt_out.push_str(&spec); - fmt_out.push('}'); - let expr: proc_macro2::TokenStream = match &name { - None => { - if next_pos >= positional.len() { - return syn::Error::new(fmt.span(), "obf!: missing format argument") - .to_compile_error() - .into(); - } - let e = positional[next_pos].clone(); - next_pos += 1; - e - } - Some(n) => { - if let Ok(idx) = n.parse::() { - match positional.get(idx) { - Some(e) => e.clone(), - None => { - return syn::Error::new( - fmt.span(), - "obf!: positional index out of range", - ) - .to_compile_error() - .into(); - } - } - } else if let Some((_, e)) = named.iter().find(|(nm, _)| nm == n) { - e.clone() - } else { - // Captured identifier: re-emit the name as a value. - match syn::parse_str::(n) { - Ok(e) => quote::ToTokens::to_token_stream(&e), - Err(err) => return err.to_compile_error().into(), - } - } - } - }; - emit.push(expr); - } - } - } - - // Pure literal — no formatting needed. - if !saw_place { - if let Some(only) = emit.into_iter().next() { - return only.into(); - } - return syn::Error::new(fmt.span(), "obf!: empty literal") - .to_compile_error() - .into(); - } - - let fmt_lit = LitStr::new(&fmt_out, fmt.span()); - quote! { - ::gndrm_obf::fmt_with(|__f| ::core::write!(__f, #fmt_lit, #(#emit),*)) - } - .into() -} diff --git a/modules/gndrm-obf/Cargo.toml b/modules/gndrm-obf/Cargo.toml deleted file mode 100644 index 51296a3..0000000 --- a/modules/gndrm-obf/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -# gndrm-obf — compile-time string obfuscation for the shipped libraries. -# -# Message/diagnostic literals are XOR-encoded at expansion so they never appear -# in `.rodata`; the runtime half (`gndrm-obf`) decodes into a stack buffer at -# the use site. `syn`/`quote`/`proc-macro2` are the standard proc-macro toolkit -# and the only way to parse a Rust format string (escapes, capture idents, -# specs) correctly without hand-rolling a lexer. - -[package] -name = "gndrm-obf" -description = "Compile-time string obfuscation: decode macro + runtime decode buffer" -version.workspace = true -edition.workspace = true -license.workspace = true -authors.workspace = true - -[lib] -name = "gndrm_obf" - -[dependencies] -gndrm-obf-macros = { path = "../gndrm-obf-macros" } diff --git a/modules/gndrm-obf/src/lib.rs b/modules/gndrm-obf/src/lib.rs deleted file mode 100644 index 0899842..0000000 --- a/modules/gndrm-obf/src/lib.rs +++ /dev/null @@ -1,158 +0,0 @@ -//! Compile-time string obfuscation for the shipped libraries. -//! -//! Message and diagnostic string literals are stored XOR-encoded in `.rodata` -//! and decoded into a stack buffer at the use site, so `strings` over a shipped -//! artifact no longer recovers log/error text. Encoding happens at macro -//! expansion (see `gndrm-obf-macros`); decoding is a per-byte XOR into a fixed -//! local array — no allocation, no heap, no global state. -//! -//! Functionally load-bearing strings (env var names, Vulkan layer/extension -//! names, socket/protocol names, device paths compared at runtime) are left -//! readable by design. - -use std::ffi::CStr; -use std::fmt; -use std::ops::Deref; - -// The `obf!`/`obfc!` macros expand to `::gndrm_obf::…` paths; this makes that -// path resolve inside this crate too (its own unit tests). -extern crate self as gndrm_obf; - -pub use gndrm_obf_macros::obf; -pub use gndrm_obf_macros::obfc; - -/// One byte of the position-varying XOR key stream. -#[inline] -#[must_use] -pub const fn key_byte(key: u8, i: usize) -> u8 { - key.wrapping_add(i as u8) -} - -/// A string literal decoded into a stack-resident byte array. -/// -/// The encoded bytes come from [`obf`]; [`Obf::new`] applies the XOR key at -/// runtime. The buffer is valid UTF-8 by construction (the encoder only ever -/// XORs the original literal's bytes). -pub struct Obf([u8; N]); - -impl Obf { - /// Decode `enc` in place under `key`. - /// - /// Not `const`, and the key is passed through [`std::hint::black_box`], so - /// the optimizer cannot constant-fold the XOR back into a decoded `.rodata` - /// string — which would defeat the obfuscation entirely. - #[inline] - #[must_use] - pub fn new(enc: [u8; N], key: u8) -> Self { - let key = std::hint::black_box(key); - let mut b = enc; - let mut i = 0; - while i < N { - b[i] ^= key_byte(key, i); - i += 1; - } - Obf(b) - } -} - -impl Deref for Obf { - type Target = str; - - #[inline] - fn deref(&self) -> &str { - // The encoder XORs the original literal's bytes, which are valid - // UTF-8; the decode is the exact inverse, so the result is valid. - unsafe { std::str::from_utf8_unchecked(&self.0) } - } -} - -impl fmt::Display for Obf { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self) - } -} - -impl AsRef for Obf { - fn as_ref(&self) -> &str { - self - } -} - -/// A NUL-terminated literal decoded into a stack-resident byte array. -/// -/// Same encoding as [`Obf`], but the encoded buffer carries the terminating -/// NUL so the decoded value is a valid [`CStr`] — used for logcat tags handed -/// to `__android_log_write`. -pub struct ObfC([u8; N]); - -impl ObfC { - /// Decode `enc` (a literal plus its NUL) under `key`. See [`Obf::new`] for - /// why this is not `const` and black-boxes the key. - #[inline] - #[must_use] - pub fn new(enc: [u8; N], key: u8) -> Self { - let key = std::hint::black_box(key); - let mut b = enc; - let mut i = 0; - while i < N { - b[i] ^= key_byte(key, i); - i += 1; - } - ObfC(b) - } - - /// The decoded value as a C string. - /// - /// # Panics - /// Only if `N == 0` (the encoder always appends the NUL). - #[inline] - #[must_use] - pub fn as_cstr(&self) -> &CStr { - CStr::from_bytes_with_nul(&self.0).expect("obfc encoding includes the NUL") - } -} - -/// A [`fmt::Display`] adaptor over a closure that writes with `write!`. -/// -/// `obf!` expands to this so the decoded pieces (whose buffers must not -/// outlive the formatting statement) are written through the formatter the -/// caller already holds, never stored. -pub struct FmtWith(F); - -impl) -> fmt::Result> fmt::Display for FmtWith { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - (self.0)(f) - } -} - -/// Wrap a formatting closure as a [`fmt::Display`] value. -#[inline] -#[must_use] -pub fn fmt_with) -> fmt::Result>(f: F) -> FmtWith { - FmtWith(f) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn obf_roundtrips() { - let s = obf!("scan-out acceptor poll: {}", 7u32); - assert_eq!(s.to_string(), "scan-out acceptor poll: 7"); - } - - #[test] - fn obfc_matches_plain() { - let t = obfc!("gndrm-daemon"); - assert_eq!(t.as_cstr().to_str().unwrap(), "gndrm-daemon"); - } - - #[test] - fn obf_escapes() { - assert_eq!( - obf!("a\tb\n\"q\"\u{1f600}").to_string(), - "a\tb\n\"q\"\u{1f600}" - ); - } -} diff --git a/modules/gndrm-uapi/Cargo.toml b/modules/gndrm-uapi/Cargo.toml index 96a5010..40adf3d 100644 --- a/modules/gndrm-uapi/Cargo.toml +++ b/modules/gndrm-uapi/Cargo.toml @@ -10,8 +10,5 @@ authors.workspace = true all = "deny" pedantic = "warn" -[dependencies] -gndrm-obf = { path = "../gndrm-obf" } - [dev-dependencies] cc = "1" diff --git a/tools/build-shim.sh b/tools/build-shim.sh index 4f694e4..ad8ab08 100755 --- a/tools/build-shim.sh +++ b/tools/build-shim.sh @@ -20,13 +20,9 @@ export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(git -C "$ROOT" log -1 --format= # -ffile-prefix-map scrubs the build-host path from __FILE__/debug records so it # cannot leak into the shipped .so (the Rust side has --remap-path-prefix). CFLAGS="-Wall -Wextra -Werror -O2 -fPIC -ffile-prefix-map=$ROOT=. -ffile-prefix-map=$PWD=." -# The shim's log text is obfuscated at build time: obf-shim.py rewrites each -# LOG(...) site to decode an XOR-encoded literal, so `strings` on the shipped -# .so no longer recovers the messages. The .c stays the readable source. -GEN="$OUT/gen" -mkdir -p "$GEN" -CSRC="$GEN/gndrm_shim.c" -python3 "$ROOT/tools/obf-shim.py" "$SRC" "$CSRC" +# The .c is compiled as written: the project is open source, so its log text is +# a plain literal and `strings` on the shipped .so is expected to find it. +CSRC="$SRC" # NOTE: no -fvisibility=hidden — the interposed symbols (open/ioctl/close) # must stay exported for LD_PRELOAD interposition to work at all. What pins the # exported set is the linker version script below: it makes everything except diff --git a/tools/obf-shim.py b/tools/obf-shim.py deleted file mode 100644 index 7843e67..0000000 --- a/tools/obf-shim.py +++ /dev/null @@ -1,218 +0,0 @@ -#!/usr/bin/env python3 -"""obf-shim.py — compile-time obfuscation of the LD_PRELOAD shim's log text. - -Reads `gndrm_shim.c`, rewrites every `LOG("", args...)` call site to decode -an XOR-encoded copy of the literal at runtime, and emits the encoded table plus -the `gndrm_str`/`gndrm_logfmt` support into the output file. The literal text is -gone from the compiled `.so` (`strings` finds the encoded bytes, not the text); -the gate and the "[gndrm-shim] " prefix are unchanged. - -Deterministic: identical input yields identical output. Run by -`tools/build-shim.sh`; the source stays the readable, canonical input. -""" -import re -import sys - -MAX_MSG = 512 -LOG_DEF = re.compile(r"#define LOG\(\.\.\.\).*?\n[^\n]*while \(0\)\n", re.S) - - -def match_paren(s, i): - d = 0 - n = len(s) - while i < n: - c = s[i] - if c == '"': - i += 1 - while i < n: - if s[i] == '\\': - i += 2 - continue - if s[i] == '"': - break - i += 1 - elif c in "([{": - d += 1 - elif c in ")]}": - d -= 1 - if d == 0: - return i + 1 - i += 1 - raise ValueError("unbalanced parens") - - -def split_top(s): - out, depth, i, start, n = [], 0, 0, 0, len(s) - while i < n: - c = s[i] - if c == '"': - i += 1 - while i < n: - if s[i] == '\\': - i += 2 - continue - if s[i] == '"': - break - i += 1 - elif c in "([{": - depth += 1 - elif c in ")]}": - depth -= 1 - elif c == "," and depth == 0: - out.append(s[start:i]) - start = i + 1 - i += 1 - out.append(s[start:]) - return out - - -def c_unescape(lit): - """Decode a single C string literal (with surrounding quotes) to bytes.""" - assert lit[0] == '"' and lit[-1] == '"' - body = lit[1:-1] - out = bytearray() - i = 0 - while i < len(body): - c = body[i] - if c != '\\': - out += c.encode() - i += 1 - continue - i += 1 - e = body[i] - simple = {'n': 10, 't': 9, 'r': 13, '\\': 92, '"': 34, "'": 39, - '0': 0, 'a': 7, 'b': 8, 'f': 12, 'v': 11} - if e in simple: - out.append(simple[e]) - i += 1 - elif e == 'x': - i += 1 - j = i - while j < len(body) and body[j] in "0123456789abcdefABCDEF": - j += 1 - out.append(int(body[i:j], 16) & 0xFF) - i = j - else: - raise ValueError(f"unsupported escape \\{e}") - return bytes(out) - - -def extract_literals(arg): - """Concatenate the decoded bytes of all C string literals in `arg`.""" - out = bytearray() - for m in re.finditer(r'"(?:[^"\\]|\\.)*"', arg): - out += c_unescape(m.group(0)) - return bytes(out) - - -def key_for(b): - h = 0x811C9DC5 - for x in b: - h ^= x - h = (h * 0x01000193) & 0xFFFFFFFF - return h & 0xFF - - -def main(): - src_path, out_path = sys.argv[1], sys.argv[2] - src = open(src_path).read() - - msgs = [] # (bytes) - repls = [] # (start, end, replacement) - - # LOG("", args...) → GNDRM_LOGM(id, args) / GNDRM_LOGM0(id) - for m in re.finditer(r"(?len; i++)", - " buf[i] = (char)(m->enc[i] ^ (unsigned char)(m->key + i));", - " buf[m->len] = 0;", - " return buf;", - "}", - # Two distinct buffers: a message and a `why`-style reference can be - # live at once (the LOG site decodes its own format while `why` still - # points at its decode), so sharing one buffer would clobber. - f"static const char *gndrm_str(unsigned id) {{", - f" static _Thread_local char buf[{MAX_MSG}];", - " return gndrm_decode(id, buf);", - "}", - f"static const char *gndrm_ref(unsigned id) {{", - f" static _Thread_local char buf2[{MAX_MSG}];", - " return gndrm_decode(id, buf2);", - "}", - "static void gndrm_logfmt(const char *fmt, ...) {", - " va_list ap;", - ' fputs("[gndrm-shim] ", stderr);', - " va_start(ap, fmt);", - " vfprintf(stderr, fmt, ap);", - " va_end(ap);", - "}", - "#define GNDRM_LOGM0(id) do { \\", - ' if (getenv("GNDRM_LOG_SHIM")) gndrm_logfmt(gndrm_str(id)); \\', - "} while (0)", - "#define GNDRM_LOGM(id, ...) do { \\", - ' if (getenv("GNDRM_LOG_SHIM")) gndrm_logfmt(gndrm_str(id), __VA_ARGS__); \\', - "} while (0)", - "/* --- end generated --- */", - ] - block = "\n".join(lines) + "\n" - - src, n = LOG_DEF.subn(block, src) - if n != 1: - raise SystemExit("obf-shim: LOG macro definition not found exactly once") - - open(out_path, "w").write(src) - print(f"obf-shim: {len(msgs)} messages obfuscated -> {out_path}") - - -if __name__ == "__main__": - main() From 9aa13649cb201534d6178513000c2cfd05d8e80a Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:38:38 +0800 Subject: [PATCH 2/3] ci: a PR gate that builds the workspace with warnings as errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo build --workspace --all-targets` under `RUSTFLAGS=-D warnings`, then `cargo clippy --workspace --all-targets -- -D warnings`. Both `--locked`. `--all-targets` is the part that earns its keep: it compiles the test and bench targets too, so a change that only breaks a test build fails the gate instead of failing at review. No artifacts are produced or uploaded — the job's status is the output. Host build only. `tools/build-android.sh` and `build-shim.sh android` need the NDK, the gamescope termux prefix (`GAMESCOPE_TERMUX_PREFIX`) and the export / undefined-symbol audits that read the cross build's output, which a hosted runner cannot stand up; the workflow header says so, so nobody reads a green run as covering the shipped artifacts. No `cargo fmt --check`: the tree is hand-formatted, and a fmt gate would fail every PR. Verified from a cold target directory, which is the closest local proxy for a first CI run: `cargo build` rc 0 with 0 warnings, `cargo clippy` rc 0, and actionlint 1.7.12 reports 0 parse errors and 0 errors. --- .github/workflows/build.yml | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/build.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..d3c78e7 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,48 @@ +name: build + +# PR gate: every change compiles with no warnings. +# +# Host build only. The Android artifacts (`tools/build-android.sh`, +# `build-shim.sh android`) need the NDK, the gamescope termux prefix and the +# export/undefined-symbol audits that read the cross build's output — that is a +# workstation step, not something this runner can stand up. What is checked here +# is the part CI can hold: the workspace builds for the host target, tests and +# benches included, with `-D warnings`, and clippy accepts every target. +# +# No formatting check on purpose: the tree is hand-formatted. +# +# No artifacts are produced or uploaded; the result is the job's status. + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: build-${{ github.ref }} + cancel-in-progress: true + +jobs: + host: + name: host build, no warnings + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - uses: Swatinem/rust-cache@v2 + + # `--all-targets` compiles the test and bench targets too, so a change + # that only breaks a test build fails here rather than at review. + - name: cargo build (workspace, all targets, warnings are errors) + env: + RUSTFLAGS: -D warnings + run: cargo build --workspace --all-targets --locked + + - name: cargo clippy (workspace, all targets, warnings are errors) + run: cargo clippy --workspace --all-targets --locked -- -D warnings From 49bcdb3df7269da44e2103f751ec4b2536d4da9d Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:43:17 +0800 Subject: [PATCH 3/3] ci: install the host libraries the clients link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first run failed at link time, not in the code: rust-lld: error: unable to find library -lvulkan rust-lld: error: unable to find library -lwayland-client error: could not compile `gn-utils` (bin "gn-device-probe" test) `gn-utils` (and `icd_shim/src/x11.rs`) carry `#[link]` attributes for the host's Vulkan, wayland and xcb, so `--all-targets` on a bare runner cannot link its binaries. The runner now installs `libvulkan-dev`, `libwayland-dev`, `libxcb1-dev`, `libxcb-dri3-dev`, `libxcb-present-dev` and `libxcb-sync-dev` before building — the same set a developer machine has to have. Verified in a clean `ubuntu:24.04` container with only those packages added, which is what the runner is: `cargo build --workspace --all-targets --locked` under `RUSTFLAGS=-D warnings` rc 0 with no warnings, and `cargo clippy --workspace --all-targets --locked -- -D warnings` rc 0, both with the current stable toolchain (1.99.1) rather than the local 1.98.0. actionlint reports 0 errors. --- .github/workflows/build.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d3c78e7..13d6d55 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -37,6 +37,17 @@ jobs: - uses: Swatinem/rust-cache@v2 + # The guest-side clients link the host's Vulkan, wayland and xcb: + # `utils/src/{vk,wlproto}.rs` and `icd_shim/src/x11.rs` carry the `#[link]` + # attributes, so a runner without the -dev packages fails at link time with + # `unable to find library -lvulkan` rather than in the code. + - name: system libraries the clients link + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends \ + libvulkan-dev libwayland-dev \ + libxcb1-dev libxcb-dri3-dev libxcb-present-dev libxcb-sync-dev + # `--all-targets` compiles the test and bench targets too, so a change # that only breaks a test build fails here rather than at review. - name: cargo build (workspace, all targets, warnings are errors)