use super::{ProfileGroup, Setting, SettingValue, Subsystem};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
const MAX_PROFILES_PER_FILE: usize = 20_000;
const MIN_STRING_LEN: usize = 4;
pub fn drs_exe_set() -> std::collections::BTreeSet<String> {
let mut set = std::collections::BTreeSet::new();
let Some(dir) = drs_dir() else { return set };
let Ok(entries) = std::fs::read_dir(&dir) else {
return set;
};
for entry in entries.flatten() {
let path = entry.path();
let Some(stem) = path.file_name().and_then(|n| n.to_str()) else {
continue;
};
if !stem.starts_with("nvdrsdb") || path.extension().and_then(|e| e.to_str()) != Some("bin")
{
continue;
}
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
for s in extract_utf16_strings(&bytes) {
let lower = s.trim().to_ascii_lowercase();
if lower.ends_with(".exe") && lower.len() > 4 {
set.insert(lower);
}
}
}
set
}
pub fn scan_drs_groups() -> Vec<ProfileGroup> {
let mut groups = Vec::new();
let Some(dir) = drs_dir() else { return groups };
let Ok(entries) = std::fs::read_dir(&dir) else {
return groups;
};
for entry in entries.flatten() {
let path = entry.path();
let Some(stem) = path.file_name().and_then(|n| n.to_str()) else {
continue;
};
if !stem.starts_with("nvdrsdb") || path.extension().and_then(|e| e.to_str()) != Some("bin")
{
continue;
}
if let Some(group) = scan_file(&path) {
groups.push(group);
}
}
groups
}
fn drs_dir() -> Option<PathBuf> {
let pd = std::env::var_os("PROGRAMDATA")?;
let dir = PathBuf::from(pd).join("NVIDIA Corporation").join("Drs");
if dir.is_dir() {
Some(dir)
} else {
None
}
}
fn scan_file(path: &Path) -> Option<ProfileGroup> {
let bytes = std::fs::read(path).ok()?;
let strings = extract_utf16_strings(&bytes);
let mut seen = BTreeSet::new();
let mut exes: Vec<String> = Vec::new();
let mut display_profiles: Vec<String> = Vec::new();
for s in &strings {
let s = s.trim();
if s.is_empty() {
continue;
}
let lower = s.to_ascii_lowercase();
if lower.ends_with(".exe") {
if seen.insert(lower.clone()) {
exes.push(s.to_string());
}
} else if looks_like_profile_name(s) && exes.is_empty() {
display_profiles.push(s.to_string());
}
}
let mut group = ProfileGroup::new(
Subsystem::Gpu,
"NVIDIA Driver Profile Database (DRS)",
path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("nvdrsdb")
.to_string(),
path.display().to_string(),
);
group.push(
Setting::info(
"file_size_bytes",
"DB File Size",
SettingValue::Uint(bytes.len() as u64),
)
.with_unit("bytes")
.with_source(path.display().to_string()),
);
group.push(
Setting::info(
"app_profile_count",
"Application Profiles Detected",
SettingValue::Uint(exes.len() as u64),
)
.with_description(
"Number of .exe references in the DRS database. Each typically \
corresponds to a per-application driver profile (NVIDIA-shipped \
or user-customized via NVIDIA Control Panel / NVPI).",
)
.with_source(path.display().to_string()),
);
for (i, exe) in exes.iter().take(MAX_PROFILES_PER_FILE).enumerate() {
group.push(
Setting::info(
format!("app_{:04}", i),
exe.clone(),
SettingValue::Text("(profile present)".to_string()),
)
.with_source("DRS binary scan"),
);
}
if exes.len() > MAX_PROFILES_PER_FILE {
group.note(format!(
"{} additional application profiles in DB not shown (cap = {}).",
exes.len() - MAX_PROFILES_PER_FILE,
MAX_PROFILES_PER_FILE
));
}
group.note(
"DRS scan extracts .exe references via UTF-16 string search. The \
per-setting DWORD/string values inside each profile (DLSS toggle, \
V-Sync, etc.) require NVAPI's NvAPI_DRS_* functions to decode \
precisely and are not exposed here.",
);
if path.metadata().ok().map(|m| m.len()).unwrap_or(0) > 100 * 1024 {
group.note(
"If this list looks incomplete, the NVIDIA driver may be writing \
updates to nvdrsdb1.bin instead of nvdrsdb0.bin (or vice versa) — \
both are scanned automatically.",
);
}
Some(group)
}
fn looks_like_profile_name(s: &str) -> bool {
let len = s.chars().count();
if !(4..=80).contains(&len) {
return false;
}
let has_alpha = s.chars().any(|c| c.is_ascii_alphabetic());
let has_space = s.contains(' ');
has_alpha && has_space && !s.contains("://") && !s.contains('\\')
}
fn extract_utf16_strings(bytes: &[u8]) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut i = 0;
while i + 1 < bytes.len() {
let lo = bytes[i];
let hi = bytes[i + 1];
if hi == 0 && (0x20..0x7f).contains(&lo) {
cur.push(lo as char);
} else {
if cur.chars().count() >= MIN_STRING_LEN {
out.push(std::mem::take(&mut cur));
} else {
cur.clear();
}
}
i += 2;
}
if cur.chars().count() >= MIN_STRING_LEN {
out.push(cur);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utf16_string_extraction() {
let bytes = [
b'H', 0, b'i', 0, b'!', 0, 0xFF, 0xFF, b'H', 0, b'e', 0, b'l', 0, b'l', 0, b'o', 0, 0, 0,
];
let s = extract_utf16_strings(&bytes);
assert_eq!(s, vec!["Hello".to_string()]);
}
#[test]
fn profile_name_heuristic() {
assert!(looks_like_profile_name("Microsoft Flight Simulator"));
assert!(looks_like_profile_name("Cyberpunk 2077"));
assert!(!looks_like_profile_name("game.exe"));
assert!(!looks_like_profile_name("C:\\foo"));
assert!(!looks_like_profile_name("abc"));
}
#[test]
fn scan_smoke() {
let _ = scan_drs_groups();
}
}