From 3ac81705fd367b08995616025ed74bce59a078ee Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:03:54 +0000 Subject: [PATCH 01/29] Publish: develop 211fdef to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .../platform/windows/src/bin/chrome-builds.rs | 41 +- rivet/platform/windows/src/chrome_build.rs | 21 + rivet/platform/windows/src/lib.rs | 1 + rivet/platform/windows/src/row_port.rs | 592 +++++++- rivet/platform/windows/src/row_recipe.rs | 60 +- rivet/platform/windows/src/row_resolve.rs | 1278 +++++++++++++++++ 6 files changed, 1908 insertions(+), 85 deletions(-) create mode 100644 rivet/platform/windows/src/row_resolve.rs diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index 252fa64..f3fb64b 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -262,14 +262,22 @@ fn find( ) -> Result { let prior = json_file(prior_path)?; let stored = prior["fingerprints"].as_object(); - let (prints, prior_starts) = match (stored, old_module) { - (Some(stored), "-") => (stored.clone(), std::collections::BTreeSet::new()), - (None, "-") => { + let prior_bytes = match old_module { + "-" => None, + path => Some(read(Path::new(path))?), + }; + let prior_pe = match &prior_bytes { + Some(bytes) => { + Some(PeFile::parse(bytes).ok_or("the prior module is not a 64-bit PE image")?) + } + None => None, + }; + let prints = match (stored, &prior_pe) { + (Some(stored), None) => stored.clone(), + (None, None) => { return Err("the prior row has no fingerprints, and no prior module was given to read them from".into()); } - _ => { - let bytes = read(Path::new(old_module))?; - let pe = PeFile::parse(&bytes).ok_or("the prior module is not a 64-bit PE image")?; + (_, Some(pe)) => { // Fingerprints read from another build would find the wrong functions. let start = prior["frame"]["hwnd_for_view"] .as_u64() @@ -282,10 +290,10 @@ fn find( if pe.read(start, prologue.len()) == Some(prologue.as_slice()) => {} _ => return Err("the prior module is not the build of the prior row".into()), } - let prints = match stored { + match stored { Some(stored) => stored.clone(), None => { - let (prints, missing) = row_port::fingerprints_of(&prior, &pe); + let (prints, missing) = row_port::fingerprints_of(&prior, pe); if !missing.is_empty() { println!( "the prior build gives no fingerprint for {}", @@ -294,11 +302,15 @@ fn find( } prints } - }; - // A fingerprint taken at a function start counts only function starts of the new build. - (prints, pe.function_starts()) + } } }; + // A fingerprint taken at a function start counts only function starts of the new build, and + // what fingerprints leave open is looked for by reading the prior build next to the new one. + let prior_starts = prior_pe + .as_ref() + .map(PeFile::function_starts) + .unwrap_or_default(); let mut old = Vec::new(); symbols::publics(old_pdb, &mut |address, name| { old.push((address, name.to_owned())) @@ -313,7 +325,7 @@ fn find( let bytes = read(module)?; let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; let (mut row, mut report) = - row_port::find_candidate(&prior, &prints, &prior_starts, version, &pe); + row_port::find_candidate(&prior, &prints, prior_pe.as_ref(), version, &pe); // No symbols name `screen_origin` here: a prior row without it gives a row without it. row_port::seed_screen_origin(&mut row, &[], &pe, &mut report); report.review.extend(row_port::hand_only_review(&prior)); @@ -331,11 +343,14 @@ fn find( pe.function_starts().len() ); println!( - "{} {} without its PDB: {} of {} addresses found by fingerprint, {} for review", + "{} {} without its PDB: {} of {} addresses found by fingerprint, {} settled by two methods, {} values read, {} carried, {} for review", report.browser, report.version, report.fingerprinted.len(), report.addresses, + report.settled.len(), + report.derived.len(), + report.carried.len(), report.review.len() ); Ok(report.review.is_empty()) diff --git a/rivet/platform/windows/src/chrome_build.rs b/rivet/platform/windows/src/chrome_build.rs index d4787e8..7328df3 100644 --- a/rivet/platform/windows/src/chrome_build.rs +++ b/rivet/platform/windows/src/chrome_build.rs @@ -235,6 +235,27 @@ impl<'a> PeFile<'a> { starts } + /// Every part of a function the exception table lists, as start and end. The linker moves cold + /// parts out of a function, and each such part has its own entry. + pub fn function_ranges(&self) -> std::collections::BTreeMap { + let (directory, size) = self.exception_directory; + let mut ranges = std::collections::BTreeMap::new(); + let Some(table) = self.offset(directory).filter(|_| directory != 0) else { + return ranges; + }; + for index in 0..(size / 12) as usize { + let entry = table + index * 12; + match (u32_at(self.bytes, entry), u32_at(self.bytes, entry + 4)) { + (Some(start), Some(end)) if end > start => { + ranges.insert(start, end); + } + (Some(_), Some(_)) => {} + _ => break, + } + } + ranges + } + /// Finds the slot of `function` in the vtable at `vtable`, scanning a bounded number of slots. pub fn vtable_slot(&self, vtable: u32, function: u32) -> Option { (0..512u32).find(|slot| self.pointer_rva(vtable + slot * 8) == Some(function)) diff --git a/rivet/platform/windows/src/lib.rs b/rivet/platform/windows/src/lib.rs index 27f8313..88c1962 100644 --- a/rivet/platform/windows/src/lib.rs +++ b/rivet/platform/windows/src/lib.rs @@ -11,6 +11,7 @@ pub mod focus; pub mod hold; pub mod row_port; pub mod row_recipe; +pub mod row_resolve; pub mod row_watch; pub mod signed_table; pub mod start; diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 06224de..79487ee 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -19,6 +19,7 @@ use serde::Serialize; use serde_json::{json, Value}; use crate::chrome_build::{hex, PeFile}; +use crate::row_resolve; /// The lowest value taken for an address. Offsets and slots lie below it. const LOWEST_ADDRESS: u64 = 0x10_0000; @@ -68,6 +69,8 @@ pub struct PortReport { pub made_without_pdb: bool, /// Addresses a fingerprint found in exactly one place of the new build. pub fingerprinted: Vec, + /// Values that are Rivet's settings rather than facts about the build, kept from the prior row. + pub settings: Vec, } fn is_address(value: u64) -> bool { @@ -163,14 +166,48 @@ fn candidates( votes } -/// A function's first instructions, read as far as this needs them. +/// A function's instructions, read as far as this needs them. pub mod x64 { - /// One decoded instruction: its length and where its RIP-relative displacement or relative - /// branch target is, if it has one. + /// One decoded instruction: its length, where its RIP-relative displacement or relative branch + /// target is, where a displacement from a register is, as in `[rcx + 0x558]`, and where its + /// immediate value is. Each place is `(offset, size)` within the instruction. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct Instruction { pub length: usize, pub relative: Option<(usize, usize)>, + pub displacement: Option<(usize, usize)>, + pub immediate: Option<(usize, usize)>, + } + + impl Instruction { + fn plain(length: usize) -> Self { + Self { + length, + relative: None, + displacement: None, + immediate: None, + } + } + + /// An instruction whose last `size` bytes, from `at`, are an immediate value. + fn with_immediate(at: usize, size: usize) -> Self { + Self { + length: at + size, + relative: None, + displacement: None, + immediate: Some((at, size)), + } + } + + /// A branch whose last `size` bytes, from `at`, are the distance to its target. + fn branch(at: usize, size: usize) -> Self { + Self { + length: at + size, + relative: Some((at, size)), + displacement: None, + immediate: None, + } + } } fn modrm(bytes: &[u8], at: usize, immediate: usize) -> Option { @@ -178,10 +215,12 @@ pub mod x64 { let (mode, rm) = (byte >> 6, byte & 7); let mut length = at + 1; let mut relative = None; + let mut displacement = None; if mode != 3 && rm == 4 { let sib = *bytes.get(length)?; length += 1; if mode == 0 && sib & 7 == 5 { + displacement = Some((length, 4)); length += 4; } } @@ -190,19 +229,39 @@ pub mod x64 { relative = Some((length, 4)); length += 4; } - 1 => length += 1, - 2 => length += 4, + 1 => { + displacement = Some((length, 1)); + length += 1; + } + 2 => { + displacement = Some((length, 4)); + length += 4; + } _ => {} } Some(Instruction { length: length + immediate, relative, + displacement, + immediate: (immediate > 0).then_some((length, immediate)), }) } /// Decodes the instruction at the start of `bytes`, or `None` for one this does not know. The /// list covers what function starts are made of, and anything else goes to a person. pub fn decode(bytes: &[u8]) -> Option { + decode_with(bytes, false) + } + + /// Decodes as `decode` does, and also the instructions met inside a function body: lock and + /// segment prefixes, string and x87 instructions, VEX encoded vector instructions and more of + /// the two and three byte opcodes. It reads bodies to follow calls and operands, and never + /// judges a guard, so what a hook may copy stays as `decode` says. + pub fn decode_body(bytes: &[u8]) -> Option { + decode_with(bytes, true) + } + + fn decode_with(bytes: &[u8], body: bool) -> Option { let mut at = 0; let mut wide_operand = false; let mut rex_w = false; @@ -210,6 +269,7 @@ pub mod x64 { match *bytes.get(at)? { 0x66 => wide_operand = true, 0xF2 | 0xF3 => {} + 0xF0 | 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 if body => {} _ => break, } at += 1; @@ -221,15 +281,9 @@ pub mod x64 { let opcode = *bytes.get(at)?; at += 1; let word = if wide_operand { 2 } else { 4 }; - let plain = |length| { - Some(Instruction { - length, - relative: None, - }) - }; match opcode { - 0x50..=0x5F | 0x90 | 0xC3 | 0xCC | 0x99 => plain(at), - 0x98 => plain(at), + 0x50..=0x5F | 0x90 | 0xC3 | 0xCC | 0x99 => Some(Instruction::plain(at)), + 0x98 => Some(Instruction::plain(at)), 0x00..=0x03 | 0x08..=0x0B | 0x10..=0x13 @@ -246,10 +300,15 @@ pub mod x64 { | 0xFE | 0xFF => modrm(bytes, at, 0), 0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x34 | 0x3C | 0x6A | 0xA8 | 0xB0..=0xB7 => { - plain(at + 1) + Some(Instruction::with_immediate(at, 1)) + } + 0x05 | 0x0D | 0x15 | 0x1D | 0x25 | 0x2D | 0x35 | 0x3D | 0x68 | 0xA9 => { + Some(Instruction::with_immediate(at, word)) } - 0x05 | 0x0D | 0x15 | 0x1D | 0x25 | 0x2D | 0x35 | 0x3D | 0x68 | 0xA9 => plain(at + word), - 0xB8..=0xBF => plain(at + if rex_w { 8 } else { word }), + 0xB8..=0xBF => Some(Instruction::with_immediate( + at, + if rex_w { 8 } else { word }, + )), 0x80 | 0x83 | 0xC0 | 0xC1 | 0xC6 | 0x6B => modrm(bytes, at, 1), 0x81 | 0xC7 | 0x69 => modrm(bytes, at, word), 0xF6 => { @@ -264,22 +323,13 @@ pub mod x64 { }; modrm(bytes, at, immediate) } - 0x70..=0x7F | 0xEB => Some(Instruction { - length: at + 1, - relative: Some((at, 1)), - }), - 0xE8 | 0xE9 => Some(Instruction { - length: at + 4, - relative: Some((at, 4)), - }), + 0x70..=0x7F | 0xEB => Some(Instruction::branch(at, 1)), + 0xE8 | 0xE9 => Some(Instruction::branch(at, 4)), 0x0F => { let second = *bytes.get(at)?; at += 1; match second { - 0x80..=0x8F => Some(Instruction { - length: at + 4, - relative: Some((at, 4)), - }), + 0x80..=0x8F => Some(Instruction::branch(at, 4)), 0x10..=0x17 | 0x1E | 0x1F @@ -295,9 +345,81 @@ pub mod x64 { | 0xBF | 0xD6 | 0xEF => modrm(bytes, at, 0), + _ if body => body_two_byte(bytes, at, second), _ => None, } } + _ if body => body_one_byte(bytes, at, opcode), + _ => None, + } + } + + /// One byte opcodes that only a function body holds. `at` is just past the opcode. + fn body_one_byte(bytes: &[u8], at: usize, opcode: u8) -> Option { + match opcode { + 0x91..=0x97 | 0x9C..=0x9F | 0xA4..=0xA7 | 0xAA..=0xAF | 0xC9 | 0xF4 | 0xF5 => { + Some(Instruction::plain(at)) + } + 0xF8..=0xFD => Some(Instruction::plain(at)), + 0xC2 => Some(Instruction::with_immediate(at, 2)), + 0xCD => Some(Instruction::with_immediate(at, 1)), + 0xD8..=0xDF => modrm(bytes, at, 0), + 0xE0..=0xE3 => Some(Instruction::branch(at, 1)), + // Two byte VEX: one payload byte, then an opcode of the 0F map. + 0xC5 => { + let opcode = *bytes.get(at + 1)?; + modrm(bytes, at + 2, vex_immediate(1, opcode)) + } + // Three byte VEX: the map in the first payload byte, then one more payload byte. + 0xC4 => { + let map = bytes.get(at)? & 0x1F; + let opcode = *bytes.get(at + 2)?; + modrm(bytes, at + 3, vex_immediate(map, opcode)) + } + _ => None, + } + } + + /// Whether a VEX instruction of `map` ends in an immediate byte. + fn vex_immediate(map: u8, opcode: u8) -> usize { + match map { + 3 => 1, + 1 => usize::from(matches!(opcode, 0x70..=0x73 | 0xC2 | 0xC4..=0xC6)), + _ => 0, + } + } + + /// Two byte opcodes that only a function body holds. `at` is just past the second byte. + fn body_two_byte(bytes: &[u8], at: usize, second: u8) -> Option { + match second { + 0x0B | 0x31 | 0x77 | 0xA2 | 0xC8..=0xCF => Some(Instruction::plain(at)), + 0x0D + | 0x18..=0x1D + | 0x74..=0x76 + | 0x7C + | 0x7D + | 0xA3 + | 0xA5 + | 0xAB + | 0xAD + | 0xAE + | 0xB0 + | 0xB1 + | 0xB3 + | 0xB8 + | 0xBB + | 0xBC + | 0xBD + | 0xC0 + | 0xC1 + | 0xC3 + | 0xC7 + | 0xD0..=0xD5 + | 0xD7..=0xEE + | 0xF0..=0xFE => modrm(bytes, at, 0), + 0x70..=0x73 | 0xA4 | 0xAC | 0xBA | 0xC2 | 0xC4..=0xC6 => modrm(bytes, at, 1), + 0x38 => modrm(bytes, at + 1, 0), + 0x3A => modrm(bytes, at + 1, 1), _ => None, } } @@ -354,6 +476,23 @@ pub mod x64 { } Some(false) } + + /// An instruction's bytes with its relative value, displacement and immediate cleared: what + /// stays the same when code moves and members, slots and constants change. + pub fn skeleton(bytes: &[u8], instruction: &Instruction) -> Vec { + let mut out = bytes[..instruction.length.min(bytes.len())].to_vec(); + let fields = [ + instruction.relative, + instruction.displacement, + instruction.immediate, + ]; + for (offset, size) in fields.into_iter().flatten() { + for index in offset..(offset + size).min(out.len()) { + out[index] = 0; + } + } + out + } } /// A byte field with no address field of the same name, and where it was read from. @@ -503,7 +642,7 @@ fn settle(target: u32, choices: &[(u32, usize)], build: &Value, pe: &PeFile) -> } /// The bytes of a function short enough to read to its end: its first `ret` with no branch before. -fn whole_function(pe: &PeFile, address: u32) -> Option> { +pub(crate) fn whole_function(pe: &PeFile, address: u32) -> Option> { let bytes = pe.read(address, 48)?; let mut at = 0; while at < 32 { @@ -842,7 +981,7 @@ pub fn port_row( named: &BTreeMap)>, new: &NewBuild, ) -> (Value, PortReport) { - let (row, mut report) = begin_row(prior, new.version); + let (row, mut report) = begin_row(prior, new.version, true); let mut moved: BTreeMap = BTreeMap::new(); let targets = addresses_of(&row); report.addresses = targets.len(); @@ -850,8 +989,10 @@ pub fn port_row( finish_row(row, &moved, new.pe, report) } -/// A copy of the prior row with the new version, and frame addresses in the `0x` form. -fn begin_row(prior: &Value, version: &str) -> (Value, PortReport) { +/// A copy of the prior row with the new version, and frame addresses in the `0x` form. `carries` +/// says the values with no recipe stay as the prior row has them, so a new milestone stops the +/// row; without it they are read from the new build later, each with its own review line. +fn begin_row(prior: &Value, version: &str, carries: bool) -> (Value, PortReport) { let mut row = prior.clone(); if let Some(object) = row.as_object_mut() { // The mark tells how the prior row was made, not this one. @@ -880,7 +1021,8 @@ fn begin_row(prior: &Value, version: &str) -> (Value, PortReport) { .push(format!("{} is not a four part version", version)); } report.carried = crate::row_recipe::without_recipe(&prior["build"]); - if prior_version.split('.').next() != version.split('.').next() { + report.settings = crate::row_recipe::settings(&prior["build"]); + if carries && prior_version.split('.').next() != version.split('.').next() { report.review.push(format!( "the milestone changed from {prior_version} to {version}: {} values have no recipe and were carried over unchecked: {}", report.carried.len(), @@ -1045,7 +1187,7 @@ fn fingerprint_targets(row: &Value) -> BTreeSet { } /// The start of a function with its displacements cleared, cut at an instruction end. -fn code_print(pe: &PeFile, address: u32) -> Option> { +pub(crate) fn code_print(pe: &PeFile, address: u32) -> Option> { if !pe.is_code(address) { return None; } @@ -1116,7 +1258,7 @@ pub fn fingerprints_of(row: &Value, pe: &PeFile) -> (serde_json::Map>) -> BTreeMap> { +pub(crate) fn find_prints(pe: &PeFile, prints: &BTreeMap>) -> BTreeMap> { let mut by_anchor: HashMap<[u8; ANCHOR], Vec> = HashMap::new(); let mut first = [false; 256]; for (target, shape) in prints { @@ -1152,7 +1294,7 @@ fn find_prints(pe: &PeFile, prints: &BTreeMap>) -> BTreeMap Vec { +pub(crate) fn find_table(pe: &PeFile, slot: u32, function: u32) -> Vec { let value = (pe.image_base() + u64::from(function)).to_le_bytes(); let mut found = Vec::new(); for (base, bytes, _) in pe.sections() { @@ -1176,7 +1318,7 @@ pub fn find_row(prior: &Value, version: &str, pe: &PeFile) -> Result Result, - prior_starts: &BTreeSet, + prior_pe: Option<&PeFile>, version: &str, pe: &PeFile, ) -> (Value, PortReport) { - let (row, mut report) = begin_row(prior, version); + let (row, mut report) = begin_row(prior, version, prior_pe.is_none()); report.made_without_pdb = true; + let prior_starts = prior_pe.map(PeFile::function_starts).unwrap_or_default(); let targets = fingerprint_targets(prior); report.addresses = targets.len(); let mut functions = BTreeMap::new(); let mut tables = BTreeMap::new(); + // Each address its fingerprint did not pin down, with its review line, waits for the methods + // that read the prior build next to the new one. + let mut wanted: BTreeMap = BTreeMap::new(); + let want = |kind, candidates: Option>| row_resolve::Wanted { kind, candidates }; for target in &targets { match stored.get(&format!("{target:#x}")) { Some(Value::String(text)) => match hex(text).filter(|shape| shape.len() >= ANCHOR) { @@ -1229,7 +1379,20 @@ pub fn find_candidate( .push(format!("{target:#x}: unreadable table fingerprint")), } } - _ => report.review.push(format!("{target:#x}: no fingerprint")), + _ => { + let line = format!("{target:#x}: no fingerprint"); + match prior_pe { + Some(prior_pe) => { + let kind = if prior_pe.is_code(*target) { + row_resolve::Kind::Function + } else { + row_resolve::Kind::Table + }; + wanted.insert(*target, (line, want(kind, None))); + } + None => report.review.push(line), + } + } } } let found = find_prints(pe, &functions); @@ -1251,6 +1414,7 @@ pub fn find_candidate( || (new_starts.contains(place) && (target % 16 != 0 || *place % 16 == 0)) }) .collect(); + let function = row_resolve::Kind::Function; match places.as_slice() { [only] => { moved.insert(*target, *only); @@ -1264,21 +1428,28 @@ pub fn find_candidate( .fingerprinted .push(format!("{target:#x} -> {only:#x}{checked}")); } - [] if !all.is_empty() => report.review.push(format!( - "{target:#x} matches no function start, of {} places", - all.len() - )), - [] => report.review.push(format!("{target:#x} matches no place")), - many => report - .review - .push(format!("{target:#x} matches {} places", many.len())), + [] if !all.is_empty() => { + let line = format!( + "{target:#x} matches no function start, of {} places", + all.len() + ); + wanted.insert(*target, (line, want(function, None))); + } + [] => { + let line = format!("{target:#x} matches no place"); + wanted.insert(*target, (line, want(function, None))); + } + many => { + let line = format!("{target:#x} matches {} places", many.len()); + wanted.insert(*target, (line, want(function, Some(many.to_vec())))); + } } } for (target, (slot, holds)) in &tables { + let table = row_resolve::Kind::Table; let Some(function) = moved.get(holds).copied() else { - report.review.push(format!( - "{target:#x}: the function in slot {slot} was not found" - )); + let line = format!("{target:#x}: the function in slot {slot} was not found"); + wanted.insert(*target, (line, want(table, None))); continue; }; match find_table(pe, *slot, function).as_slice() { @@ -1288,26 +1459,184 @@ pub fn find_candidate( .fingerprinted .push(format!("{target:#x} -> {only:#x}")); } - many => report.review.push(format!( - "{target:#x}: {} tables hold {function:#x} in slot {slot}", - many.len() - )), + many => { + let line = format!( + "{target:#x}: {} tables hold {function:#x} in slot {slot}", + many.len() + ); + let candidates = (!many.is_empty()).then(|| many.to_vec()); + wanted.insert(*target, (line, want(table, candidates))); + } } } + let mut followed = BTreeMap::new(); + match prior_pe { + Some(prior_pe) if !wanted.is_empty() => { + let table_targets: BTreeSet = tables + .keys() + .copied() + .chain( + wanted + .iter() + .filter(|(_, (_, want))| want.kind == row_resolve::Kind::Table) + .map(|(target, _)| *target), + ) + .collect(); + let asked: BTreeMap = wanted + .iter() + .map(|(target, (_, want))| (*target, want.clone())) + .collect(); + let resolution = row_resolve::resolve(prior_pe, pe, &moved, &asked, &table_targets); + for (target, (line, _)) in &wanted { + match resolution.places.get(target) { + Some(place) => { + moved.insert(*target, *place); + } + None => { + let reason = resolution + .reasons + .get(target) + .map_or("no method was run", String::as_str); + report.review.push(format!("{line}; not settled: {reason}")); + } + } + } + report.settled.extend(resolution.settled); + followed = resolution.followed; + } + _ => report + .review + .extend(wanted.into_values().map(|(line, _)| line)), + } let places: BTreeSet = moved.values().copied().collect(); if places.len() != moved.len() { report .review .push("two addresses found the same place".to_owned()); } - let (mut row, report) = finish_row(row, &moved, pe, report); + let (mut row, mut report) = finish_row(row, &moved, pe, report); if let Some(object) = row.as_object_mut() { // They describe the prior build, so they would mislead in this row. object.remove("fingerprints"); } + if let Some(prior_pe) = prior_pe { + read_carried(prior, &mut row, &moved, &followed, prior_pe, pe, &mut report); + } (row, report) } +/// The value at a path such as `layout.frame_ids[2]` or `toolbar.dev.colours[3][0]`. +fn value_at<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { + let mut current = value; + for part in path.split('.') { + let (key, indexes) = part.split_at(part.find('[').unwrap_or(part.len())); + current = current.get(key)?; + for index in indexes.split(']').filter(|index| !index.is_empty()) { + current = current.get(index.trim_start_matches('[').parse::().ok()?)?; + } + } + Some(current) +} + +fn value_at_mut<'a>(value: &'a mut Value, path: &str) -> Option<&'a mut Value> { + let mut current = value; + for part in path.split('.') { + let (key, indexes) = part.split_at(part.find('[').unwrap_or(part.len())); + current = current.get_mut(key)?; + for index in indexes.split(']').filter(|index| !index.is_empty()) { + current = current.get_mut(index.trim_start_matches('[').parse::().ok()?)?; + } + } + Some(current) +} + +/// Reads each value the recipes leave, a member offset, slot, size or id, from the instructions +/// that use it in the prior build's functions and the same instructions in the new build. A value +/// that cannot be read keeps a review line with the reason and stays listed as carried, so the row +/// is never published with a value of the prior build. +fn read_carried( + prior: &Value, + row: &mut Value, + moved: &BTreeMap, + followed: &BTreeMap, + prior_pe: &PeFile, + pe: &PeFile, + report: &mut PortReport, +) { + let mut values = Vec::new(); + let mut unreadable = Vec::new(); + for path in std::mem::take(&mut report.carried) { + let items: Vec<(String, &Value)> = match value_at(&prior["build"], &path) { + Some(Value::Array(items)) => items + .iter() + .enumerate() + .map(|(index, item)| (format!("{path}[{index}]"), item)) + .collect(), + Some(item) => vec![(path.clone(), item)], + None => vec![], + }; + if items.is_empty() { + unreadable.push(path); + } + for (path, item) in items { + match crate::row_recipe::number(item) { + Some(value) => values.push((path, value)), + None => unreadable.push(path), + } + } + } + // Each part of the row reads its values from its own functions. + let mut sections: BTreeMap> = BTreeMap::new(); + for (section, part) in prior["build"].as_object().into_iter().flatten() { + let mut part = part.clone(); + let mut pairs = Vec::new(); + walk_addresses("", &mut part, &mut |_, value| { + if let Some(address) = read_address(value).filter(|value| is_address(*value)) { + let address = address as u32; + if let Some(place) = moved.get(&address).filter(|_| prior_pe.is_code(address)) { + pairs.push((address, *place)); + } + } + }); + pairs.sort_unstable(); + pairs.dedup(); + if !pairs.is_empty() { + sections.insert(section.clone(), pairs); + } + } + for reading in row_resolve::read_values(prior_pe, pe, §ions, followed, &values) { + match reading.value { + Ok((value, how)) => { + if let Some(place) = value_at_mut(&mut row["build"], &reading.path) { + *place = if place.is_string() { + write_address(value) + } else { + json!(value) + }; + } + report.derived.push(if value == reading.prior { + format!("{}: {value:#x}, {how}", reading.path) + } else { + format!("{}: {:#x} -> {value:#x}, {how}", reading.path, reading.prior) + }); + } + Err(reason) => { + report.review.push(format!( + "{} was not read from the new build: {reason}", + reading.path + )); + report.carried.push(reading.path); + } + } + } + for path in unreadable { + report + .review + .push(format!("{path} is not a number this generator can read")); + report.carried.push(path); + } +} + /// The key of a row made without its build's symbols. It holds what the row job needs to make the /// row again from the symbols once they are published, and to compare the two. The runtime reads /// only `frame` and `build`, so the mark changes nothing in a browser. @@ -1974,6 +2303,33 @@ mod tests { assert_eq!(x64::shape(&[0x56, 0xCF]), None); } + #[test] + fn nfr6_the_operands_of_a_body_instruction_are_located() { + // mov rax, [rcx + 0x558]: a displacement of four bytes from the third byte. + let load = x64::decode(&[0x48, 0x8B, 0x81, 0x58, 0x05, 0x00, 0x00]).unwrap(); + assert_eq!(load.displacement, Some((3, 4))); + assert_eq!(load.immediate, None); + // call [rax + 0x2b8]: a table slot read through its displacement. + let call = x64::decode(&[0xFF, 0x90, 0xB8, 0x02, 0x00, 0x00]).unwrap(); + assert_eq!(call.displacement, Some((2, 4))); + // mov edx, 0x9c45, and cmp byte [rcx + 0x30], 1. + let id = x64::decode(&[0xBA, 0x45, 0x9C, 0x00, 0x00]).unwrap(); + assert_eq!(id.immediate, Some((1, 4))); + let compare = x64::decode(&[0x80, 0x79, 0x30, 0x01]).unwrap(); + assert_eq!(compare.displacement, Some((2, 1))); + assert_eq!(compare.immediate, Some((3, 1))); + // lock cmpxchg and a VEX move decode only as body instructions. + let lock = [0xF0, 0x48, 0x0F, 0xB1, 0x51, 0x08]; + assert_eq!(x64::decode(&lock), None); + assert_eq!(x64::decode_body(&lock).unwrap().displacement, Some((5, 1))); + let vex = [0xC5, 0xF8, 0x10, 0x41, 0x10]; + assert_eq!(x64::decode_body(&vex).unwrap().length, 5); + assert_eq!( + x64::skeleton(&[0x48, 0x8B, 0x81, 0x58, 0x05, 0x00, 0x00], &load), + [0x48, 0x8B, 0x81, 0, 0, 0, 0] + ); + } + /// A verified row whose functions sit at 0x101000 in its module. fn verified_row() -> Value { json!({ @@ -2125,15 +2481,21 @@ mod tests { ) -> (Value, PortReport) { let bytes = module(&code_refs(code)); let pe = PeFile::parse(&bytes).unwrap(); - find_candidate(&verified_row(), prints, &BTreeSet::new(), version, &pe) + find_candidate(&verified_row(), prints, None, version, &pe) } /// `module` with an exception table at 0x10f000 that lists `starts`. fn with_starts(code: &[(u32, Vec)], starts: &[u32]) -> Vec { + let ranges: Vec<(u32, u32)> = starts.iter().map(|start| (*start, start + 0x20)).collect(); + with_ranges(code, &ranges) + } + + /// `module` with an exception table at 0x10f000 that lists each `(start, end)`. + fn with_ranges(code: &[(u32, Vec)], ranges: &[(u32, u32)]) -> Vec { let mut table = vec![]; - for start in starts { + for (start, end) in ranges { table.extend_from_slice(&start.to_le_bytes()); - table.extend_from_slice(&(start + 0x20).to_le_bytes()); + table.extend_from_slice(&end.to_le_bytes()); table.extend_from_slice(&0u32.to_le_bytes()); } let mut code = code.to_vec(); @@ -2142,10 +2504,91 @@ mod tests { let directory = 0x98 + 112 + 24; bytes[directory..directory + 4].copy_from_slice(&0x10f000u32.to_le_bytes()); bytes[directory + 4..directory + 8] - .copy_from_slice(&(12 * starts.len() as u32).to_le_bytes()); + .copy_from_slice(&(12 * ranges.len() as u32).to_le_bytes()); + bytes + } + + /// The verified row's paint function, which reads `view_layer` with `loads` past the bytes its + /// fingerprint holds. + fn paint_reading(loads: &str) -> Vec { + let mut bytes = hex("4157415641554154565755534881eca0000000").unwrap(); + bytes.resize(32, 0x90); + bytes.extend(hex(loads).unwrap()); + bytes.push(0xC3); bytes } + /// A candidate row for a build whose paint function reads `view_layer` with `new_loads`, made + /// from the verified row and its build, whose paint function reads it with `prior_loads`. + fn read_view_layer(prior_loads: &str, new_loads: &str) -> (Value, PortReport) { + let ranges = |shift: u32, paint: usize| { + vec![ + (0x101100 + shift, 0x101120 + shift), + (0x101200 + shift, 0x101220 + shift), + (0x101300 + shift, 0x101300 + shift + paint as u32), + ] + }; + let mut old = shifted_code(0, 0x10); + old[3].1 = paint_reading(prior_loads); + let prior_bytes = with_ranges(&old, &ranges(0, old[3].1.len())); + let prior_pe = PeFile::parse(&prior_bytes).unwrap(); + let (prints, missing) = fingerprints_of(&verified_row(), &prior_pe); + assert!(missing.is_empty(), "{missing:?}"); + let mut new = shifted_code(0x2000, 0x44); + new[3].1 = paint_reading(new_loads); + let bytes = with_ranges(&new, &ranges(0x2000, new[3].1.len())); + let pe = PeFile::parse(&bytes).unwrap(); + find_candidate(&verified_row(), &prints, Some(&prior_pe), "1.0.0.3", &pe) + } + + #[test] + fn nfr6_a_carried_value_is_read_from_the_instructions_that_use_it() { + // mov rax, [rcx + 0x20]; mov rdx, [rcx + 0x20], and the new build moved the member to 0x28. + let (row, report) = + read_view_layer("488b8120000000488b9120000000", "488b8128000000488b9128000000"); + assert!(report.review.is_empty(), "{:?}", report.review); + assert_eq!(row["build"]["toolbar"]["view_layer"], "0x28"); + assert!(report.carried.is_empty(), "{:?}", report.carried); + assert_eq!( + report.derived, + ["toolbar.view_layer: 0x20 -> 0x28, read at 2 uses in 1 of its functions"] + ); + } + + #[test] + fn nfr6_a_value_no_instruction_gives_stops_the_row() { + // The new build reads the member with a short displacement: not the same instruction. + let (_, report) = read_view_layer("488b8120000000488b9120000000", "488b4128488b5128"); + assert_eq!(report.carried, ["toolbar.view_layer"]); + assert!(report.derived.is_empty(), "{:?}", report.derived); + assert!( + report.review.iter().any(|line| line + .starts_with("toolbar.view_layer was not read from the new build: its 2 uses")), + "{:?}", + report.review + ); + // One use alone is not read either, and neither are uses that disagree. + let (_, report) = read_view_layer("488b8120000000", "488b8128000000"); + assert!( + report + .review + .iter() + .any(|line| line.contains("a second reading is needed")), + "{:?}", + report.review + ); + let (_, report) = + read_view_layer("488b8120000000488b9120000000", "488b8128000000488b9130000000"); + assert!( + report + .review + .iter() + .any(|line| line.contains("its uses disagree")), + "{:?}", + report.review + ); + } + #[test] fn nfr6_a_function_start_is_found_only_at_a_function_start() { // The paint function's first bytes also open a block inside another function at 0x105300. @@ -2158,10 +2601,16 @@ mod tests { let prior_pe = PeFile::parse(&prior_bytes).unwrap(); let prior_starts = prior_pe.function_starts(); assert_eq!(prior_starts.len(), 3); - let (prints, _) = fingerprints_of(&verified_row(), &prior_pe); + // The row holds no value without a recipe, so only its addresses are looked for. + let mut verified = verified_row(); + verified["build"]["toolbar"] + .as_object_mut() + .unwrap() + .remove("view_layer"); + let (prints, _) = fingerprints_of(&verified, &prior_pe); let bytes = with_starts(&code, &[0x103100, 0x103200, 0x103300]); let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = find_candidate(&verified_row(), &prints, &prior_starts, "1.0.0.3", &pe); + let (row, report) = find_candidate(&verified, &prints, Some(&prior_pe), "1.0.0.3", &pe); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); // A part moved out of another function starts where it may, and a whole function does not. @@ -2172,18 +2621,19 @@ mod tests { )); let bytes = with_starts(&split, &[0x103100, 0x103200, 0x103300, 0x105308]); let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = find_candidate(&verified_row(), &prints, &prior_starts, "1.0.0.3", &pe); + let (row, report) = find_candidate(&verified, &prints, Some(&prior_pe), "1.0.0.3", &pe); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); // Bytes that match only inside another function are no place at all. let bytes = with_starts(&code, &[0x103100, 0x103200]); let pe = PeFile::parse(&bytes).unwrap(); - let (_, report) = find_candidate(&verified_row(), &prints, &prior_starts, "1.0.0.3", &pe); + let (_, report) = find_candidate(&verified, &prints, Some(&prior_pe), "1.0.0.3", &pe); assert!( report .review .iter() - .any(|line| line == "0x101300 matches no function start, of 2 places"), + .any(|line| line + .starts_with("0x101300 matches no function start, of 2 places; not settled:")), "{:?}", report.review ); diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index 327383c..a14d276 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -415,11 +415,43 @@ pub fn derive_row(build: &mut Value, pe: &PeFile) -> Derived { derived } +/// Values Rivet chooses rather than reads from a build, such as how long it waits before it opens +/// a new tab. The row carries them for the runtime, so they are kept from the prior row. +pub const SETTINGS: &[&str] = &["tabs.new_tab_delay_ms"]; + +/// Lists of `[id, colour]` pairs: the id is a value of the build, and the colour is Rivet's choice. +pub const ID_COLOUR_PAIRS: &[&str] = &["toolbar.dev.colours"]; + +/// The values of a row that are Rivet's settings rather than facts about its build. +pub fn settings(build: &Value) -> Vec { + let mut out: Vec = SETTINGS + .iter() + .filter(|path| number(at_path(build, path)).is_some()) + .map(|path| (*path).to_owned()) + .collect(); + for list in ID_COLOUR_PAIRS { + if let Some(pairs) = at_path(build, list).as_array() { + out.extend((0..pairs.len()).map(|index| format!("{list}[{index}][1]"))); + } + } + out +} + /// Every number of a row below the address range that no recipe reads: member offsets, slots, -/// sizes, ids and constants that a port can only carry over. +/// sizes, ids and constants that a port can only carry over. Rivet's own settings are not listed. pub fn without_recipe(build: &Value) -> Vec { fn walk(path: &str, value: &Value, out: &mut Vec) { match value { + Value::Array(items) + if items.len() == 2 + && path + .rsplit_once('[') + .is_some_and(|(list, _)| ID_COLOUR_PAIRS.contains(&list)) => + { + if number(&items[0]).is_some_and(|id| id < LOWEST_ADDRESS) { + out.push(format!("{path}[0]")); + } + } Value::Object(object) => { for (key, item) in object { let next = if path.is_empty() { @@ -459,6 +491,7 @@ pub fn without_recipe(build: &Value) -> Vec { path != "version" && !path.starts_with("version[") && !FIELDS.iter().any(|field| field.path == path) + && !SETTINGS.contains(&path.as_str()) }); out } @@ -637,4 +670,29 @@ mod tests { vec!["layout.caption_container_offset", "layout.frame_ids"] ); } + + #[test] + fn nfr6_rivet_settings_are_not_values_of_the_build() { + let build = json!({ + "tabs": {"new_tab_delay_ms": 0, "tab_contents": "0x0"}, + "toolbar": {"dev": {"colours": [[316, 4280953905u32], [2082, 0]], "console": 40005}}, + }); + assert_eq!( + without_recipe(&build), + vec![ + "tabs.tab_contents", + "toolbar.dev.colours[0][0]", + "toolbar.dev.colours[1][0]", + "toolbar.dev.console" + ] + ); + assert_eq!( + settings(&build), + vec![ + "tabs.new_tab_delay_ms", + "toolbar.dev.colours[0][1]", + "toolbar.dev.colours[1][1]" + ] + ); + } } diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs new file mode 100644 index 0000000..f6d0bf3 --- /dev/null +++ b/rivet/platform/windows/src/row_resolve.rs @@ -0,0 +1,1278 @@ +//! Finds, in a build whose symbols are not published, the functions and class tables that the +//! prior row's fingerprints do not pin down to one place. +//! +//! Each such address is looked for by several independent methods, and a place is taken only when +//! two different methods name the same place and no method names another. The methods read the +//! prior build, whose row a person verified, next to the new build: +//! +//! - calls into it: a function known in both builds calls or loads it from the same spot of its +//! body in both builds; +//! - its calls: in the prior build it calls functions that their own fingerprints find in the new +//! build, and exactly one candidate makes the same calls from the same spots; +//! - its table slot: a class table known in both builds holds it, at the slot that lines up once +//! the slots around it are compared, since a milestone can add or remove a virtual function; +//! - a text it uses: it refers to a text the new build holds once, and exactly one function there +//! refers to that text; +//! - for a class table, references to it (a function known in both builds loads it from the same +//! spot) and its slots (exactly one candidate holds the same functions in the same slots). +//! +//! Anything else stays unresolved with its reason, and its row goes to a person. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; +use std::rc::Rc; + +use crate::chrome_build::PeFile; +use crate::row_port::{code_print, find_prints, find_table, whole_function, x64}; + +/// How many bytes of a function body are read at most. +const BODY_LIMIT: u32 = 0x4000; +/// How far a function the exception table does not list, a leaf, is read at most. +const LEAF_LIMIT: u32 = 0x200; +/// How many instructions before a site name it within its body. +const CONTEXT: usize = 3; +/// How many levels of calls are followed from the functions known in both builds. +const FOLLOW_DEPTH: usize = 3; +/// How many functions are followed at most. +const FOLLOW_LIMIT: usize = 4000; +/// How many slots of a class table are read at most. +const TABLE_SLOTS: u32 = 512; +/// How many slots of a class table are compared to tell one table from another. +const TABLE_SEEN: u32 = 0x80; +/// How many slots on each side of a slot are compared to line two tables up. +const ALIGN_REACH: u32 = 6; +/// How far a milestone may move a slot. +const ALIGN_SHIFT: i64 = 2; +/// How many slots must agree for two tables, or two stretches of them, to be the same. +const ALIGN_LEAST: usize = 3; +/// The shortest text taken as a sign of the function that uses it. +const TEXT_LEAST: usize = 8; +/// The longest text read. +const TEXT_MOST: usize = 256; +/// How many candidates a function with no fingerprint match may have. +const CANDIDATES_MOST: usize = 256; +/// How many times the methods run again with what the last round found. +const ROUNDS: usize = 4; + +/// One instruction of a function body, as far as the methods need it. +#[derive(Debug, Clone)] +pub struct Step { + pub rva: u32, + /// The bytes with the relative value, displacement and immediate cleared. + pub skeleton: Vec, + /// Where a direct call or jump goes. + pub call: Option, + /// What a RIP-relative operand points at: data, a table or a function passed as a callback. + pub reference: Option, + /// A displacement from a register, as `[rcx + 0x558]` holds. + pub displacement: Option, + pub immediate: Option, + /// A call or jump through memory, as `call [rax + 0x2b8]` calls a table slot. + pub indirect: bool, + /// Its operand is the stack: a local variable, or the frame's size. Neither is a value of a row. + pub stack: bool, +} + +/// Whether a memory operand's base is the stack or frame pointer, which hold locals, not members. +fn stack_based(raw: &[u8], displacement: Option<(usize, usize)>) -> bool { + let Some((offset, size)) = displacement else { + return false; + }; + let opcode = opcode_at(raw); + // REX.B names r12 or r13 where the base field says rsp or rbp. + let extended = opcode > 0 && raw[opcode - 1] & 0xF0 == 0x40 && raw[opcode - 1] & 1 != 0; + let mode = if size == 1 { 1 } else { 2 }; + let before = offset.checked_sub(1).and_then(|at| raw.get(at)).copied(); + let base = match before { + // The ModRM byte itself, with no SIB byte after it. + Some(modrm) if modrm >> 6 == mode && modrm & 7 != 4 => modrm & 7, + // A SIB byte, whose low bits name the base. + Some(sib) => sib & 7, + None => return false, + }; + !extended && matches!(base, 4 | 5) +} + +fn signed(bytes: &[u8], field: (usize, usize)) -> Option { + let (offset, size) = field; + let part = bytes.get(offset..offset + size)?; + Some(match size { + 1 => i64::from(part[0] as i8), + 2 => i64::from(i16::from_le_bytes([part[0], part[1]])), + 4 => i64::from(i32::from_le_bytes([part[0], part[1], part[2], part[3]])), + 8 => i64::from_le_bytes(part.try_into().ok()?), + _ => return None, + }) +} + +/// Where the opcode of an instruction is, past its prefixes. +fn opcode_at(raw: &[u8]) -> usize { + let mut at = 0; + while raw.get(at).is_some_and(|byte| { + matches!( + byte, + 0x66 | 0xF2 | 0xF3 | 0xF0 | 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 + ) + }) { + at += 1; + } + if raw.get(at).is_some_and(|byte| byte & 0xF0 == 0x40) { + at += 1; + } + at +} + +fn step(raw: &[u8], instruction: &x64::Instruction, rva: u32) -> Step { + let next = i64::from(rva) + instruction.length as i64; + let opcode = opcode_at(raw); + let first = raw.get(opcode).copied(); + let second = raw.get(opcode + 1).copied(); + let branch = matches!(first, Some(0x70..=0x7F | 0xEB | 0xE0..=0xE3 | 0xE8 | 0xE9)) + || (first == Some(0x0F) && matches!(second, Some(0x80..=0x8F))); + let mut call = None; + let mut reference = None; + if let Some(field) = instruction.relative { + let target = signed(raw, field) + .map(|distance| next + distance) + .and_then(|target| u32::try_from(target).ok()); + if matches!(first, Some(0xE8 | 0xE9)) { + call = target; + } else if !branch { + reference = target; + } + } + Step { + rva, + skeleton: x64::skeleton(raw, instruction), + call, + reference, + displacement: instruction + .displacement + .and_then(|field| signed(raw, field)), + immediate: instruction.immediate.and_then(|field| signed(raw, field)), + indirect: first == Some(0xFF) + && second.is_some_and(|modrm| matches!((modrm >> 3) & 7, 2 | 4)), + // `add rsp, n` and `sub rsp, n` size the frame. + stack: stack_based(raw, instruction.displacement) + || (matches!(first, Some(0x81 | 0x83)) && matches!(second, Some(0xC4 | 0xEC))), + } +} + +/// Reads a function body from its start, as far as its exception table entry or, for a leaf, its +/// padding, and stops at the first instruction it cannot read. +fn read_body(pe: &PeFile, ranges: &BTreeMap, start: u32) -> Vec { + if !pe.is_code(start) { + return vec![]; + } + let listed = ranges.get(&start).copied(); + let length = match listed { + Some(end) => end.saturating_sub(start).min(BODY_LIMIT), + None => LEAF_LIMIT, + } as usize; + let Some(bytes) = pe.read(start, length).or_else(|| pe.read(start, 16)) else { + return vec![]; + }; + let mut steps = Vec::new(); + let mut at = 0; + while at < bytes.len() { + let rest = &bytes[at..]; + if listed.is_none() && rest.starts_with(&[0xCC, 0xCC]) { + break; + } + let Some(instruction) = x64::decode_body(rest) else { + break; + }; + if instruction.length == 0 || instruction.length > rest.len() { + break; + } + steps.push(step(&rest[..instruction.length], &instruction, start + at as u32)); + at += instruction.length; + } + steps +} + +/// One build: its module, its function ranges and the bodies read so far. +pub struct Side<'a> { + pub pe: &'a PeFile<'a>, + ranges: BTreeMap, + bodies: HashMap>>, +} + +impl<'a> Side<'a> { + pub fn new(pe: &'a PeFile<'a>) -> Self { + Self { + pe, + ranges: pe.function_ranges(), + bodies: HashMap::new(), + } + } + + pub fn body(&mut self, start: u32) -> Rc> { + if let Some(body) = self.bodies.get(&start) { + return Rc::clone(body); + } + let body = Rc::new(read_body(self.pe, &self.ranges, start)); + self.bodies.insert(start, Rc::clone(&body)); + body + } + + /// The start of the function part that holds an address. + fn enclosing(&self, rva: u32) -> Option { + let (start, end) = self.ranges.range(..=rva).next_back()?; + (rva < *end).then_some(*start) + } + + fn is_start(&self, rva: u32) -> bool { + self.ranges.contains_key(&rva) + } +} + +/// Names the instruction at `index` by the instructions around it, as they stay when code moves. +pub fn context(steps: &[Step], index: usize, before: usize, after: usize) -> Vec { + let first = index.saturating_sub(before); + let last = (index + after).min(steps.len().saturating_sub(1)); + let mut key = vec![(index - first) as u8]; + for step in &steps[first..=last] { + key.push(step.skeleton.len() as u8); + key.extend_from_slice(&step.skeleton); + } + key +} + +/// Where each call or reference of a body points, named by the instructions before it, in order. +fn named_sites(steps: &[Step]) -> HashMap, Vec> { + let mut sites: HashMap, Vec> = HashMap::new(); + for (index, step) in steps.iter().enumerate() { + if let Some(target) = step.call.or(step.reference) { + sites + .entry(context(steps, index, CONTEXT, 0)) + .or_default() + .push(target); + } + } + sites +} + +/// Pairs what the two bodies of one function point at: sites named the same way, which each body +/// has the same number of, in order. +fn pair_sites(old: &HashMap, Vec>, new: &HashMap, Vec>) -> Vec<(u32, u32)> { + let mut pairs = Vec::new(); + for (key, targets) in old { + if let Some(others) = new.get(key).filter(|others| others.len() == targets.len()) { + pairs.extend(targets.iter().copied().zip(others.iter().copied())); + } + } + pairs.sort_unstable(); + pairs +} + +/// Addresses of the prior build with their places in the new one, found by following the calls +/// and references of functions known in both. An address reached two ways that disagree has none. +#[derive(Debug, Default)] +pub struct Followed { + pub places: BTreeMap, + conflicts: BTreeSet, +} + +impl Followed { + /// Records a pair, and says whether it is new. + fn add(&mut self, old: u32, new: u32) -> bool { + if self.conflicts.contains(&old) { + return false; + } + match self.places.get(&old) { + Some(place) if *place == new => false, + Some(_) => { + self.places.remove(&old); + self.conflicts.insert(old); + false + } + None => { + self.places.insert(old, new); + true + } + } + } + + fn get(&self, old: u32) -> Option { + self.places.get(&old).copied() + } +} + +/// Follows calls and references from the functions known in both builds, a few levels deep. +pub fn follow(old: &mut Side, new: &mut Side, known: &BTreeMap) -> Followed { + let mut followed = Followed::default(); + let mut frontier: Vec<(u32, u32)> = known + .iter() + .map(|(from, to)| (*from, *to)) + .filter(|(from, to)| old.pe.is_code(*from) && new.pe.is_code(*to)) + .collect(); + let mut visited = BTreeSet::new(); + for _ in 0..FOLLOW_DEPTH { + let mut next = Vec::new(); + for (from_old, from_new) in frontier { + if visited.len() >= FOLLOW_LIMIT || !visited.insert(from_old) { + continue; + } + let old_sites = named_sites(&old.body(from_old)); + let new_sites = named_sites(&new.body(from_new)); + for (to_old, to_new) in pair_sites(&old_sites, &new_sites) { + if known.contains_key(&to_old) { + continue; + } + if followed.add(to_old, to_new) && old.pe.is_code(to_old) && new.pe.is_code(to_new) + { + next.push((to_old, to_new)); + } + } + } + frontier = next; + } + followed +} + +/// The calls a function makes, as its prior body names them, to functions whose place in the new +/// build is known: `(site, rank among sites named the same, how many such sites, new place)`. +fn expected_calls( + old: &mut Side, + target: u32, + anchors: &BTreeMap, +) -> Vec<(Vec, usize, usize, u32)> { + let body = old.body(target); + let mut expected = Vec::new(); + for (key, callees) in named_sites(&body) { + for (rank, callee) in callees.iter().enumerate() { + if let Some(place) = anchors.get(callee) { + expected.push((key.clone(), rank, callees.len(), *place)); + } + } + } + expected.sort(); + expected +} + +/// The one candidate that makes the expected calls from the same spots, and contradicts none. +fn by_its_calls( + new: &mut Side, + expected: &[(Vec, usize, usize, u32)], + candidates: &[u32], +) -> Vec { + if expected.is_empty() { + return vec![]; + } + let least = expected.len().min(2); + let mut passing = Vec::new(); + for candidate in candidates { + let theirs = named_sites(&new.body(*candidate)); + let (mut hits, mut misses) = (0, 0); + for (key, rank, count, place) in expected { + match theirs.get(key) { + Some(found) if found.len() == *count => { + if found[*rank] == *place { + hits += 1; + } else { + misses += 1; + } + } + _ => {} + } + } + if misses == 0 && hits >= least { + passing.push(*candidate); + } + } + // Two candidates that both pass cannot be told apart: neither is an answer. + if passing.len() == 1 { + passing + } else { + vec![] + } +} + +/// The functions of a build that call any of `wanted` directly, by the function part each call is in. +fn calls_into(side: &Side, wanted: &BTreeSet) -> BTreeMap> { + let mut found: BTreeMap> = BTreeMap::new(); + if wanted.is_empty() { + return found; + } + for (base, bytes, is_code) in side.pe.sections() { + if !is_code { + continue; + } + for at in 0..bytes.len().saturating_sub(4) { + if !matches!(bytes[at], 0xE8 | 0xE9) { + continue; + } + let distance = i32::from_le_bytes([bytes[at + 1], bytes[at + 2], bytes[at + 3], bytes[at + 4]]); + let site = base + at as u32; + let Ok(target) = u32::try_from(i64::from(site) + 5 + i64::from(distance)) else { + continue; + }; + if wanted.contains(&target) { + if let Some(start) = side.enclosing(site) { + found.entry(target).or_default().insert(start); + } + } + } + } + found +} + +/// The functions the prior bodies of `targets` call that their own fingerprints find in exactly one +/// place of the new build. They do not depend on the calls followed from known functions. +fn callee_anchors(old: &mut Side, new: &Side, targets: &[u32]) -> BTreeMap { + let mut prints = BTreeMap::new(); + for target in targets { + let body = old.body(*target); + for step in body.iter() { + let callee = step + .call + .or(step.reference.filter(|place| old.pe.is_code(*place))); + if let Some(callee) = callee { + if let Some(print) = code_print(old.pe, callee) { + prints.insert(callee, print); + } + } + } + } + let mut anchors = BTreeMap::new(); + for (callee, places) in find_prints(new.pe, &prints) { + // A print taken at a function start counts only function starts, as for the row itself. + let places: Vec = places + .into_iter() + .filter(|place| !old.is_start(callee) || new.is_start(*place)) + .collect(); + if let [only] = places.as_slice() { + anchors.insert(callee, *only); + } + } + anchors +} + +/// A function as the slots of a class table show it: its fingerprint, or the whole of a short one. +fn entry_shape(pe: &PeFile, function: u32) -> Option> { + code_print(pe, function).or_else(|| whole_function(pe, function)) +} + +fn same_function(old: &Side, new: &Side, known: &BTreeMap, from: u32, to: u32) -> bool { + if let Some(place) = known.get(&from) { + return *place == to; + } + match (entry_shape(old.pe, from), entry_shape(new.pe, to)) { + (Some(left), Some(right)) => left == right, + _ => false, + } +} + +/// The function in a slot of a class table, or `None` past the table's end. +fn entry(pe: &PeFile, table: u32, slot: i64) -> Option { + let slot = u32::try_from(slot).ok()?; + let at = table.checked_add(slot.checked_mul(8)?)?; + pe.pointer_rva(at).filter(|function| pe.is_code(*function)) +} + +/// How far slot `slot` of the old table moved in the new one, judged by the slots around it. +fn line_up( + old: &Side, + new: &Side, + known: &BTreeMap, + tables: (u32, u32), + slot: u32, +) -> Option { + let mut scores = Vec::new(); + for shift in -ALIGN_SHIFT..=ALIGN_SHIFT { + let mut score = 0; + for near in slot.saturating_sub(ALIGN_REACH)..=slot + ALIGN_REACH { + if near == slot { + continue; + } + let from = entry(old.pe, tables.0, i64::from(near)); + let to = entry(new.pe, tables.1, i64::from(near) + shift); + if let (Some(from), Some(to)) = (from, to) { + if same_function(old, new, known, from, to) { + score += 1; + } + } + } + scores.push((score, shift)); + } + scores.sort_by(|left, right| right.0.cmp(&left.0)); + match scores.as_slice() { + [(top, shift), (second, _), ..] if *top >= ALIGN_LEAST && top > second => Some(*shift), + _ => None, + } +} + +/// The places the class tables known in both builds give a function by its slot. +fn by_table_slot( + old: &Side, + new: &Side, + known: &BTreeMap, + tables: &[(u32, u32)], + target: u32, +) -> BTreeSet { + let mut found = BTreeSet::new(); + for pair in tables { + for slot in 0..TABLE_SLOTS { + let Some(function) = entry(old.pe, pair.0, i64::from(slot)) else { + break; + }; + if function != target { + continue; + } + if let Some(shift) = line_up(old, new, known, *pair, slot) { + if let Some(place) = entry(new.pe, pair.1, i64::from(slot) + shift) { + found.insert(place); + } + } + } + } + found +} + +/// The candidate tables whose slots hold the same functions as the old table, and how many agree. +fn by_slots( + old: &Side, + new: &Side, + known: &BTreeMap, + target: u32, + candidates: &[u32], +) -> Vec { + let mut passing = Vec::new(); + for candidate in candidates { + let (mut seen, mut agreed) = (0, 0); + for slot in 0..TABLE_SEEN { + let Some(function) = entry(old.pe, target, i64::from(slot)) else { + break; + }; + seen += 1; + let agrees = (-1..=1).any(|shift| { + entry(new.pe, *candidate, i64::from(slot) + shift) + .is_some_and(|place| same_function(old, new, known, function, place)) + }); + if agrees { + agreed += 1; + } + } + if agreed >= ALIGN_LEAST && agreed * 2 >= seen { + passing.push(*candidate); + } + } + passing +} + +/// Tables of the new build that hold, near the same slot, a function the old table holds and +/// whose place is known. +fn table_candidates(old: &Side, new: &Side, known: &BTreeMap, target: u32) -> Vec { + let mut found = BTreeSet::new(); + let mut tried = 0; + for slot in 0..TABLE_SEEN { + let Some(function) = entry(old.pe, target, i64::from(slot)) else { + break; + }; + let Some(place) = known.get(&function).filter(|place| new.pe.is_code(**place)) else { + continue; + }; + for shifted in slot.saturating_sub(1)..=slot + 1 { + found.extend(find_table(new.pe, shifted, *place)); + } + tried += 1; + if tried == 2 { + break; + } + } + found.into_iter().take(CANDIDATES_MOST).collect() +} + +/// A table a function known in both builds loads from the same spot, or a place a few slots into +/// one, which keeps its distance from the table's start. +fn by_reference(followed: &Followed, target: u32) -> Option { + let (from, to) = followed + .places + .range(target.saturating_sub(0x40)..=target) + .next_back()?; + to.checked_add(target - from) +} + +/// The text at an address of a data section, with its terminating zero, when it is plain text. +fn text_at(pe: &PeFile, rva: u32) -> Option> { + if pe.is_code(rva) { + return None; + } + let window = pe + .read(rva, TEXT_MOST + 1) + .or_else(|| pe.read(rva, TEXT_LEAST + 1))?; + let end = window.iter().position(|byte| *byte == 0)?; + let text = &window[..end]; + if text.len() < TEXT_LEAST || !text.iter().all(|byte| (0x20..0x7F).contains(byte)) { + return None; + } + Some(window[..=end].to_vec()) +} + +/// For each text, the functions of a build that load it, when the build holds it exactly once. +fn functions_using(side: &Side, texts: &BTreeSet>) -> BTreeMap, BTreeSet> { + let mut by_head: HashMap<[u8; TEXT_LEAST], Vec<&Vec>> = HashMap::new(); + let mut first = [false; 256]; + for text in texts { + let head: [u8; TEXT_LEAST] = text[..TEXT_LEAST].try_into().expect("checked length"); + first[head[0] as usize] = true; + by_head.entry(head).or_default().push(text); + } + let mut places: BTreeMap<&Vec, Vec> = BTreeMap::new(); + for (base, bytes, is_code) in side.pe.sections() { + if is_code { + continue; + } + for at in 0..bytes.len().saturating_sub(TEXT_LEAST) { + if !first[bytes[at] as usize] { + continue; + } + let head: [u8; TEXT_LEAST] = bytes[at..at + TEXT_LEAST].try_into().expect("in range"); + for text in by_head.get(&head).map_or(&[][..], Vec::as_slice) { + if bytes[at..].starts_with(text) { + places.entry(*text).or_default().push(base + at as u32); + } + } + } + } + let at_address: HashMap> = places + .iter() + .filter_map(|(text, found)| match found.as_slice() { + [only] => Some((*only, *text)), + _ => None, + }) + .collect(); + let mut users: BTreeMap, BTreeSet> = BTreeMap::new(); + for (base, bytes, is_code) in side.pe.sections() { + if !is_code { + continue; + } + // `lea` or `mov` of a register from [rip + disp32]: REX, 8D or 8B, a ModRM of 00 reg 101. + for at in 3..bytes.len().saturating_sub(4) { + if bytes[at - 1] & 0xC7 != 0x05 + || !matches!(bytes[at - 2], 0x8D | 0x8B) + || bytes[at - 3] & 0xF0 != 0x40 + { + continue; + } + let distance = i32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); + let site = base + at as u32; + let Ok(target) = u32::try_from(i64::from(site) + 4 + i64::from(distance)) else { + continue; + }; + if let Some(text) = at_address.get(&target) { + if let Some(start) = side.enclosing(site) { + users.entry((*text).clone()).or_default().insert(start); + } + } + } + } + users +} + +/// Which method gave a place. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Method { + CallsInto, + ItsCalls, + TableSlot, + Text, + References, + Slots, +} + +impl fmt::Display for Method { + fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { + out.write_str(match self { + Method::CallsInto => "calls into it", + Method::ItsCalls => "its calls", + Method::TableSlot => "its table slot", + Method::Text => "a text it uses", + Method::References => "references to it", + Method::Slots => "its slots", + }) + } +} + +fn names(methods: &BTreeSet) -> String { + methods + .iter() + .map(Method::to_string) + .collect::>() + .join(" and ") +} + +/// Takes a place only when two different methods name it, no method names another, and it is one +/// of the fingerprint's places where there are any. +pub fn decide( + answers: &[(Method, u32)], + candidates: Option<&[u32]>, +) -> Result<(u32, BTreeSet), String> { + let places: BTreeSet = answers.iter().map(|(_, place)| *place).collect(); + let methods: BTreeSet = answers.iter().map(|(method, _)| *method).collect(); + match places.iter().copied().collect::>().as_slice() { + [] => Err("no method found it".to_owned()), + [place] => { + if candidates.is_some_and(|candidates| !candidates.contains(place)) { + Err(format!( + "{} found {place:#x}, which is not one of its fingerprint's places", + names(&methods) + )) + } else if methods.len() < 2 { + Err(format!( + "only {} found it, at {place:#x}, and a second method is needed", + names(&methods) + )) + } else { + Ok((*place, methods)) + } + } + _ => { + let mut said: Vec = answers + .iter() + .map(|(method, place)| format!("{method} {place:#x}")) + .collect(); + said.sort(); + said.dedup(); + Err(format!("the methods disagree: {}", said.join(", "))) + } + } +} + +/// What an address of the prior row is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Function, + Table, +} + +/// An address the fingerprints did not pin down, with the places they matched, if any. +#[derive(Debug, Clone)] +pub struct Wanted { + pub kind: Kind, + pub candidates: Option>, +} + +/// What the methods found. +#[derive(Debug, Default)] +pub struct Resolution { + /// The new place of each address two methods agree on. + pub places: BTreeMap, + /// For the report: each place and the methods that found it. + pub settled: Vec, + /// Why each other address has no place. + pub reasons: BTreeMap, + /// Functions of the prior build with their places in the new one, as the calls of known + /// functions pair them, for reading values from the same instructions in both builds. + pub followed: BTreeMap, +} + +/// Looks for each wanted address with every method, in rounds, since a place found in one round +/// is known in the next. `known` holds the places the fingerprints found, and `tables` names the +/// prior row's addresses that are class tables. +pub fn resolve( + old_pe: &PeFile, + new_pe: &PeFile, + known: &BTreeMap, + wanted: &BTreeMap, + tables: &BTreeSet, +) -> Resolution { + let mut old = Side::new(old_pe); + let mut new = Side::new(new_pe); + let mut known = known.clone(); + let mut resolution = Resolution::default(); + let functions: Vec = wanted + .iter() + .filter(|(_, want)| want.kind == Kind::Function) + .map(|(target, _)| *target) + .collect(); + + // What does not depend on the known places is read once: the callees found by their own + // fingerprints, the functions that call them, and the texts each function uses. + let anchors = callee_anchors(&mut old, &new, &functions); + let mut texts_of: BTreeMap>> = BTreeMap::new(); + for target in &functions { + let body = old.body(*target); + let texts: BTreeSet> = body + .iter() + .filter_map(|step| step.reference) + .filter_map(|place| text_at(old.pe, place)) + .collect(); + texts_of.insert(*target, texts); + } + let all_texts: BTreeSet> = texts_of.values().flatten().cloned().collect(); + let users = functions_using(&new, &all_texts); + let mut seen_anchors = anchors.clone(); + for (from, to) in &known { + if old.pe.is_code(*from) { + seen_anchors.insert(*from, *to); + } + } + let mut expected = BTreeMap::new(); + let mut called = BTreeSet::new(); + for target in &functions { + let calls = expected_calls(&mut old, *target, &seen_anchors); + called.extend(calls.iter().map(|call| call.3)); + expected.insert(*target, calls); + } + let callers = calls_into(&new, &called); + + let mut pending: BTreeSet = wanted.keys().copied().collect(); + for _ in 0..ROUNDS { + let followed = follow(&mut old, &mut new, &known); + let table_pairs: Vec<(u32, u32)> = known + .iter() + .filter(|(from, _)| tables.contains(from)) + .map(|(from, to)| (*from, *to)) + .collect(); + let mut found_any = false; + for target in pending.clone() { + let want = &wanted[&target]; + let mut answers = Vec::new(); + match want.kind { + Kind::Function => { + if let Some(place) = followed.get(target) { + answers.push((Method::CallsInto, place)); + } + let calls = &expected[&target]; + let candidates: Vec = match &want.candidates { + Some(list) => list.clone(), + None => calls + .iter() + .flat_map(|call| callers.get(&call.3).into_iter().flatten().copied()) + .collect::>() + .into_iter() + .take(CANDIDATES_MOST) + .collect(), + }; + for place in by_its_calls(&mut new, calls, &candidates) { + answers.push((Method::ItsCalls, place)); + } + for place in by_table_slot(&old, &new, &known, &table_pairs, target) { + answers.push((Method::TableSlot, place)); + } + if let Some(place) = by_text(&texts_of[&target], &users) { + answers.push((Method::Text, place)); + } + } + Kind::Table => { + if let Some(place) = by_reference(&followed, target) { + answers.push((Method::References, place)); + } + let candidates = match &want.candidates { + Some(list) => list.clone(), + None => table_candidates(&old, &new, &known, target), + }; + for place in by_slots(&old, &new, &known, target, &candidates) { + answers.push((Method::Slots, place)); + } + } + } + match decide(&answers, want.candidates.as_deref()) { + Ok((place, methods)) => { + known.insert(target, place); + resolution.places.insert(target, place); + resolution.settled.push(format!( + "{target:#x} -> {place:#x} by {}", + names(&methods) + )); + resolution.reasons.remove(&target); + pending.remove(&target); + found_any = true; + } + Err(reason) => { + resolution.reasons.insert(target, reason); + } + } + } + resolution.followed = followed.places; + if !found_any || pending.is_empty() { + break; + } + } + resolution +} + +/// The one function that uses every text of a target the new build holds once. +fn by_text(texts: &BTreeSet>, users: &BTreeMap, BTreeSet>) -> Option { + let mut common: Option> = None; + for text in texts { + let Some(found) = users.get(text) else { + continue; + }; + common = Some(match common { + Some(common) => common.intersection(found).copied().collect(), + None => found.clone(), + }); + } + let common = common?; + match common.iter().copied().collect::>().as_slice() { + [only] => Some(*only), + _ => None, + } +} + +/// How many instructions on each side of a use name it within its body. +const VALUE_CONTEXT: usize = 2; + +/// Which operand of an instruction holds a value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Operand { + Displacement, + Immediate, +} + +/// A value of the prior row read again from the new build, or why it could not be. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Reading { + pub path: String, + pub prior: u64, + /// The new value and how it was read. + pub value: Result<(u64, String), String>, +} + +fn keys(steps: &[Step]) -> Vec> { + (0..steps.len()) + .map(|index| context(steps, index, VALUE_CONTEXT, VALUE_CONTEXT)) + .collect() +} + +/// Whether an instruction uses `wanted`: as a member displacement or an immediate for a plain +/// value, or as the displacement of a call through a table for a slot, which is eight bytes each. +fn use_of(step: &Step, wanted: i64, slot: bool) -> Option { + if step.stack { + return None; + } + if slot { + return (step.indirect && step.displacement == Some(wanted)).then_some(Operand::Displacement); + } + if step.displacement == Some(wanted) { + Some(Operand::Displacement) + } else if step.immediate == Some(wanted) { + Some(Operand::Immediate) + } else { + None + } +} + +/// Reads one value from the instructions that use it. Each use of `prior` in a prior function body +/// is named by the instructions around it, with their own operands cleared, and the same +/// instruction is looked up in the function's new body. A value is taken only when at least two +/// uses are read and every use read gives the same value. +fn read_value( + old: &mut Side, + new: &mut Side, + pairs: &[(u32, u32)], + prior: u64, + slot: bool, +) -> Result<(u64, String), String> { + if prior == 0 { + return Err("zero is used too widely in code to be told apart".to_owned()); + } + let wanted = if slot { prior.checked_mul(8) } else { Some(prior) } + .and_then(|value| i64::try_from(value).ok()) + .ok_or_else(|| format!("{prior:#x} is too large to be an operand"))?; + let mut found: Vec<(u64, u32)> = Vec::new(); + let mut uses = 0; + for (from, to) in pairs { + let old_body = old.body(*from); + let new_body = new.body(*to); + let old_keys = keys(&old_body); + let new_keys = keys(&new_body); + for (index, step) in old_body.iter().enumerate() { + let Some(operand) = use_of(step, wanted, slot) else { + continue; + }; + uses += 1; + let key = &old_keys[index]; + let rank = old_keys[..index].iter().filter(|other| *other == key).count(); + let count = old_keys.iter().filter(|other| *other == key).count(); + let theirs: Vec = new_keys + .iter() + .enumerate() + .filter(|(_, other)| *other == key) + .map(|(at, _)| at) + .collect(); + if theirs.len() != count { + continue; + } + let other = &new_body[theirs[rank]]; + let read = match operand { + Operand::Displacement => other.displacement, + Operand::Immediate => other.immediate, + }; + let Some(read) = read.and_then(|read| u64::try_from(read).ok()) else { + continue; + }; + if slot && read % 8 != 0 { + continue; + } + found.push((if slot { read / 8 } else { read }, *from)); + } + } + let values: BTreeSet = found.iter().map(|(value, _)| *value).collect(); + let functions: BTreeSet = found.iter().map(|(_, function)| *function).collect(); + match values.iter().copied().collect::>().as_slice() { + [] if uses == 0 => Err(format!( + "no instruction of the {} functions known in both builds uses {prior:#x}", + pairs.len() + )), + [] => Err(format!( + "its {uses} uses in the prior build were not found in the new one" + )), + [value] if found.len() >= 2 => Ok(( + *value, + format!( + "read at {} uses in {} of its functions", + found.len(), + functions.len() + ), + )), + [value] => Err(format!( + "read at only one use, as {value:#x}, and a second reading is needed" + )), + _ => Err(format!("its uses disagree: {values:#x?}")), + } +} + +/// Reads each value of the prior row that has no recipe from the instructions that use it in the +/// functions of its part of the row, and in the functions they call, in both builds. `sections` +/// pairs the prior and new places of each part's functions, and `followed` pairs the functions +/// the calls of known functions reach. A value's part is the first name of its path, and a value +/// whose name ends in `_slot` is a slot of a class table. +pub fn read_values( + old_pe: &PeFile, + new_pe: &PeFile, + sections: &BTreeMap>, + followed: &BTreeMap, + values: &[(String, u64)], +) -> Vec { + let mut old = Side::new(old_pe); + let mut new = Side::new(new_pe); + let mut pairs_of: BTreeMap<&str, Vec<(u32, u32)>> = BTreeMap::new(); + for (section, pairs) in sections { + let mut all: BTreeSet<(u32, u32)> = pairs.iter().copied().collect(); + for (from, _) in pairs { + let body = old.body(*from); + for step in body.iter() { + if let Some(place) = step.call.and_then(|callee| followed.get(&callee)) { + all.insert((step.call.expect("checked"), *place)); + } + } + } + pairs_of.insert(section.as_str(), all.into_iter().collect()); + } + let mut readings = Vec::new(); + for (path, prior) in values { + let section = path.split('.').next().unwrap_or_default(); + let name = path.rsplit('.').next().unwrap_or_default(); + let slot = name.split('[').next().unwrap_or_default().ends_with("_slot"); + let pairs = pairs_of.get(section).map_or(&[][..], Vec::as_slice); + readings.push(Reading { + path: path.clone(), + prior: *prior, + value: read_value(&mut old, &mut new, pairs, *prior, slot), + }); + } + readings +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub const IMAGE_BASE: u64 = 0x1_8000_0000; + /// Where a fixture keeps its exception table, in its data section. + const EXCEPTIONS: u32 = 0x20f000; + + fn place(rva: u32) -> usize { + if rva >= 0x200000 { + 0x10400 + (rva - 0x200000) as usize + } else { + 0x400 + (rva - 0x100000) as usize + } + } + + /// A 64-bit module with a code section at 0x100000 and a data section at 0x200000, holding + /// the given bytes and an exception table that lists `ranges`. + pub fn module(parts: &[(u32, Vec)], ranges: &[(u32, u32)]) -> Vec { + let mut bytes = vec![0u8; 0x400]; + bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); + bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); + bytes[0x86..0x88].copy_from_slice(&2u16.to_le_bytes()); + bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes()); + bytes[0x98..0x9a].copy_from_slice(&0x20bu16.to_le_bytes()); + bytes[0x98 + 24..0x98 + 32].copy_from_slice(&IMAGE_BASE.to_le_bytes()); + let sections = [ + (0x100000u32, 0x400u32, 0x2000_0000u32), + (0x200000, 0x10400, 0x4000_0000), + ]; + for (index, (rva, raw, flags)) in sections.iter().enumerate() { + let header = 0x98 + 240 + 40 * index; + bytes[header + 8..header + 12].copy_from_slice(&0x10000u32.to_le_bytes()); + bytes[header + 12..header + 16].copy_from_slice(&rva.to_le_bytes()); + bytes[header + 16..header + 20].copy_from_slice(&0x10000u32.to_le_bytes()); + bytes[header + 20..header + 24].copy_from_slice(&raw.to_le_bytes()); + bytes[header + 36..header + 40].copy_from_slice(&flags.to_le_bytes()); + } + bytes.resize(0x400 + 0x20000, 0); + bytes[0x400..0x10400].fill(0xCC); + let mut table = vec![]; + for (start, end) in ranges { + table.extend_from_slice(&start.to_le_bytes()); + table.extend_from_slice(&end.to_le_bytes()); + table.extend_from_slice(&0u32.to_le_bytes()); + } + let directory = 0x98 + 112 + 24; + bytes[directory..directory + 4].copy_from_slice(&EXCEPTIONS.to_le_bytes()); + bytes[directory + 4..directory + 8].copy_from_slice(&(table.len() as u32).to_le_bytes()); + let at = place(EXCEPTIONS); + bytes[at..at + table.len()].copy_from_slice(&table); + for (rva, data) in parts { + let at = place(*rva); + bytes[at..at + data.len()].copy_from_slice(data); + } + bytes + } + + pub fn call(from: u32, to: u32) -> Vec { + let mut bytes = vec![0xE8]; + bytes.extend_from_slice(&((i64::from(to) - i64::from(from) - 5) as i32).to_le_bytes()); + bytes + } + + pub fn table(functions: &[u32]) -> Vec { + functions + .iter() + .flat_map(|function| (IMAGE_BASE + u64::from(*function)).to_le_bytes()) + .collect() + } + + /// sub rsp, 28h; call `to`; add rsp, 28h; ret. + fn caller(at: u32, to: u32) -> Vec { + let mut bytes = vec![0x48, 0x83, 0xEC, 0x28]; + bytes.extend(call(at + 4, to)); + bytes.extend([0x48, 0x83, 0xC4, 0x28, 0xC3]); + bytes + } + + /// push rsi; sub rsp, 20h; mov rsi, rcx; add rsp, 20h; pop rsi; ret. + const TARGET: [u8; 14] = [ + 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x83, 0xC4, 0x20, 0x5E, 0xC3, + ]; + + /// `mov eax, n; ret`: a different small function for each slot of a table. + fn small(n: u8) -> Vec { + vec![0xB8, n, 0, 0, 0, 0xC3] + } + + const OLD_CALLER: u32 = 0x101000; + const OLD_TARGET: u32 = 0x101100; + const OLD_TABLE: u32 = 0x200100; + const NEW_CALLER: u32 = 0x103000; + const NEW_TARGETS: [u32; 2] = [0x103100, 0x103200]; + const NEW_TABLE: u32 = 0x200800; + + /// The prior build: a caller of the target, and a table that holds it in slot 3. + fn old_module() -> Vec { + let mut parts = vec![ + (OLD_CALLER, caller(OLD_CALLER, OLD_TARGET)), + (OLD_TARGET, TARGET.to_vec()), + ]; + let mut slots = vec![]; + for n in 0..6u8 { + let at = 0x101400 + 0x10 * u32::from(n); + parts.push((at, small(n))); + slots.push(at); + } + slots.insert(3, OLD_TARGET); + parts.push((OLD_TABLE, table(&slots))); + module( + &parts, + &[(OLD_CALLER, OLD_CALLER + 14), (OLD_TARGET, OLD_TARGET + 14)], + ) + } + + /// The new build: the target's bytes in two places, a caller of the first, and a table that + /// holds `in_table` in slot 3. + fn new_module(in_table: u32) -> Vec { + let mut parts = vec![ + (NEW_CALLER, caller(NEW_CALLER, NEW_TARGETS[0])), + (NEW_TARGETS[0], TARGET.to_vec()), + (NEW_TARGETS[1], TARGET.to_vec()), + ]; + let mut slots = vec![]; + for n in 0..6u8 { + let at = 0x103400 + 0x10 * u32::from(n); + parts.push((at, small(n))); + slots.push(at); + } + slots.insert(3, in_table); + parts.push((NEW_TABLE, table(&slots))); + let ranges = [ + (NEW_CALLER, NEW_CALLER + 14), + (NEW_TARGETS[0], NEW_TARGETS[0] + 14), + (NEW_TARGETS[1], NEW_TARGETS[1] + 14), + ]; + module(&parts, &ranges) + } + + fn run(new_bytes: &[u8], known_table: bool) -> Resolution { + let old_bytes = old_module(); + let old = PeFile::parse(&old_bytes).unwrap(); + let new = PeFile::parse(new_bytes).unwrap(); + let mut known = BTreeMap::from([(OLD_CALLER, NEW_CALLER)]); + if known_table { + known.insert(OLD_TABLE, NEW_TABLE); + } + let wanted = BTreeMap::from([( + OLD_TARGET, + Wanted { + kind: Kind::Function, + candidates: Some(NEW_TARGETS.to_vec()), + }, + )]); + resolve(&old, &new, &known, &wanted, &BTreeSet::from([OLD_TABLE])) + } + + #[test] + fn nfr6_a_function_with_several_places_takes_the_one_two_methods_agree_on() { + let resolution = run(&new_module(NEW_TARGETS[0]), true); + assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); + assert_eq!( + resolution.settled, + ["0x101100 -> 0x103100 by calls into it and its table slot"] + ); + assert!(resolution.reasons.is_empty(), "{:?}", resolution.reasons); + } + + #[test] + fn nfr6_methods_that_disagree_leave_the_function_unresolved() { + let resolution = run(&new_module(NEW_TARGETS[1]), true); + assert!(resolution.places.is_empty()); + let reason = &resolution.reasons[&OLD_TARGET]; + assert!(reason.starts_with("the methods disagree: "), "{reason}"); + assert!(reason.contains("calls into it 0x103100"), "{reason}"); + assert!(reason.contains("its table slot 0x103200"), "{reason}"); + } + + #[test] + fn nfr6_one_method_alone_does_not_place_a_function() { + let resolution = run(&new_module(NEW_TARGETS[0]), false); + assert!(resolution.places.is_empty()); + let reason = &resolution.reasons[&OLD_TARGET]; + assert!(reason.starts_with("only calls into it found it"), "{reason}"); + } + + #[test] + fn nfr6_a_place_outside_the_fingerprint_matches_is_refused() { + let answers = [(Method::CallsInto, 0x103300), (Method::TableSlot, 0x103300)]; + let refused = decide(&answers, Some(&NEW_TARGETS[..])).unwrap_err(); + assert!(refused.contains("not one of its fingerprint's places"), "{refused}"); + let (place, methods) = decide(&answers, None).unwrap(); + assert_eq!(place, 0x103300); + assert_eq!(methods.len(), 2); + assert_eq!(decide(&[], None).unwrap_err(), "no method found it"); + } +} From 71d517a3a7557f489ed90d7da784e870b491aa9b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:35:30 +0000 Subject: [PATCH 02/29] Publish: develop 3f547a2 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .github/workflows/browser-rows.yml | 8 +- .../platform/windows/src/bin/chrome-builds.rs | 14 +- rivet/platform/windows/src/command_ids.rs | 55 +++ rivet/platform/windows/src/lib.rs | 2 + rivet/platform/windows/src/row_features.rs | 348 ++++++++++++++++++ rivet/platform/windows/src/row_port.rs | 259 ++++++++++++- rivet/platform/windows/src/row_recipe.rs | 80 +++- rivet/platform/windows/src/row_watch.rs | 36 ++ .../windows/src/browsers/chromium/commands.rs | 19 + rivet/runtime/windows/src/builds/chrome.rs | 2 - rivet/runtime/windows/src/builds/mod.rs | 13 +- rivet/runtime/windows/src/builds/tests.rs | 42 ++- rivet/runtime/windows/src/chromium/view.rs | 7 + .../windows/src/features/app_window.rs | 19 +- .../runtime/windows/src/features/dev_page.rs | 16 +- 15 files changed, 874 insertions(+), 46 deletions(-) create mode 100644 rivet/platform/windows/src/command_ids.rs create mode 100644 rivet/platform/windows/src/row_features.rs diff --git a/.github/workflows/browser-rows.yml b/.github/workflows/browser-rows.yml index d99737e..d0c5a42 100644 --- a/.github/workflows/browser-rows.yml +++ b/.github/workflows/browser-rows.yml @@ -431,7 +431,9 @@ jobs: # The harness builds Rivet itself, with the test flags that keep sync and sign-in off. ./scripts/tests/windows-features.ps1 -Browsers $name ` -Executable "${{ steps.build.outputs.executable }}" -OutDir $features - ./tools/chrome-builds.exe gate (Join-Path $features "results.json") $name + # A check of a feature the row turns off for this build is not required; the row ships with + # that feature off, and the gate prints a note for it. + ./tools/chrome-builds.exe gate (Join-Path $features "results.json") $name "$temp/row.json" if ($LASTEXITCODE -ne 0) { throw "a feature check failed or could not run; results.json lists which" } Set-Content (Join-Path $temp "session/features-passed") "${{ matrix.build.version }}" @@ -538,6 +540,10 @@ jobs: $body += "The symbol server had no PDB for this build, so the row was made from the fingerprints of the $($report.prior_version) row: $($report.fingerprinted.Count) of $($report.addresses) addresses matched exactly one place. When the PDB appears, the row job makes the row again from it and compares the two.`n`n" } $body += (($report.review | ForEach-Object { "- $_" }) -join "`n") + if ($report.switched_off.Count -gt 0) { + $body += "`n`nThese features are off in this row, because a value they need could not be read from this build:`n`n" + $body += (($report.switched_off | ForEach-Object { "- $_" }) -join "`n") + } gh pr create --draft --base develop --head $branch --title "Feat: Propose a row for ${{ matrix.build.browser }} ${{ matrix.build.version }}" --body $body gh workflow run test.yml --ref $branch diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index f3fb64b..e37dac5 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -105,7 +105,8 @@ fn main() -> ExitCode { ["pending", stable, beta, edge, brave, known] => { pending(Path::new(stable), Path::new(beta), Path::new(edge), Path::new(brave), Path::new(known)) } - ["gate", results, browser] => gate(Path::new(results), browser), + ["gate", results, browser] => gate(Path::new(results), browser, None), + ["gate", results, browser, row] => gate(Path::new(results), browser, Some(Path::new(row))), ["fingerprint", row, module, out] => fingerprint(Path::new(row), Path::new(module), Path::new(out)), ["release-sign", version, signed, files @ ..] => release_sign(version, Path::new(signed), files), ["release-check", signed, file] => release_check(Path::new(signed), Path::new(file)), @@ -123,7 +124,7 @@ fn main() -> ExitCode { ["table-withdraw", published, signed, builds @ ..] if !builds.is_empty() => { table_withdraw(Path::new(published), Path::new(signed), builds) } - _ => Err("usage: chrome-builds pdb-key | extract [frame-class] | port | find | pdb-check | pending | gate | fingerprint | release-sign ... | release-check | table-key | table-add | table-read | table-merge ... | table-sign [published-file] | table-withdraw ...".into()), + _ => Err("usage: chrome-builds pdb-key | extract
[frame-class] | port | find | pdb-check | pending | gate [row.json] | fingerprint | release-sign ... | release-check | table-key | table-add | table-read | table-merge ... | table-sign [published-file] | table-withdraw ...".into()), }; match result { Ok(()) => ExitCode::SUCCESS, @@ -878,13 +879,18 @@ mod symbols { } /// Refuses a browser that did not pass every feature check, so it is never listed as supported. -fn gate(results: &Path, browser: &str) -> Result<(), String> { +/// The row is the one being published: a check of a feature it turns off is not required. +fn gate(results: &Path, browser: &str, row: Option<&Path>) -> Result<(), String> { + let row = match row { + Some(path) => json_file(path)?, + None => serde_json::Value::Null, + }; let text = String::from_utf8(read(results)?) .map_err(|error| format!("the feature results are not text: {error}"))?; // PowerShell writes UTF-8 with a byte order mark. let results: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')) .map_err(|error| format!("the feature results are not JSON: {error}"))?; - let notes = row_watch::publish_gate(&results, browser) + let notes = row_watch::publish_gate_for_row(&results, browser, &row) .map_err(|reasons| format!("{browser} is not supported: {}", reasons.join("; ")))?; for note in notes { println!("note: {note}"); diff --git a/rivet/platform/windows/src/command_ids.rs b/rivet/platform/windows/src/command_ids.rs new file mode 100644 index 0000000..fe805cb --- /dev/null +++ b/rivet/platform/windows/src/command_ids.rs @@ -0,0 +1,55 @@ +//! Chromium's browser command ids that Rivet runs, per Chromium milestone. +//! +//! A browser window runs these ids from its own `WM_COMMAND`, as its own menu and keys do, so they +//! need no address or member of the build. They are defined in `chrome/app/chrome_command_ids.h`, +//! and each value below was read from that header at the milestone's branch on +//! chromium.googlesource.com (`refs/branch-heads//chrome/app/chrome_command_ids.h`). They +//! are public and stable, so they are not values of a build row: the row generator and the +//! runtime both take them from here. A milestone without a read value has no id, and what needs it +//! stays off, because a wrong id runs another command. + +/// `IDC_DEV_TOOLS_INSPECT` and `IDC_DEV_TOOLS_CONSOLE` per Chromium milestone, with the branch the +/// header was read at. They are the commands of the Ctrl+Shift+C and Ctrl+Shift+J keys. +pub const DEV_TOOLS: &[(u16, u16, u32, u32)] = &[ + (150, 7871, 40023, 40005), + (151, 7922, 40023, 40005), + (152, 7977, 40023, 40005), + (153, 8010, 40023, 40005), + (154, 8037, 40023, 40005), + (155, 8059, 40023, 40005), + (156, 8078, 40023, 40005), + (157, 8103, 40023, 40005), + (158, 8127, 40023, 40005), + (159, 8154, 40023, 40005), +]; + +/// The paths of a row's values that are these command ids. A row generator never carries them: +/// it writes the value this table gives, or zero for a milestone it does not know. +pub const ROW_PATHS: &[&str] = &["toolbar.dev.inspect", "toolbar.dev.console"]; + +/// The inspect and console command ids of a Chromium milestone. +pub fn dev_tools(milestone: u16) -> Option<(u32, u32)> { + DEV_TOOLS + .iter() + .find(|(known, _, _, _)| *known == milestone) + .map(|(_, _, inspect, console)| (*inspect, *console)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fr11_developer_commands_come_from_chromium_command_ids() { + for milestone in 150..=159u16 { + assert_eq!(dev_tools(milestone), Some((40023, 40005)), "{milestone}"); + } + // An unread milestone never borrows a neighbour's value. + assert_eq!(dev_tools(149), None); + assert_eq!(dev_tools(160), None); + // Each milestone appears once, in branch order. + assert!(DEV_TOOLS + .windows(2) + .all(|pair| pair[0].0 + 1 == pair[1].0 && pair[0].1 < pair[1].1)); + } +} diff --git a/rivet/platform/windows/src/lib.rs b/rivet/platform/windows/src/lib.rs index 88c1962..81c550f 100644 --- a/rivet/platform/windows/src/lib.rs +++ b/rivet/platform/windows/src/lib.rs @@ -6,9 +6,11 @@ pub mod background; pub mod chrome_build; +pub mod command_ids; pub mod control; pub mod focus; pub mod hold; +pub mod row_features; pub mod row_port; pub mod row_recipe; pub mod row_resolve; diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs new file mode 100644 index 0000000..ede4daa --- /dev/null +++ b/rivet/platform/windows/src/row_features.rs @@ -0,0 +1,348 @@ +//! Which feature of a row each value belongs to, and how a row turns that feature off. +//! +//! A row value that could not be read from its own build must never reach a browser. When it +//! belongs to a feature the runtime can do without, the row turns that feature off and clears the +//! value, and the rest of the row can still ship once its checks pass. A value of a part the +//! window cannot do without (the frame and the page area layout) has no switch here, so it still +//! stops the row and the browser opens with Rivet's held build. +//! +//! The switches are the ones the runtime already obeys: a section's `supported` flag, an optional +//! part left `null`, an empty list of colour ids, and the frame colour's `provider_verified`. Each +//! one was checked against every reader of the values it covers, so a feature that is off reads +//! none of them. The same switches work in older runtimes, which read the same row fields. + +use serde_json::{json, Value}; + +/// The address a build records for what it does not have. +const ABSENT: &str = "0x7fff0000"; + +/// What turns a feature off in a row. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Off { + /// A `supported` or `provider_verified` flag set to false. + Flag(&'static str), + /// An optional part set to `null`. + Part(&'static str), +} + +/// What a value of a feature that is off becomes, so the row holds nothing of another build. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Clear { + /// Every number in it becomes zero, in the form it was written. + Zero, + /// The address the build does not have, which a reader takes as nothing there. + Absent, + /// An empty list. + Empty, +} + +/// A feature of a row and the values only it reads. +pub struct RowFeature { + /// The feature's name, as the runtime and the report give it. + pub name: &'static str, + /// Row paths of its values. A path that ends with `.` covers the whole section. + pub paths: &'static [&'static str], + pub off: &'static [Off], + pub clear: Clear, + /// The checks of `scripts/tests/windows-features.ps1` that need the feature. A row that has the + /// feature off is not expected to pass them. A prefix ending with `-` covers its family. + pub checks: &'static [&'static str], +} + +pub const ROW_FEATURES: &[RowFeature] = &[ + RowFeature { + name: "split view", + paths: &["split."], + off: &[Off::Flag("split.supported")], + clear: Clear::Zero, + checks: &["split", "split-"], + }, + RowFeature { + name: "vertical tabs", + paths: &[ + "vertical.update_collapse_action", + "vertical.browser_offset", + "vertical.mode_offset", + "vertical.width_offset", + ], + off: &[Off::Flag("vertical.supported")], + clear: Clear::Zero, + checks: &[], + }, + RowFeature { + name: "sidebar", + paths: &[ + "side_panel.color_source", + "side_panel.source_in_widget", + "side_panel.entry_count", + "side_panel.extension_entry", + "side_panel.features_coordinator", + "side_panel.features_offset", + ], + off: &[Off::Flag("side_panel.supported")], + clear: Clear::Zero, + checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], + }, + RowFeature { + name: "sidebar", + paths: &["side_panel.hidden_entries"], + off: &[Off::Flag("side_panel.supported")], + clear: Clear::Empty, + checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], + }, + RowFeature { + // Fields of the browser's layout object that only the Sidebar's part of the layout reads. + // The layout reads an absent field as no view. + name: "sidebar", + paths: &[ + "side_panel.side_panel", + "side_panel.side_panel_animation", + "side_panel.contents_outline", + "side_panel.vertical_tabs", + ], + off: &[Off::Flag("side_panel.supported")], + clear: Clear::Absent, + checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], + }, + RowFeature { + name: "app window", + paths: &["app_window."], + off: &[Off::Part("app_window")], + clear: Clear::Zero, + checks: &["mini-", "tab-moves"], + }, + RowFeature { + name: "address suggestions", + paths: &["omnibox."], + off: &[Off::Part("omnibox")], + clear: Clear::Zero, + checks: &["address-suggest", "security-chip"], + }, + RowFeature { + // An empty list is a build without developer colours, whose page keeps the browser's own. + name: "developer colours", + paths: &["toolbar.dev.colours"], + off: &[], + clear: Clear::Empty, + checks: &["dev-row"], + }, + RowFeature { + name: "frame colour", + paths: &["layout.frame_ids", "layout.caption_ink_ids"], + off: &[Off::Flag("layout.provider_verified")], + clear: Clear::Empty, + checks: &[], + }, +]; + +/// Values the runtime does not read while another value of the row says so: then they are not +/// values of the build at all, and a row holds zero for them. +pub struct UnusedWhen { + pub paths: &'static [&'static str], + /// The address that decides it. + pub address: &'static str, + /// Unused while that address is recorded, or while it is absent. + pub while_recorded: bool, + pub why: &'static str, +} + +pub const UNUSED_WHEN: &[UnusedWhen] = &[ + UnusedWhen { + paths: &["tabs.tab_collection", "tabs.tab_contents"], + address: "tabs.tab_at", + while_recorded: true, + why: "the build has its own GetWebContentsAt", + }, + UnusedWhen { + paths: &[ + "vertical.window_feature_tab_strip", + "vertical.window_feature_callers", + "vertical.toolbar_in_view", + "vertical.toolbar_leading", + ], + address: "vertical.window_feature", + while_recorded: false, + why: "the tab strip is left out through ShouldDrawTabStrip, not the window feature", + }, +]; + +/// The field a value path names: `layout.frame_ids[2]` names `layout.frame_ids`. +pub fn field_of(path: &str) -> &str { + path.split('[').next().unwrap_or(path) +} + +fn covers(rule: &str, path: &str) -> bool { + let field = field_of(path); + if rule.ends_with('.') { + field.starts_with(rule) + } else { + field == rule + } +} + +/// The feature a value belongs to, when the row can turn it off. +pub fn feature_of(path: &str) -> Option<&'static RowFeature> { + ROW_FEATURES + .iter() + .find(|feature| feature.paths.iter().any(|rule| covers(rule, path))) +} + +fn at<'a>(build: &'a Value, path: &str) -> Option<&'a Value> { + path.split('.').try_fold(build, |value, key| value.get(key)) +} + +fn at_mut<'a>(build: &'a mut Value, path: &str) -> Option<&'a mut Value> { + path.split('.').try_fold(build, |value, key| value.get_mut(key)) +} + +fn is_recorded(value: &Value) -> bool { + crate::row_recipe::number(value) + .is_some_and(|value| (0x10_0000..0x7FFF_0000).contains(&value)) +} + +/// Why the runtime does not read a value in this row, or `None` when it does. +pub fn unused(build: &Value, path: &str) -> Option<&'static str> { + UNUSED_WHEN + .iter() + .find(|rule| { + rule.paths.iter().any(|each| covers(each, path)) + && at(build, rule.address) + .is_some_and(|value| is_recorded(value) == rule.while_recorded) + }) + .map(|rule| rule.why) +} + +fn zero(value: &mut Value) { + if let Value::Array(items) = value { + items.iter_mut().for_each(zero); + return; + } + let cleared = match &*value { + Value::String(text) if text.starts_with("0x") => json!("0x0"), + Value::Number(_) => json!(0), + _ => return, + }; + *value = cleared; +} + +/// Clears the field a value path names, as `clear` says. +pub fn clear(build: &mut Value, path: &str, how: Clear) { + let Some(value) = at_mut(build, field_of(path)) else { + return; + }; + match how { + Clear::Zero => zero(value), + Clear::Absent => *value = json!(ABSENT), + Clear::Empty => *value = json!([]), + } +} + +/// Turns a feature off in a row's build part. +pub fn switch_off(build: &mut Value, feature: &RowFeature) { + for off in feature.off { + match *off { + Off::Flag(path) => { + if let Some(flag) = at_mut(build, path) { + *flag = json!(false); + } + } + Off::Part(name) => build[name] = Value::Null, + } + } +} + +/// The key of a row that names the features it has off and the values that turned them off. The +/// runtime reads only `frame` and `build`, so it changes nothing in a browser; the feature gate +/// reads it. +pub const SWITCHED_OFF: &str = "switched_off"; + +/// The feature checks a row's switched-off features excuse, by the names the row gives. +pub fn excused_checks(row: &Value) -> Vec<(&'static str, &'static str)> { + let names: Vec<&str> = row[SWITCHED_OFF] + .as_array() + .map_or(&[][..], Vec::as_slice) + .iter() + .filter_map(|entry| entry["feature"].as_str()) + .collect(); + let mut out = Vec::new(); + for feature in ROW_FEATURES + .iter() + .filter(|feature| names.contains(&feature.name)) + { + for check in feature.checks { + if !out.contains(&(feature.name, *check)) { + out.push((feature.name, *check)); + } + } + } + out +} + +/// The switched-off feature that excuses a feature check, if one does. +pub fn excuses(excused: &[(&'static str, &'static str)], check: &str) -> Option<&'static str> { + excused + .iter() + .find(|(_, rule)| { + if rule.ends_with('-') { + check.starts_with(rule) + } else { + check == *rule + } + }) + .map(|(name, _)| *name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nfr6_every_row_value_of_a_feature_has_one_switch() { + assert_eq!(feature_of("split.view_size").unwrap().name, "split view"); + assert_eq!(feature_of("toolbar.dev.colours[3][0]").unwrap().name, "developer colours"); + assert_eq!(feature_of("layout.frame_ids[1]").unwrap().name, "frame colour"); + assert_eq!(feature_of("omnibox.match_size").unwrap().name, "address suggestions"); + // The frame and the page area layout have no switch: the window cannot do without them. + for core in [ + "layout.view_bounds_offset", + "layout.frame_browser_window_offset", + "side_panel.page_area", + "side_panel.host_view", + "side_panel.contents_container", + "side_panel.toolbar", + "toolbar.get_widget_slot", + ] { + assert!(feature_of(core).is_none(), "{core}"); + } + // A value that only looks like a section's name is not in it. + assert!(feature_of("splitter.width").is_none()); + } + + #[test] + fn nfr6_a_value_the_runtime_does_not_read_is_not_a_value_of_the_build() { + let build = json!({ + "tabs": {"tab_at": "0x326a00", "tab_collection": "0x30"}, + "vertical": {"window_feature": "0x7fff0000", "window_feature_callers": ["0x0", "0x0"]}, + }); + assert!(unused(&build, "tabs.tab_collection").is_some()); + assert!(unused(&build, "vertical.window_feature_callers[1]").is_some()); + let build = json!({ + "tabs": {"tab_at": "0x7fff0000"}, + "vertical": {"window_feature": "0x1234560"}, + }); + assert!(unused(&build, "tabs.tab_collection").is_none()); + assert!(unused(&build, "vertical.toolbar_in_view").is_none()); + } + + #[test] + fn nfr6_a_switched_off_feature_excuses_only_its_own_checks() { + let row = json!({"switched_off": [{"feature": "split view"}, {"feature": "developer colours"}]}); + let excused = excused_checks(&row); + assert_eq!(excuses(&excused, "split-grid-4"), Some("split view")); + assert_eq!(excuses(&excused, "split"), Some("split view")); + assert_eq!(excuses(&excused, "dev-row"), Some("developer colours")); + assert_eq!(excuses(&excused, "sidebar"), None); + assert_eq!(excuses(&excused, "bar-layout"), None); + assert!(excused_checks(&json!({})).is_empty()); + } +} diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 79487ee..c458378 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -71,6 +71,20 @@ pub struct PortReport { pub fingerprinted: Vec, /// Values that are Rivet's settings rather than facts about the build, kept from the prior row. pub settings: Vec, + /// Features this row turns off, each with the values that could not be read for it. The row + /// clears those values, so none of the prior build reaches a browser. + pub switched_off: Vec, + /// Values the runtime does not read in this row, written as zero, with the reason. + pub unused: Vec, + /// Whether every carried value must be settled: the milestone changed, or values were read. + #[serde(skip)] + must_check: bool, + /// The milestone change, when there is one and nothing read the carried values. + #[serde(skip)] + milestone: Option, + /// Why each value that was tried could not be read. + #[serde(skip)] + unread: BTreeMap, } fn is_address(value: u64) -> bool { @@ -986,7 +1000,78 @@ pub fn port_row( let targets = addresses_of(&row); report.addresses = targets.len(); port_by_name(prior, &row, named, new, &targets, &mut moved, &mut report); - finish_row(row, &moved, new.pe, report) + let (mut row, mut report) = finish_row(row, &moved, new.pe, report); + settle_carried(&mut row, &mut report); + (row, report) +} + +/// Settles each value no recipe or instruction read from the new build. A value the runtime does +/// not read in this row is written as zero. A value of a feature the runtime can do without turns +/// that feature off for this build and is cleared, so the rest of the row is not held back by it. +/// Any other value stops the row with its reason, since no feature may run on a value of another +/// build. +fn settle_carried(row: &mut Value, report: &mut PortReport) { + use crate::row_features::{self, Clear, RowFeature}; + report + .derived + .extend(crate::row_recipe::follow(&mut row["build"])); + if !report.must_check { + return; + } + let mut left = Vec::new(); + let mut off: BTreeMap<&'static str, (&'static RowFeature, Vec)> = BTreeMap::new(); + for path in std::mem::take(&mut report.carried) { + if let Some(why) = row_features::unused(&row["build"], &path) { + row_features::clear(&mut row["build"], &path, Clear::Zero); + report.unused.push(format!("{path}: {why}")); + report.unread.remove(&path); + } else if let Some(feature) = row_features::feature_of(&path) { + row_features::clear(&mut row["build"], &path, feature.clear); + off.entry(feature.name) + .or_insert((feature, Vec::new())) + .1 + .push(path); + } else { + left.push(path); + } + } + let mut entries = Vec::new(); + for (name, (feature, paths)) in off { + row_features::switch_off(&mut row["build"], feature); + let reasons: Vec = paths + .iter() + .map(|path| match report.unread.remove(path) { + Some(reason) => format!("{path} {reason}"), + None => format!("{path} has no recipe"), + }) + .collect(); + report + .switched_off + .push(format!("{name} is off: {}", reasons.join("; "))); + entries.push(json!({"feature": name, "values": paths})); + } + if !entries.is_empty() { + row[row_features::SWITCHED_OFF] = json!(entries); + } + let mut unchecked = Vec::new(); + for path in &left { + match report.unread.remove(path) { + Some(reason) => report.review.push(format!("{path} {reason}")), + None => unchecked.push(path.clone()), + } + } + if !unchecked.is_empty() { + let head = report + .milestone + .clone() + .unwrap_or_else(|| "values were not read".to_owned()); + report.review.push(format!( + "{head}: {} values have no recipe and were carried over unchecked: {}", + unchecked.len(), + unchecked.join(", ") + )); + } + report.carried = left; } /// A copy of the prior row with the new version, and frame addresses in the `0x` form. `carries` @@ -1020,13 +1105,14 @@ fn begin_row(prior: &Value, version: &str, carries: bool) -> (Value, PortReport) .review .push(format!("{} is not a four part version", version)); } + write_command_ids(&mut row, version, &mut report); report.carried = crate::row_recipe::without_recipe(&prior["build"]); report.settings = crate::row_recipe::settings(&prior["build"]); - if carries && prior_version.split('.').next() != version.split('.').next() { - report.review.push(format!( - "the milestone changed from {prior_version} to {version}: {} values have no recipe and were carried over unchecked: {}", - report.carried.len(), - report.carried.join(", ") + let milestone_changed = prior_version.split('.').next() != version.split('.').next(); + report.must_check = !carries || milestone_changed; + if carries && milestone_changed { + report.milestone = Some(format!( + "the milestone changed from {prior_version} to {version}" )); } row["build"]["version"] = json!(parts); @@ -1037,6 +1123,42 @@ fn begin_row(prior: &Value, version: &str, carries: bool) -> (Value, PortReport) (row, report) } +/// Writes Chromium's public command ids into a row from the table read from Chromium's source, +/// for runtimes that still read them from the row. They are never carried from the prior row: a +/// milestone the table does not know gets zero, which offers no command. A prior row with zero +/// never had the developer bar checked, so it keeps zero. +fn write_command_ids(row: &mut Value, version: &str, report: &mut PortReport) { + let browser = row["build"]["browser"].as_str().unwrap_or_default(); + // Chrome, Edge and Brave carry their Chromium milestone as the first part of their version. + let milestone = matches!(browser, "Google Chrome" | "Microsoft Edge" | "Brave") + .then(|| version.split('.').next()?.parse::().ok()) + .flatten(); + let ids = milestone.and_then(crate::command_ids::dev_tools); + let Some(dev) = row["build"]["toolbar"]["dev"].as_object_mut() else { + return; + }; + for (key, id) in [ + ("inspect", ids.map(|ids| ids.0)), + ("console", ids.map(|ids| ids.1)), + ] { + let Some(prior) = dev.get(key).and_then(Value::as_u64) else { + continue; + }; + let value = if prior == 0 { 0 } else { id.unwrap_or(0) }; + dev.insert(key.to_owned(), json!(value)); + report.derived.push(match (prior == 0, id) { + (true, _) => format!("toolbar.dev.{key}: 0, the prior row offers no developer bar"), + (false, Some(id)) => format!( + "toolbar.dev.{key}: {id}, from chrome_command_ids.h at Chromium {}", + milestone.unwrap_or_default() + ), + (false, None) => format!( + "toolbar.dev.{key}: 0, no command id is read for this build's Chromium milestone" + ), + }); + } +} + /// Finds each address of a row through the public names of both builds. fn port_by_name( prior: &Value, @@ -1522,6 +1644,7 @@ pub fn find_candidate( if let Some(prior_pe) = prior_pe { read_carried(prior, &mut row, &moved, &followed, prior_pe, pe, &mut report); } + settle_carried(&mut row, &mut report); (row, report) } @@ -1552,8 +1675,8 @@ fn value_at_mut<'a>(value: &'a mut Value, path: &str) -> Option<&'a mut Value> { /// Reads each value the recipes leave, a member offset, slot, size or id, from the instructions /// that use it in the prior build's functions and the same instructions in the new build. A value -/// that cannot be read keeps a review line with the reason and stays listed as carried, so the row -/// is never published with a value of the prior build. +/// that cannot be read keeps its reason and stays listed as carried, and `settle_carried` decides +/// what it does to the row, so the row is never published with a value of the prior build. fn read_carried( prior: &Value, row: &mut Value, @@ -1621,18 +1744,19 @@ fn read_carried( }); } Err(reason) => { - report.review.push(format!( - "{} was not read from the new build: {reason}", - reading.path - )); + report.unread.insert( + reading.path.clone(), + format!("was not read from the new build: {reason}"), + ); report.carried.push(reading.path); } } } for path in unreadable { - report - .review - .push(format!("{path} is not a number this generator can read")); + report.unread.insert( + path.clone(), + "is not a number this generator can read".to_owned(), + ); report.carried.push(path); } } @@ -2123,6 +2247,111 @@ mod tests { ); } + #[test] + fn nfr6_a_command_id_is_not_a_row_value() { + let mut prior = prior(); + prior["build"]["browser"] = json!("Google Chrome"); + prior["frame"]["version"] = json!("157.0.8103.39"); + // A wrong prior value shows that the new row does not copy it. + prior["build"]["toolbar"]["dev"] = json!({"inspect": 1, "console": 2, "colours": []}); + let code = new_code(); + let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "158.0.8127.36"); + assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 40023); + assert_eq!(row["build"]["toolbar"]["dev"]["console"], 40005); + assert!( + !report.carried.iter().any(|path| path.starts_with("toolbar.dev.inspect") + || path.starts_with("toolbar.dev.console")), + "{:?}", + report.carried + ); + let milestone = report + .review + .iter() + .find(|line| line.contains("milestone")) + .expect("the other values still cross the milestone"); + assert!(!milestone.contains("toolbar.dev.console"), "{milestone}"); + // A milestone whose header was not read offers no command rather than the prior one. + let (row, _) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "199.0.1.1"); + assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 0); + // A row that never offered the developer bar keeps offering none. + prior["build"]["toolbar"]["dev"] = json!({"inspect": 0, "console": 0, "colours": []}); + let (row, _) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "158.0.8127.36"); + assert_eq!(row["build"]["toolbar"]["dev"]["console"], 0); + } + + /// A prior row whose values that are not addresses all belong to features the runtime can do + /// without, or are not read in this row. + fn prior_with_features() -> Value { + let mut prior = prior(); + let toolbar = prior["build"]["toolbar"].as_object_mut().unwrap(); + toolbar.remove("view_layer"); + toolbar.remove("colours"); + toolbar.insert( + "dev".to_owned(), + json!({"colours": [[321, 4280953905u32], [1597, 0]]}), + ); + prior["build"]["split"] = json!({"supported": true, "outline_member": "0x40"}); + prior["build"]["omnibox"] = json!({"match_size": "0x820"}); + prior["build"]["tabs"]["tab_at"] = json!("0x200300"); + prior["build"]["tabs"]["tab_collection"] = json!("0x30"); + prior + } + + #[test] + fn nfr6_a_feature_with_an_unread_value_is_off_for_that_build() { + let code = new_code(); + let (row, report) = port(&prior_with_features(), NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + // Nothing holds the rest of the row back. + assert_eq!(report.review, Vec::::new()); + assert!(report.carried.is_empty(), "{:?}", report.carried); + let build = &row["build"]; + // Each feature with a value of the prior build is off, and the value is gone. + assert_eq!(build["split"]["supported"], false); + assert_eq!(build["split"]["outline_member"], "0x0"); + assert!(build["omnibox"].is_null()); + assert_eq!(build["toolbar"]["dev"]["colours"], json!([])); + let off: Vec<&str> = row[crate::row_features::SWITCHED_OFF] + .as_array() + .unwrap() + .iter() + .map(|entry| entry["feature"].as_str().unwrap()) + .collect(); + assert_eq!(off, ["address suggestions", "developer colours", "split view"]); + assert_eq!(report.switched_off.len(), 3, "{:?}", report.switched_off); + // A value this build does not use is written as zero, and no feature goes off for it. + assert_eq!(build["tabs"]["tab_collection"], "0x0"); + assert_eq!(report.unused.len(), 1, "{:?}", report.unused); + // The addresses of the row still move to the new build. + assert_eq!(build["tabs"]["tab_at"], "0x101300"); + } + + #[test] + fn nfr6_a_value_the_window_cannot_do_without_still_stops_the_row() { + let mut prior = prior_with_features(); + prior["build"]["layout"] = json!({"view_bounds_offset": "0x1c8"}); + let code = new_code(); + let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + assert_eq!(report.carried, ["layout.view_bounds_offset"]); + assert!( + report.review.iter().any(|line| line.contains("milestone") + && line.ends_with("carried over unchecked: layout.view_bounds_offset")), + "{:?}", + report.review + ); + // The features it could do without are still off. + assert_eq!(row["build"]["split"]["supported"], false); + } + + #[test] + fn nfr6_a_row_within_its_milestone_turns_nothing_off() { + let code = new_code(); + let (row, report) = port(&prior_with_features(), NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); + assert_eq!(report.review, Vec::::new()); + assert!(report.switched_off.is_empty()); + assert_eq!(row["build"]["split"]["supported"], true); + assert!(row.get(crate::row_features::SWITCHED_OFF).is_none()); + } + #[test] fn nfr3_a_row_that_crosses_a_milestone_stops_for_review() { let code = new_code(); diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index a14d276..a65f945 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -415,9 +415,51 @@ pub fn derive_row(build: &mut Value, pe: &PeFile) -> Derived { derived } +/// Values that follow from another value of the row by the member order of a public Chromium +/// class, as (path, the value it follows, the distance). `ui/views/view.h` declares `parent_`, +/// then `children_`, then the members up to `bounds_`, 0x30 bytes after `parent_`. The runtime +/// takes them the same way, so they are written from the value they follow and never carried. +pub const FOLLOWS: &[(&str, &str, i64)] = &[ + ("app_window.view_parent", "layout.view_bounds_offset", -0x30), + ("app_window.view_children", "layout.view_bounds_offset", -0x28), +]; + +/// Writes each value of `FOLLOWS` the row has from the value it follows. +pub fn follow(build: &mut Value) -> Vec { + let mut read = Vec::new(); + for (path, from, by) in FOLLOWS { + let Some(base) = number(at_path(build, from)).filter(|base| *base >= 0x30) else { + continue; + }; + let (parent, key) = path.split_once('.').expect("a path has a parent"); + let Some(old) = number(&build[parent][key]) else { + continue; + }; + let value = (base as i64 + by) as u64; + let is_string = build[parent][key].is_string(); + build[parent][key] = if is_string { + Value::String(format!("{value:#x}")) + } else { + json!(value) + }; + read.push(if old == value { + format!("{path}: {value:#x}, from {from}") + } else { + format!("{path}: {old:#x} -> {value:#x}, from {from}") + }); + } + read +} + /// Values Rivet chooses rather than reads from a build, such as how long it waits before it opens -/// a new tab. The row carries them for the runtime, so they are kept from the prior row. -pub const SETTINGS: &[&str] = &["tabs.new_tab_delay_ms"]; +/// a new tab, how far its toolbar starts after the browser view's edge to leave room for Rivet's +/// toggle button, and the DIPs it adds to the top inset it reports. The row carries them for the +/// runtime, so they are kept from the prior row. +pub const SETTINGS: &[&str] = &[ + "tabs.new_tab_delay_ms", + "vertical.toolbar_leading", + "layout.top_inset_adjust", +]; /// Lists of `[id, colour]` pairs: the id is a value of the build, and the colour is Rivet's choice. pub const ID_COLOUR_PAIRS: &[&str] = &["toolbar.dev.colours"]; @@ -438,7 +480,8 @@ pub fn settings(build: &Value) -> Vec { } /// Every number of a row below the address range that no recipe reads: member offsets, slots, -/// sizes, ids and constants that a port can only carry over. Rivet's own settings are not listed. +/// sizes, ids and constants that a port can only carry over. Rivet's own settings and Chromium's +/// public command ids are not listed. pub fn without_recipe(build: &Value) -> Vec { fn walk(path: &str, value: &Value, out: &mut Vec) { match value { @@ -492,6 +535,8 @@ pub fn without_recipe(build: &Value) -> Vec { && !path.starts_with("version[") && !FIELDS.iter().any(|field| field.path == path) && !SETTINGS.contains(&path.as_str()) + && !crate::command_ids::ROW_PATHS.contains(&path.as_str()) + && !FOLLOWS.iter().any(|(follows, _, _)| follows == path) }); out } @@ -671,6 +716,23 @@ mod tests { ); } + #[test] + fn nfr6_a_views_parent_and_children_follow_its_bounds() { + let mut build = json!({ + "layout": {"view_bounds_offset": "0x1c0"}, + "app_window": {"view_parent": "0x198", "view_children": "0x1a0"}, + }); + assert_eq!(without_recipe(&build), vec!["layout.view_bounds_offset"]); + let read = follow(&mut build); + assert_eq!(build["app_window"]["view_parent"], "0x190"); + assert_eq!(build["app_window"]["view_children"], "0x198"); + assert_eq!(read.len(), 2, "{read:?}"); + // A row without the app window part gets none. + let mut bare = json!({"layout": {"view_bounds_offset": "0x1c8"}, "app_window": null}); + assert!(follow(&mut bare).is_empty()); + assert!(bare["app_window"].is_null()); + } + #[test] fn nfr6_rivet_settings_are_not_values_of_the_build() { let build = json!({ @@ -682,10 +744,18 @@ mod tests { vec![ "tabs.tab_contents", "toolbar.dev.colours[0][0]", - "toolbar.dev.colours[1][0]", - "toolbar.dev.console" + "toolbar.dev.colours[1][0]" ] ); + let chosen = json!({ + "vertical": {"toolbar_leading": 26, "toolbar_in_view": "0x60"}, + "layout": {"top_inset_adjust": 0}, + }); + assert_eq!(without_recipe(&chosen), vec!["vertical.toolbar_in_view"]); + assert_eq!( + settings(&chosen), + vec!["vertical.toolbar_leading", "layout.top_inset_adjust"] + ); assert_eq!( settings(&build), vec![ diff --git a/rivet/platform/windows/src/row_watch.rs b/rivet/platform/windows/src/row_watch.rs index c960533..842f084 100644 --- a/rivet/platform/windows/src/row_watch.rs +++ b/rivet/platform/windows/src/row_watch.rs @@ -299,6 +299,18 @@ pub fn test_desktop_limits(browser: &str) -> Vec<(String, String)> { /// notes name each feature left undriven by the test desktop, and a listed feature that now /// passes, so the list is looked at again. pub fn publish_gate(results: &Value, browser: &str) -> Result, Vec> { + publish_gate_for_row(results, browser, &Value::Null) +} + +/// `publish_gate` for the row being published. A check of a feature the row turns off for its +/// build is not expected to pass: the row ships with that feature off, and a note names it. Every +/// other check must still pass. +pub fn publish_gate_for_row( + results: &Value, + browser: &str, + row: &Value, +) -> Result, Vec> { + let excused = crate::row_features::excused_checks(row); let rows: Vec<&Value> = match results { Value::Array(rows) => rows.iter().collect(), // ConvertTo-Json writes a single row as an object. @@ -326,6 +338,10 @@ pub fn publish_gate(results: &Value, browser: &str) -> Result, Vec reasons.push(format!("{feature}: not run")), @@ -531,6 +547,26 @@ mod tests { .collect() } + #[test] + fn nfr6_a_feature_off_in_the_row_does_not_hold_back_the_rest() { + let mut rows = all_pass("chrome"); + for row in rows.iter_mut().filter(|row| row.1.starts_with("split")) { + row.2 = "FAIL"; + } + // Without the row, the failed split checks keep the browser off the list. + assert!(publish_gate(&results(&rows), "chrome").is_err()); + let row = json!({"switched_off": [{"feature": "split view", "values": ["split.outline_member"]}]}); + let notes = publish_gate_for_row(&results(&rows), "chrome", &row).unwrap(); + assert!(notes + .iter() + .any(|note| note == "split-grid-4: split view is off in this build's row")); + // Another feature that fails still keeps it off. + let sidebar = rows.iter().position(|row| row.1 == "sidebar").unwrap(); + rows[sidebar].2 = "FAIL"; + let reasons = publish_gate_for_row(&results(&rows), "chrome", &row).unwrap_err(); + assert_eq!(reasons, ["sidebar: FAIL"]); + } + #[test] fn nfr3_a_browser_that_passed_every_feature_is_published() { assert!(publish_gate(&results(&all_pass("chrome")), "Chrome").is_ok()); diff --git a/rivet/runtime/windows/src/browsers/chromium/commands.rs b/rivet/runtime/windows/src/browsers/chromium/commands.rs index 05041b7..4ada104 100644 --- a/rivet/runtime/windows/src/browsers/chromium/commands.rs +++ b/rivet/runtime/windows/src/browsers/chromium/commands.rs @@ -36,6 +36,15 @@ pub(crate) fn chromium_milestone(browser: &str, version: [u16; 4]) -> Option (u32, u32) { + chromium_milestone(browser, version) + .and_then(rivet_platform_windows::command_ids::dev_tools) + .unwrap_or((0, 0)) +} + /// Whether a browser keeps Chromium's command ids without public source to confirm it. Brave /// publishes its changes and adds its own ids only from 56000, so it keeps Chromium's. Edge, Whale /// and Samsung Internet take the value of their Chromium milestone, which needs a regression check @@ -150,6 +159,16 @@ mod tests { assert!(move_tab_to_new_window("Opera", [130, 0, 1, 1]).is_err()); } + #[test] + fn nfr6_a_command_id_is_not_a_row_value() { + // The developer commands follow the build's Chromium milestone, whatever its row holds. + assert_eq!(dev_tools("Google Chrome", [159, 0, 8154, 6]), (40023, 40005)); + assert_eq!(dev_tools("Microsoft Edge", [157, 0, 4341, 46]), (40023, 40005)); + // A milestone whose header was not read offers no command. + assert_eq!(dev_tools("Google Chrome", [149, 0, 1, 1]), (0, 0)); + assert_eq!(dev_tools("Samsung Internet", [30, 0, 4, 29]), (0, 0)); + } + #[test] fn fr9_browsers_without_public_command_ids_need_a_regression_check() { assert!(!needs_regression_check("Google Chrome")); diff --git a/rivet/runtime/windows/src/builds/chrome.rs b/rivet/runtime/windows/src/builds/chrome.rs index 81e0e5d..74fcc3c 100644 --- a/rivet/runtime/windows/src/builds/chrome.rs +++ b/rivet/runtime/windows/src/builds/chrome.rs @@ -3,8 +3,6 @@ use super::*; pub(super) const DEV_CHROME_156: DevMode = DevMode { - inspect: 40023, - console: 40005, colours: &[ (0x13C, DEV_GROUND), (1590, DEV_GROUND), diff --git a/rivet/runtime/windows/src/builds/mod.rs b/rivet/runtime/windows/src/builds/mod.rs index b5335aa..a96bcb5 100644 --- a/rivet/runtime/windows/src/builds/mod.rs +++ b/rivet/runtime/windows/src/builds/mod.rs @@ -139,7 +139,9 @@ pub struct AppWindow { pub detach_prologue: &'static [u8], pub insert: Option, pub insert_prologue: &'static [u8], - /// A `views::View` keeps its parent at this offset and its children vector right after it. + /// A `views::View` keeps its parent at this offset and its children vector right after it. Kept + /// for runtimes that read them from the row; this runtime takes both from the layout's bounds + /// offset, by the member order of `views::View`. pub view_parent: usize, pub view_children: usize, /// `operator new(size)`, `views::WebView::WebView(this, context)` and the object's size. @@ -618,13 +620,10 @@ pub struct Layout { row_struct! { /// What a build needs to show a page in developer mode. pub struct DevMode { - /// The browser's own commands the developer bar runs, as `WM_COMMAND` ids, or zero when the build - /// has none. They are the commands of the Ctrl+Shift+C and Ctrl+Shift+J keys, read from the - /// browser's accelerator table. - pub inspect: u32, - pub console: u32, /// Colour ids of this build and the colours the row takes in developer mode, as `0xAARRGGBB`. /// An id that `colours` does not hold is asked of the provider first, like the ones that it does. + /// A build with no colours has no developer bar. The bar's browser commands are Chromium's + /// public command ids, which come from `browsers::chromium::commands`, not from the row. pub colours: &'static [(i32, u32)], /// `gfx::Font::Font(this, &name, size)` and `gfx::FontList::FontList(this, &font)`, which build /// the monospace font of the address. A build without them keeps the address in its own font. @@ -636,8 +635,6 @@ pub struct DevMode { } const UNCHECKED_DEV: DevMode = DevMode { - inspect: 0, - console: 0, colours: &[], font_new: ABSENT, font_new_prologue: &[0], diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index d1d3757..e84ce43 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -633,11 +633,16 @@ fn fr3_a_build_with_tabs_checks_only_functions_it_has() { #[test] fn fr11_developer_commands_are_those_of_the_devtools_keys() { for build in [&CHROME, &EDGE, &BRAVE, &BRAVE_63] { - let dev = &build.toolbar.dev; - assert_eq!((dev.console, dev.inspect), (40005, 40023)); + assert!(!build.toolbar.dev.colours.is_empty()); + assert_eq!( + crate::features::dev_page::dev_commands(build), + (40023, 40005) + ); } // A build that was never checked offers no command and no bar. - assert_eq!(UNCHECKED_TOOLBAR.dev.inspect, 0); + for build in [&WHALE, &SAMSUNG, &CHROME_150] { + assert_eq!(crate::features::dev_page::dev_commands(build), (0, 0)); + } } #[test] @@ -911,8 +916,6 @@ fn fr13_every_build_that_shows_a_second_view_records_the_same_chromium_functions "size", "add_child", "set_contents", - "vparent", - "vchildren", "dtor_slot", ] { assert!( @@ -1632,3 +1635,32 @@ fn nfr6_a_table_row_carries_the_page_tools_and_bubble_anchor_of_its_prior_row() )) ); } + +/// The parent and children of a view follow from its bounds by the member order of `views::View`. +/// Every row that recorded them by hand agrees, so the rule replaces them. +#[test] +fn nfr6_a_views_parent_and_children_are_not_row_values() { + let mut seen = 0; + for build in compiled() { + let Some(row) = build.app_window.as_ref() else { + continue; + }; + assert_eq!( + crate::features::app_window::view_fields(build), + Some((row.view_parent, row.view_children)), + "{} {:?}", + build.browser, + build.version + ); + seen += 1; + } + assert!(seen >= 5, "{seen}"); + // A row the bounds offset of which moves gives the parent and children of that build. + let mut moved = crate::row_data::RowValue::to_row(&CHROME_157_38); + moved["layout"]["view_bounds_offset"] = serde_json::json!("0x1d0"); + let moved = ::from_row(&moved).unwrap(); + assert_eq!( + crate::features::app_window::view_fields(&moved), + Some((0x1A0, 0x1A8)) + ); +} diff --git a/rivet/runtime/windows/src/chromium/view.rs b/rivet/runtime/windows/src/chromium/view.rs index 3e3faa7..49621fd 100644 --- a/rivet/runtime/windows/src/chromium/view.rs +++ b/rivet/runtime/windows/src/chromium/view.rs @@ -24,6 +24,13 @@ impl View { (bounds_offset >= 0x30).then(|| bounds_offset - 0x30) } + /// Where a view keeps its children, from where it keeps its parent: `children_`, a + /// `std::vector` of views, comes right after `parent_` in `ui/views/view.h`. The view walk of + /// `reflect` finds the same pair at run time, each child naming the view 8 bytes before its list. + pub(crate) const fn children_offset(parent_offset: usize) -> usize { + parent_offset + 8 + } + pub(crate) const fn at(address: usize) -> Self { Self(address) } diff --git a/rivet/runtime/windows/src/features/app_window.rs b/rivet/runtime/windows/src/features/app_window.rs index 87dd96e..da9220d 100644 --- a/rivet/runtime/windows/src/features/app_window.rs +++ b/rivet/runtime/windows/src/features/app_window.rs @@ -12,7 +12,22 @@ use crate::builds::AppWindow; /// An address or value of the app window, as an RVA of the browser module where it is a function. pub(crate) fn recorded(name: &str) -> Option { - switched(name).or_else(|| checked_row().and_then(|row| row_value(row, name))) + switched(name).or_else(|| match name { + "vparent" | "vchildren" => { + checked_row()?; + let (parent, children) = view_fields(crate::builds::current()?)?; + Some(if name == "vparent" { parent } else { children }) + } + _ => checked_row().and_then(|row| row_value(row, name)), + }) +} + +/// Where a view of `build` keeps its parent and its children. They follow from where it keeps its +/// bounds by the member order of `views::View`, so they are not values of the build's row. +pub(crate) fn view_fields(build: &crate::builds::Build) -> Option<(usize, usize)> { + use crate::chromium::view::View; + let parent = View::parent_offset(build.layout.view_bounds_offset)?; + Some((parent, View::children_offset(parent))) } /// A value named in the test profile's `rivet-spike.txt`. @@ -121,8 +136,6 @@ pub(crate) fn row_value(row: &AppWindow, name: &str) -> Option { "kind" => Some(row.browser_type), "detach" => row.detach, "insert" => row.insert, - "vparent" => Some(row.view_parent), - "vchildren" => Some(row.view_children), "new" => Some(row.operator_new), "ctor" => Some(row.web_view_ctor), "size" => Some(row.web_view_size), diff --git a/rivet/runtime/windows/src/features/dev_page.rs b/rivet/runtime/windows/src/features/dev_page.rs index 54c12c1..084df23 100644 --- a/rivet/runtime/windows/src/features/dev_page.rs +++ b/rivet/runtime/windows/src/features/dev_page.rs @@ -47,18 +47,28 @@ pub(crate) unsafe fn toggle_dev_mode(window: HWND) -> bool { /// The buttons the developer bar of this build offers, with the command each runs. pub(crate) fn dev_actions() -> Vec<(Action, u32)> { - let dev = &crate::builds::get().toolbar.dev; + let (inspect, console) = dev_commands(crate::builds::get()); // Chromium has no browser command that opens DevTools on its Network or Performance panel. // Rivet opens them itself through Chromium's DevTools functions where the build records them. let panels = panel_buttons(crate::features::dev_tools::available()); crate::dev_mode::bar_buttons(&[ - (Action::Inspect, dev.inspect), - (Action::Console, dev.console), + (Action::Inspect, inspect), + (Action::Console, console), (Action::Network, panels), (Action::Performance, panels), ]) } +/// The inspect and console commands the developer bar of `build` runs, or zero for each. They are +/// Chromium's public command ids for the build's milestone. Only a build whose developer colours +/// were checked has the bar at all. +pub(crate) fn dev_commands(build: &crate::builds::Build) -> (u32, u32) { + if build.toolbar.dev.colours.is_empty() { + return (0, 0); + } + crate::browsers::chromium::commands::dev_tools(build.browser, build.version) +} + /// The marker the Network and Performance buttons carry when Rivet can open their panels. Rivet /// runs them itself, so it is never sent to the browser as a command. pub(crate) const PANEL_BUTTON: u32 = u32::MAX; From e58d2e3079739b9a369f8a50baee2cdb37f4b03d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:01:03 +0000 Subject: [PATCH 03/29] Publish: develop c4bcaa9 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_features.rs | 68 +- rivet/platform/windows/src/row_port.rs | 41 +- .../windows/src/browsers/chromium/layout.rs | 18 +- .../windows/src/browsers/chromium/split.rs | 4 +- rivet/runtime/windows/src/builds/brave.rs | 30 +- rivet/runtime/windows/src/builds/chrome.rs | 42 +- rivet/runtime/windows/src/builds/edge.rs | 10 +- rivet/runtime/windows/src/builds/mod.rs | 31 +- rivet/runtime/windows/src/builds/samsung.rs | 6 +- rivet/runtime/windows/src/builds/tests.rs | 6 +- rivet/runtime/windows/src/builds/whale.rs | 8 +- rivet/runtime/windows/src/chromium/mod.rs | 1 + rivet/runtime/windows/src/chromium/reflect.rs | 16 + .../windows/src/chromium/window_views.rs | 674 ++++++++++++++++++ .../windows/src/features/address_bar.rs | 2 +- .../windows/src/features/app_window.rs | 38 +- .../windows/src/features/frame_layout.rs | 11 +- .../windows/src/features/pane_infobar.rs | 3 +- .../windows/src/features/side_panel.rs | 35 +- .../windows/src/features/sidebar_page.rs | 4 +- rivet/runtime/windows/src/features/widgets.rs | 21 +- rivet/runtime/windows/src/frame.rs | 2 + rivet/runtime/windows/src/hooks/page_area.rs | 30 +- rivet/runtime/windows/src/row_data.rs | 31 +- 24 files changed, 995 insertions(+), 137 deletions(-) create mode 100644 rivet/runtime/windows/src/chromium/window_views.rs diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs index ede4daa..bfdbac9 100644 --- a/rivet/platform/windows/src/row_features.rs +++ b/rivet/platform/windows/src/row_features.rs @@ -135,6 +135,44 @@ pub const ROW_FEATURES: &[RowFeature] = &[ }, ]; +/// Values the runtime finds in the browser's own memory by Chromium's class names and the shape of +/// the view tree, so a row needs none of them. Where a row has one, the runtime only compares it +/// with what it found. A value no instruction of the new build gave is left out of the row rather +/// than carried from the prior build, and does not stop the row: the browser view, the area below +/// the top row and the view of the pages are the layout's views named `BrowserView`, +/// `MainBackgroundRegionView` and `MultiContentsView`; the frame view's field is the one that holds +/// that same browser view; and a view's widget is the one the root of its view tree names. A +/// runtime from before this cannot read a row without them, so it refuses the row and opens its +/// held build instead of guessing. +pub const REFLECTED: &[&str] = &[ + "layout.frame_browser_window_offset", + "side_panel.contents_container", + "side_panel.host_view", + "side_panel.page_area", + "toolbar.get_widget_slot", +]; + +/// Whether the runtime finds a value by reflection, so a row may leave it out. +pub fn is_reflected(path: &str) -> bool { + REFLECTED.contains(&field_of(path)) +} + +/// Leaves the field a value path names out of a row's build part. +pub fn leave_out(build: &mut Value, path: &str) { + let field = field_of(path); + let (parent, key) = match field.rsplit_once('.') { + Some((parent, key)) => (Some(parent), key), + None => (None, field), + }; + let holder = match parent { + Some(parent) => at_mut(build, parent), + None => Some(build), + }; + if let Some(object) = holder.and_then(Value::as_object_mut) { + object.remove(key); + } +} + /// Values the runtime does not read while another value of the row says so: then they are not /// values of the build at all, and a row holds zero for them. pub struct UnusedWhen { @@ -303,21 +341,33 @@ mod tests { assert_eq!(feature_of("layout.frame_ids[1]").unwrap().name, "frame colour"); assert_eq!(feature_of("omnibox.match_size").unwrap().name, "address suggestions"); // The frame and the page area layout have no switch: the window cannot do without them. - for core in [ - "layout.view_bounds_offset", - "layout.frame_browser_window_offset", - "side_panel.page_area", - "side_panel.host_view", - "side_panel.contents_container", - "side_panel.toolbar", - "toolbar.get_widget_slot", - ] { + for core in ["layout.view_bounds_offset", "side_panel.toolbar"] { assert!(feature_of(core).is_none(), "{core}"); + assert!(!is_reflected(core), "{core}"); + } + // The window's views and widget have no switch either; the runtime finds them itself. + for reflected in REFLECTED { + assert!(feature_of(reflected).is_none(), "{reflected}"); + assert!(is_reflected(reflected), "{reflected}"); } // A value that only looks like a section's name is not in it. assert!(feature_of("splitter.width").is_none()); } + #[test] + fn nfr6_a_reflected_value_is_left_out_of_the_row() { + let mut build = json!({ + "layout": {"frame_browser_window_offset": "0x340", "view_bounds_offset": "0x1c8"}, + "toolbar": {"get_widget_slot": "0xb"}, + }); + leave_out(&mut build, "layout.frame_browser_window_offset"); + leave_out(&mut build, "toolbar.get_widget_slot"); + assert_eq!( + build, + json!({"layout": {"view_bounds_offset": "0x1c8"}, "toolbar": {}}) + ); + } + #[test] fn nfr6_a_value_the_runtime_does_not_read_is_not_a_value_of_the_build() { let build = json!({ diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index c458378..b619d29 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -76,6 +76,9 @@ pub struct PortReport { pub switched_off: Vec, /// Values the runtime does not read in this row, written as zero, with the reason. pub unused: Vec, + /// Values no instruction of the new build gave that the runtime finds by reflection, so the + /// row leaves them out instead of carrying them. + pub reflected: Vec, /// Whether every carried value must be settled: the milestone changed, or values were read. #[serde(skip)] must_check: bool, @@ -1005,8 +1008,9 @@ pub fn port_row( (row, report) } -/// Settles each value no recipe or instruction read from the new build. A value the runtime does -/// not read in this row is written as zero. A value of a feature the runtime can do without turns +/// Settles each value no recipe or instruction read from the new build. A value the runtime finds +/// by reflection is left out of the row. A value the runtime does not read in this row is written +/// as zero. A value of a feature the runtime can do without turns /// that feature off for this build and is cleared, so the rest of the row is not held back by it. /// Any other value stops the row with its reason, since no feature may run on a value of another /// build. @@ -1021,7 +1025,13 @@ fn settle_carried(row: &mut Value, report: &mut PortReport) { let mut left = Vec::new(); let mut off: BTreeMap<&'static str, (&'static RowFeature, Vec)> = BTreeMap::new(); for path in std::mem::take(&mut report.carried) { - if let Some(why) = row_features::unused(&row["build"], &path) { + if row_features::is_reflected(&path) { + row_features::leave_out(&mut row["build"], &path); + report.unread.remove(&path); + report + .reflected + .push(format!("{path}: left out, the runtime finds it by reflection")); + } else if let Some(why) = row_features::unused(&row["build"], &path) { row_features::clear(&mut row["build"], &path, Clear::Zero); report.unused.push(format!("{path}: {why}")); report.unread.remove(&path); @@ -2325,6 +2335,31 @@ mod tests { assert_eq!(build["tabs"]["tab_at"], "0x101300"); } + #[test] + fn nfr6_a_row_without_window_offsets_is_not_blocked() { + // Edge 157's row stopped on exactly these values. The runtime finds them by class name and + // the view tree, so the new row leaves them out and nothing holds it back. + let mut prior = prior_with_features(); + prior["build"]["layout"] = json!({"frame_browser_window_offset": "0x3b0"}); + prior["build"]["side_panel"] = + json!({"host_view": "0x38", "page_area": "0x0", "contents_container": "0xd8"}); + prior["build"]["toolbar"]["get_widget_slot"] = json!("0xa"); + let code = new_code(); + let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + assert_eq!(report.review, Vec::::new()); + assert!(report.carried.is_empty(), "{:?}", report.carried); + assert_eq!(report.reflected.len(), 5, "{:?}", report.reflected); + let build = &row["build"]; + assert!(build["layout"].get("frame_browser_window_offset").is_none()); + assert_eq!(build["side_panel"], json!({})); + assert!(build["toolbar"].get("get_widget_slot").is_none()); + // No feature went off for them. + assert!(!report + .switched_off + .iter() + .any(|line| line.contains("side_panel.") || line.contains("get_widget_slot"))); + } + #[test] fn nfr6_a_value_the_window_cannot_do_without_still_stops_the_row() { let mut prior = prior_with_features(); diff --git a/rivet/runtime/windows/src/browsers/chromium/layout.rs b/rivet/runtime/windows/src/browsers/chromium/layout.rs index 184f4c2..052bf49 100644 --- a/rivet/runtime/windows/src/browsers/chromium/layout.rs +++ b/rivet/runtime/windows/src/browsers/chromium/layout.rs @@ -87,9 +87,12 @@ pub(crate) unsafe extern "system" fn proposed_layout( ) -> *mut c_void { let original: ProposedLayout = std::mem::transmute(page_area::original()); let result = original(this, out, params); - let host = *(this - .cast::() - .add(crate::builds::get().side_panel.host_view) as *const usize); + // The layout keeps the view it lays out in `BrowserViewLayoutViews::browser_view`, found by + // the class name of the view it holds. + let Some(host_field) = crate::chromium::window_views::host_field(this as usize) else { + return result; + }; + let host = *(this.cast::().add(host_field) as *const usize); crate::trace::trace_changed( "layout hook", &format!( @@ -115,9 +118,12 @@ unsafe extern "system" fn app_proposed_layout( let original: ProposedLayout = std::mem::transmute(APP_ORIGINAL.load(std::sync::atomic::Ordering::Acquire)); let result = original(this, out, params); - let host = *(this - .cast::() - .add(crate::builds::get().side_panel.host_view) as *const usize); + // The layout keeps the view it lays out in `BrowserViewLayoutViews::browser_view`, found by + // the class name of the view it holds. + let Some(host_field) = crate::chromium::window_views::host_field(this as usize) else { + return result; + }; + let host = *(this.cast::().add(host_field) as *const usize); crate::trace::trace_changed( "layout hook", &format!( diff --git a/rivet/runtime/windows/src/browsers/chromium/split.rs b/rivet/runtime/windows/src/browsers/chromium/split.rs index 1585390..7efa102 100644 --- a/rivet/runtime/windows/src/browsers/chromium/split.rs +++ b/rivet/runtime/windows/src/browsers/chromium/split.rs @@ -83,10 +83,10 @@ pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) let row = &crate::builds::get().side_panel; if let (Some(toolbar), Some(contents)) = ( area.bounds(row.toolbar), - area.bounds(row.contents_container), + area.contents(), ) { if area.rail == 0 && active_is_split(area.window) { - if let Some(page) = area.bounds(row.page_area) { + if let Some(page) = area.page() { fill_area(&mut *contents, &*page); } } diff --git a/rivet/runtime/windows/src/builds/brave.rs b/rivet/runtime/windows/src/builds/brave.rs index eeb8057..52d74ff 100644 --- a/rivet/runtime/windows/src/builds/brave.rs +++ b/rivet/runtime/windows/src/builds/brave.rs @@ -49,7 +49,7 @@ pub static BRAVE: Build = Build { module: "chrome.dll", version: [156, 1, 98, 62], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_BRAVE_156, get_color: 0x06A9A890, // ?GetColor@ColorProvider@ui@@QEBAIH@Z get_color_bytes: &[ @@ -236,9 +236,9 @@ pub static BRAVE: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -295,7 +295,7 @@ pub static BRAVE: Build = Build { stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], set_opaque: 0x02322E10, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], - frame_browser_window_offset: 0x340, + frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x67D, 0x67E, 0x67F], top_inset_adjust: -12, @@ -380,7 +380,7 @@ pub static BRAVE_63: Build = Build { module: "chrome.dll", version: [156, 1, 98, 63], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_BRAVE_156, get_color: 0x06A5CB00, // ?GetColor@ColorProvider@ui@@QEBAIH@Z get_color_bytes: &[ @@ -604,9 +604,9 @@ pub static BRAVE_63: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -663,7 +663,7 @@ pub static BRAVE_63: Build = Build { stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], set_opaque: 0x0244FE30, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], - frame_browser_window_offset: 0x340, + frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x67D, 0x67E, 0x67F], top_inset_adjust: 0, // Chromium's own GetTopInset, as on Chrome @@ -782,7 +782,7 @@ pub static BRAVE_157_55: Build = Build { module: "chrome.dll", version: [157, 1, 99, 55], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_BRAVE_157, get_color: 0x05B6CB30, // ?GetColor@ColorProvider@ui@@QEBAIH@Z get_color_bytes: &[ @@ -1006,9 +1006,9 @@ pub static BRAVE_157_55: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -1065,7 +1065,7 @@ pub static BRAVE_157_55: Build = Build { stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], set_opaque: 0x0080EA30, // ?SetFillsBoundsOpaquely@Layer@ui@@UEAAX_N@Z set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], - frame_browser_window_offset: 0x338, + frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x684, 0x685, 0x686], top_inset_adjust: 0, // Chromium's own GetTopInset, as on Chrome diff --git a/rivet/runtime/windows/src/builds/chrome.rs b/rivet/runtime/windows/src/builds/chrome.rs index 74fcc3c..b51e221 100644 --- a/rivet/runtime/windows/src/builds/chrome.rs +++ b/rivet/runtime/windows/src/builds/chrome.rs @@ -56,7 +56,7 @@ pub static CHROME: Build = Build { module: "chrome.dll", version: [156, 0, 8078, 48], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_CHROME_156, get_color: 0x04AA24F0, get_color_bytes: &[ @@ -320,9 +320,9 @@ pub static CHROME: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -377,7 +377,7 @@ pub static CHROME: Build = Build { corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - frame_browser_window_offset: 0x340, + frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_ink_ids: &[0x66C, 0x66D, 0x66E], @@ -460,7 +460,7 @@ pub static CHROME_156_74: Build = Build { module: "chrome.dll", version: [156, 0, 8078, 74], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_CHROME_156_74, get_color: 0x0535_9A80, get_color_bytes: &[ @@ -724,9 +724,9 @@ pub static CHROME_156_74: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -781,7 +781,7 @@ pub static CHROME_156_74: Build = Build { corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - frame_browser_window_offset: 0x340, + frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_ink_ids: &[0x66C, 0x66D, 0x66E], @@ -880,7 +880,7 @@ pub static CHROME_156_80: Build = Build { module: "chrome.dll", version: [156, 0, 8078, 80], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_CHROME_156_80, get_color: 0x052B_06D0, get_color_bytes: &[ @@ -1144,9 +1144,9 @@ pub static CHROME_156_80: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -1201,7 +1201,7 @@ pub static CHROME_156_80: Build = Build { corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - frame_browser_window_offset: 0x340, + frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], caption_ink_ids: &[0x66C, 0x66D, 0x66E], @@ -1328,7 +1328,7 @@ pub static CHROME_157_38: Build = Build { module: "chrome.dll", version: [157, 0, 8103, 38], toolbar: Toolbar { - get_widget_slot: 11, + get_widget_slot: Some(11), dev: DEV_CHROME_157_38, get_color: 0x0454_F050, get_color_bytes: &[ @@ -1592,9 +1592,9 @@ pub static CHROME_157_38: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0x50, - contents_container: 0xb8, + host_view: Some(0x38), + page_area: Some(0x50), + contents_container: Some(0xb8), vertical_tabs: 0x80, toolbar: 0x60, contents_outline: 0x58, @@ -1649,7 +1649,7 @@ pub static CHROME_157_38: Build = Build { corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - frame_browser_window_offset: 0x338, + frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], caption_ink_ids: &[0x673, 0x674, 0x675], @@ -1720,7 +1720,7 @@ pub static CHROME_150: Build = Build { corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], layout_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - frame_browser_window_offset: 0x338, + frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], caption_ink_ids: &[1593, 1594, 1595], diff --git a/rivet/runtime/windows/src/builds/edge.rs b/rivet/runtime/windows/src/builds/edge.rs index 7af0022..29ab5c9 100644 --- a/rivet/runtime/windows/src/builds/edge.rs +++ b/rivet/runtime/windows/src/builds/edge.rs @@ -57,7 +57,7 @@ pub static EDGE: Build = Build { module: "msedge.dll", version: [156, 0, 4314, 50], toolbar: Toolbar { - get_widget_slot: 10, + get_widget_slot: Some(10), dev: DEV_EDGE_156, get_color: 0x0100309E, get_color_bytes: &[ @@ -323,9 +323,9 @@ pub static EDGE: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x38, - page_area: 0, - contents_container: 0xd8, + host_view: Some(0x38), + page_area: Some(0), + contents_container: Some(0xd8), vertical_tabs: ABSENT, toolbar: ABSENT, // the pages of a split fit their toolbar in Chrome's layout only contents_outline: ABSENT, @@ -381,7 +381,7 @@ pub static EDGE: Build = Build { corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], layout_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x40, 0x48], set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - frame_browser_window_offset: 0x3B0, // frame view member that holds the BrowserWindow subobject, read by GetBrowserView + frame_browser_window_offset: Some(0x3B0), // frame view member that holds the BrowserWindow subobject, read by GetBrowserView browser_window_in_view: 0x1F8, // BrowserWindow subobject distance from the BrowserView, read by GetBrowserView caption_paint_prologue: &[0xE9, 0x01, 0x00, 0x00, 0x00, 0xCC, 0x41, 0x57], caption_ink_ids: &[0x66C, 0x66D, 0x66E], // Chrome value, not checked on Edge diff --git a/rivet/runtime/windows/src/builds/mod.rs b/rivet/runtime/windows/src/builds/mod.rs index a96bcb5..c012b9d 100644 --- a/rivet/runtime/windows/src/builds/mod.rs +++ b/rivet/runtime/windows/src/builds/mod.rs @@ -186,8 +186,10 @@ pub struct AppWindow { row_struct! { /// Values for `chrome_toolbar.rs`. pub struct Toolbar { - /// `views::View::GetWidget` is the twelfth entry of every view's vtable. - pub get_widget_slot: usize, + /// `views::View::GetWidget`'s entry in every view's vtable, only to confirm the widget the root + /// of a view's tree names. `None` when the row does not have it: the widget is then found + /// through the view tree alone. + pub get_widget_slot: Option, /// What this build needs to show a page in developer mode. pub dev: DevMode, /// `ui::ColorProvider::GetColor(this, id)`. A provider makes a colour the first time it is asked @@ -506,11 +508,13 @@ pub struct SidePanel { /// toggle and its key. pub extensions_by_toggle: Option, /// The layout object keeps the host view at +0x38, the contents container at +0xb8, the side - /// panel at +0xc0 and the content shown while the side panel animates at +0xc8. - pub host_view: usize, + /// panel at +0xc0 and the content shown while the side panel animates at +0xc8. The host view, + /// the page area and the contents container are also found by the class names of the views + /// they hold, and a row value only confirms them; `None` when the row does not have one. + pub host_view: Option, /// The view behind the whole area below the top row, which the rail shares the height of. - pub page_area: usize, - pub contents_container: usize, + pub page_area: Option, + pub contents_container: Option, /// The browser's vertical tab list, which lies left of the page. pub vertical_tabs: usize, /// The browser's top row: toolbar, address bar and the buttons around it. @@ -602,8 +606,9 @@ pub struct Layout { pub layout_prologue: &'static [u8], pub set_bounds_rect_prologue: &'static [u8], /// `BrowserFrameViewWin` holds the `BrowserView`'s `BrowserWindow` subobject here, and the -/// subobject lies this many bytes after the start of the `BrowserView`. - pub frame_browser_window_offset: usize, + /// subobject lies this many bytes after the start of the `BrowserView`. The field is also found + /// as the one that holds the view the layout lays out, and a row value only confirms it. + pub frame_browser_window_offset: Option, pub browser_window_in_view: usize, pub caption_paint_prologue: &'static [u8], /// Colour ids `WindowsCaptionButton::PaintButtonContents` reads for its glyphs: active, inactive @@ -651,7 +656,7 @@ const DEV_HOVER: u32 = 0x17FF_FFFF; const DEV_RIPPLE: u32 = 0x24FF_FFFF; const UNCHECKED_TOOLBAR: Toolbar = Toolbar { - get_widget_slot: 0, + get_widget_slot: None, dev: UNCHECKED_DEV, content_window_for_hwnd: ABSENT, widget_for_window: ABSENT, @@ -819,9 +824,9 @@ const UNCHECKED_SIDEPANEL: SidePanel = SidePanel { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0, - page_area: 0, - contents_container: 0, + host_view: None, + page_area: None, + contents_container: None, vertical_tabs: 0, toolbar: 0, contents_outline: 0, @@ -874,7 +879,7 @@ const UNCHECKED_LAYOUT: Layout = Layout { corner_paint_prologue: &[0], layout_prologue: &[0], set_bounds_rect_prologue: &[0], - frame_browser_window_offset: 0, + frame_browser_window_offset: None, browser_window_in_view: 0, caption_paint_prologue: &[0], caption_ink_ids: &[], diff --git a/rivet/runtime/windows/src/builds/samsung.rs b/rivet/runtime/windows/src/builds/samsung.rs index cf5ba5b..befdbd5 100644 --- a/rivet/runtime/windows/src/builds/samsung.rs +++ b/rivet/runtime/windows/src/builds/samsung.rs @@ -363,9 +363,9 @@ pub static SAMSUNG: Build = Build { coordinator_browser: Some(0x28), entry_key_size: Some(0x48), extensions_by_toggle: Some(true), - host_view: 0x30, - page_area: ABSENT, - contents_container: 0x80, + host_view: Some(0x30), + page_area: Some(ABSENT), + contents_container: Some(0x80), vertical_tabs: ABSENT, toolbar: 0x70, contents_outline: ABSENT, diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index e84ce43..1f70e64 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -217,7 +217,7 @@ fn nfr3_whale_maps_only_the_frame_hooks() { WHALE.layout.frame_browser_window_offset, WHALE.layout.browser_window_in_view ), - (0x338, 0x210) + (Some(0x338), 0x210) ); } @@ -1071,7 +1071,7 @@ fn nfr3_chromium_157_rows_record_the_members_that_moved() { assert_eq!(build.tabs.browser_in_view, 0x558, "{name}"); assert_eq!(build.side_panel.browser_offset, 0x558, "{name}"); assert_eq!(build.layout.view_bounds_offset, 0x1C8, "{name}"); - assert_eq!(build.layout.frame_browser_window_offset, 0x338, "{name}"); + assert_eq!(build.layout.frame_browser_window_offset, Some(0x338), "{name}"); assert_eq!(build.layout.caption_container_offset, 0x3C0, "{name}"); assert_eq!( (build.layout.top_inset_slot, build.layout.caption_paint_slot), @@ -1206,7 +1206,7 @@ fn fr9_whale_split_functions_match_the_installed_build() { fn check_brave_toolbar_hooks(brave: &Build) { assert_eq!(brave.toolbar.skip, ""); - assert_eq!(brave.toolbar.get_widget_slot, 11); + assert_eq!(brave.toolbar.get_widget_slot, Some(11)); // The Brave row's caption colour ids sit 17 above Chrome's. assert_eq!( brave.layout.caption_ink_ids, diff --git a/rivet/runtime/windows/src/builds/whale.rs b/rivet/runtime/windows/src/builds/whale.rs index 770434a..45931c8 100644 --- a/rivet/runtime/windows/src/builds/whale.rs +++ b/rivet/runtime/windows/src/builds/whale.rs @@ -358,9 +358,9 @@ pub static WHALE: Build = Build { coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: 0x20, - page_area: 0x28, - contents_container: 0x90, + host_view: Some(0x20), + page_area: Some(0x28), + contents_container: Some(0x90), vertical_tabs: 0x60, toolbar: 0x40, contents_outline: 0x38, @@ -396,7 +396,7 @@ pub static WHALE: Build = Build { caption_vtable: 0xfb15d60, caption_size_slot: 74, caption_size: ABSENT, - frame_browser_window_offset: 0x338, + frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x210, view_bounds_offset: 0x1C0, ..UNCHECKED_LAYOUT diff --git a/rivet/runtime/windows/src/chromium/mod.rs b/rivet/runtime/windows/src/chromium/mod.rs index 713c6d1..8cef86b 100644 --- a/rivet/runtime/windows/src/chromium/mod.rs +++ b/rivet/runtime/windows/src/chromium/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod memory; pub(crate) mod reflect; pub(crate) mod screen; pub(crate) mod view; +pub(crate) mod window_views; diff --git a/rivet/runtime/windows/src/chromium/reflect.rs b/rivet/runtime/windows/src/chromium/reflect.rs index 0e2843e..8f3e7be 100644 --- a/rivet/runtime/windows/src/chromium/reflect.rs +++ b/rivet/runtime/windows/src/chromium/reflect.rs @@ -149,6 +149,12 @@ pub(crate) fn class_name(ranges: &Ranges, view: usize) -> Option { class_name_within(ranges, view, 0x100) } +/// `class_name` for an object whose `MetaDataProvider` part may come late, after bases with +/// members of their own, as in `views::Widget` and in a `views::View` reached at its start. +pub(crate) fn class_name_far(ranges: &Ranges, object: usize) -> Option { + class_name_within(ranges, object, 0x800) +} + /// `class_name` for a pointer to the start of a `views::View`, whose `MetaDataProvider` part comes /// after seven other bases and their members, so it is looked for within `reach` bytes. fn class_name_within(ranges: &Ranges, view: usize, reach: usize) -> Option { @@ -437,6 +443,16 @@ pub(crate) fn find_cached( Ok((found, false)) } +/// The parent and view list fields an earlier walk found for the build with this fingerprint. +pub(crate) fn walked_fields(build: (u32, u32)) -> Option<(usize, usize)> { + CACHE.lock().ok().and_then(|cache| { + cache + .iter() + .find(|(key, _)| *key == build) + .map(|(_, offsets)| (offsets.parent, offsets.children)) + }) +} + /// The views a `std::vector` at `view + field` holds. fn children_of(view: usize, field: usize) -> Vec { let (Some(begin), Some(end)) = (word(view + field), word(view + field + 8)) else { diff --git a/rivet/runtime/windows/src/chromium/window_views.rs b/rivet/runtime/windows/src/chromium/window_views.rs new file mode 100644 index 0000000..94e412d --- /dev/null +++ b/rivet/runtime/windows/src/chromium/window_views.rs @@ -0,0 +1,674 @@ +//! Finds the views and the widget of a browser window by Chromium's own class names and the shape +//! of its view tree, so the window needs no member offset or vtable slot of its build for them. +//! +//! Each path below follows public Chromium source: +//! +//! - `BrowserViewLayout` keeps the views it lays out in `BrowserViewLayoutViews views_` +//! (`chrome/browser/ui/views/frame/layout/browser_view_layout.h`). Its `browser_view` is the +//! `BrowserView` as a `views::View`, `main_background_region` is a `MainBackgroundRegionView` and +//! `multi_contents_view` is a `MultiContentsView`. `BrowserView::BrowserView` adds both of the +//! latter with `AddChildView` (`browser_view.cc`), so each names the browser view as its parent. +//! The layout's fields are found by the class names of the views they point at. +//! - `BrowserFrameView` keeps the browser view in `views::ViewTracker browser_view_` +//! (`browser_frame_view.h`), which holds the `BrowserView`'s `views::View`: the view the layout +//! lays out. The frame view's field is the one that holds the same view. +//! - A view's widget is what `View::GetWidget` returns: the root view's `widget_`, a +//! `raw_ptr` of `views::internal::RootView` (`ui/views/widget/root_view.h`). The root +//! view is reached through `View::parent_` until it is null. `Widget` owns the root view in +//! `std::unique_ptr root_view_` (`ui/views/widget/widget.h`), so the root's +//! widget field is the one whose object points back at the root, and `Widget` carries its own +//! class metadata (`METADATA_HEADER_BASE(Widget)`). +//! +//! The logic reads memory through `Memory`, so it is tested on plain data. Where a build's row also +//! has the value, the two must agree or the value is not used. + +/// Reads of the browser's memory that the paths need. +pub(crate) trait Memory { + /// The word at `address`, or `None` when it cannot be read. + fn word(&self, address: usize) -> Option; + /// The `ui::metadata` class name of the object at `object`, when it has one. + fn class_name(&self, object: usize) -> Option; +} + +pub(crate) const BROWSER_VIEW: &str = "BrowserView"; +pub(crate) const MAIN_BACKGROUND_REGION: &str = "MainBackgroundRegionView"; +pub(crate) const MULTI_CONTENTS: &str = "MultiContentsView"; + +/// How far into a layout object its view fields are looked for. +const LAYOUT_REACH: usize = 0x400; +/// How far into a frame view, a root view or a widget a field is looked for. +const OBJECT_REACH: usize = 0x1000; +/// How many parents a view may have before the walk to its root gives up. +const MAX_DEPTH: usize = 64; + +/// The fields of `object` within `reach` that hold the one object named `class`, with that object. +/// Several fields may hold the same object. Two different objects of the class leave it unknown. +pub(crate) fn fields_naming( + memory: &M, + object: usize, + reach: usize, + class: &str, + accept: &dyn Fn(usize) -> bool, +) -> Option<(Vec, usize)> { + let mut found: Option<(Vec, usize)> = None; + for field in (0..reach).step_by(8) { + let Some(value) = memory.word(object + field) else { + break; + }; + if value == 0 || value == object || value % 8 != 0 { + continue; + } + if let Some((fields, known)) = found.as_mut() { + if *known == value { + fields.push(field); + continue; + } + } + if memory.class_name(value).as_deref() != Some(class) || !accept(value) { + continue; + } + if found.is_some() { + return None; + } + found = Some((vec![field], value)); + } + found +} + +/// The fields of a browser layout object, as offsets into it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct LayoutFields { + /// The fields that hold the `BrowserView`, the view the layout lays out. + pub host: Vec, + /// The fields that hold the `MainBackgroundRegionView`, the area below the top row. + pub page_area: Vec, + /// The fields that hold the `MultiContentsView`, which holds the pages. + pub contents: Vec, +} + +/// The view fields of the layout object at `layout`. With the parent field known, a page area or +/// contents view counts only when it names the browser view as its parent, as `AddChildView` left +/// it. `None` when no field holds a browser view. +pub(crate) fn layout_fields( + memory: &M, + layout: usize, + parent: Option, +) -> Option { + let anything = |_: usize| true; + let (host, view) = fields_naming(memory, layout, LAYOUT_REACH, BROWSER_VIEW, &anything)?; + let child_of_host = |child: usize| match parent { + Some(parent) => memory.word(child + parent) == Some(view), + None => true, + }; + let child = |class: &str| { + fields_naming(memory, layout, LAYOUT_REACH, class, &child_of_host) + .map_or_else(Vec::new, |(fields, _)| fields) + }; + Some(LayoutFields { + host, + page_area: child(MAIN_BACKGROUND_REGION), + contents: child(MULTI_CONTENTS), + }) +} + +/// The fields of the frame view at `frame` that hold its browser view. When the layout already +/// gave the browser view, the field must hold that one; otherwise every view in the browser view's +/// own list of children must name it as their parent, which tells a view's own address from a +/// pointer into another part of the object. +pub(crate) fn frame_fields( + memory: &M, + frame: usize, + host: Option, + parent: Option, +) -> Option> { + let is_host = |view: usize| match (host, parent) { + (Some(host), _) => view == host, + (None, Some(parent)) => is_listing_parent(memory, view, parent), + (None, None) => false, + }; + fields_naming(memory, frame, OBJECT_REACH, BROWSER_VIEW, &is_host).map(|(fields, _)| fields) +} + +/// Whether the view at `view` lists children that all name it at `parent`. `View::children_` is +/// the `std::vector` right after `parent_` in `ui/views/view.h`. +fn is_listing_parent(memory: &M, view: usize, parent: usize) -> bool { + let children = children(memory, view, parent + 8); + !children.is_empty() + && children + .iter() + .all(|child| memory.word(child + parent) == Some(view)) +} + +fn children(memory: &M, view: usize, field: usize) -> Vec { + let (Some(begin), Some(end)) = (memory.word(view + field), memory.word(view + field + 8)) else { + return Vec::new(); + }; + if begin == 0 || end < begin || (end - begin) % 8 != 0 || (end - begin) / 8 > 256 { + return Vec::new(); + } + (begin..end).step_by(8).filter_map(|at| memory.word(at)).collect() +} + +/// The root of the view tree `view` is in: the view whose parent is null. +pub(crate) fn root_of(memory: &M, view: usize, parent: usize) -> Option { + let mut at = view; + for _ in 0..MAX_DEPTH { + match memory.word(at + parent)? { + 0 => return Some(at), + next => at = next, + } + } + None +} + +/// Where a root view keeps its widget and where the widget keeps the root view, as offsets. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct WidgetFields { + pub widget_in_root: usize, + pub root_in_widget: usize, +} + +/// Finds the widget fields from a root view at `root`: a field of the root whose object has class +/// metadata and holds the root in turn, which is not a child view naming the root as its parent. +/// The root must be named as a `RootView` is. `None` when no field or two different ones qualify. +pub(crate) fn widget_fields( + memory: &M, + root: usize, + parent: usize, +) -> Option { + if !memory + .class_name(root) + .is_some_and(|name| name.ends_with("RootView")) + { + return None; + } + let listed = children(memory, root, parent + 8); + let mut found: Option<(usize, WidgetFields)> = None; + for field in (0..OBJECT_REACH).step_by(8) { + let Some(widget) = memory.word(root + field) else { + break; + }; + if widget == 0 || widget == root || widget % 8 != 0 || listed.contains(&widget) { + continue; + } + if found.is_some_and(|(known, _)| known == widget) { + continue; + } + // Reading stops where the object's memory ends. + let Some(back) = (0..OBJECT_REACH) + .step_by(8) + .map_while(|offset| memory.word(widget + offset).map(|word| (offset, word))) + .find(|(offset, word)| *offset != parent && *word == root) + .map(|(offset, _)| offset) + else { + continue; + }; + if memory.class_name(widget).is_none() { + continue; + } + let fields = WidgetFields { + widget_in_root: field, + root_in_widget: back, + }; + if found.is_some() { + return None; + } + found = Some((widget, fields)); + } + found.map(|(_, fields)| fields) +} + +/// The widget that holds `view` through fields already found: the root's widget, which must hold +/// the root back. Zero for a view in no widget, as `View::GetWidget` gives. +pub(crate) fn widget_of( + memory: &M, + view: usize, + parent: usize, + fields: WidgetFields, +) -> usize { + let Some(root) = root_of(memory, view, parent) else { + return 0; + }; + let Some(widget) = memory.word(root + fields.widget_in_root) else { + return 0; + }; + if widget == 0 || memory.word(widget + fields.root_in_widget) != Some(root) { + return 0; + } + widget +} + +/// One value from the fields reflection found and the value of the row. Both must agree when both +/// are known: the row's field must be one of the fields that hold the object. A row with no value +/// takes the reflected one, and a build reflection finds nothing in keeps its row's. +pub(crate) fn settle(reflected: Option<&[usize]>, row: Option) -> Option { + match (reflected.filter(|fields| !fields.is_empty()), row) { + (Some(fields), Some(row)) => fields.contains(&row).then_some(row), + (Some(fields), None) => fields.first().copied(), + (None, row) => row, + } +} + +/// The browser's own memory, read only where it can be read, with class names read through each +/// object's `ui::metadata` as `reflect` reads them. +pub(crate) struct Live { + ranges: crate::chromium::reflect::Ranges, +} + +impl Memory for Live { + fn word(&self, address: usize) -> Option { + crate::chromium::memory::readable(address, 8) + .then(|| unsafe { (address as *const usize).read() }) + } + fn class_name(&self, object: usize) -> Option { + crate::chromium::reflect::class_name_far(&self.ranges, object) + } +} + +/// The browser module's memory, once its sections are known. +fn live() -> Option<&'static Live> { + static LIVE: std::sync::OnceLock> = std::sync::OnceLock::new(); + LIVE.get_or_init(|| { + let image = crate::chromium::image::recorded()?; + let headers = + unsafe { std::slice::from_raw_parts(image.base as *const u8, 0x1000.min(image.size)) }; + let list = crate::chromium::reflect::sections(headers); + Some(Live { + ranges: crate::chromium::reflect::ranges_of(image.base, &list), + }) + }) + .as_ref() +} + +/// Where a view of this build keeps its parent. +fn parent_field() -> Option { + crate::builds::current() + .and_then(crate::features::app_window::view_fields) + .map(|(parent, _)| parent) +} + +/// What one value became: not looked for yet, or settled, with `None` for a value that neither +/// reflection nor the row gave, or where the two disagree. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Settled { + Unknown, + Known(Option), +} + +/// How many times a value is looked for before the row alone decides it, so a build whose views +/// carry other names does not scan on every layout. +const TRIES: u32 = 8; + +struct Slot { + value: std::sync::Mutex<(Settled, u32)>, +} + +impl Slot { + const fn new() -> Self { + Self { + value: std::sync::Mutex::new((Settled::Unknown, 0)), + } + } + + /// The settled value, or what `find` and the row settle it to. A miss counts as a try, and + /// after the last try the row's value stands alone. + fn get(&self, row: Option, find: impl FnOnce() -> Option>) -> Option { + let mut value = self.value.lock().unwrap_or_else(|error| error.into_inner()); + if let Settled::Known(known) = value.0 { + return known; + } + match find() { + Some(fields) => { + let settled = settle(Some(fields.as_slice()), row); + if settled.is_none() { + crate::trace::trace(&format!( + "window views: reflection found {fields:x?} where the row has {row:x?}, so the value is not used" + )); + } + value.0 = Settled::Known(settled); + settled + } + None => { + value.1 += 1; + if value.1 >= TRIES { + value.0 = Settled::Known(row); + } + row + } + } + } + + fn known(&self, row: Option) -> Option { + match self.value.lock().unwrap_or_else(|error| error.into_inner()).0 { + Settled::Known(known) => known, + Settled::Unknown => row, + } + } +} + +static HOST: Slot = Slot::new(); +static PAGE_AREA: Slot = Slot::new(); +static CONTENTS: Slot = Slot::new(); +static FRAME: Slot = Slot::new(); + +/// A row value that is recorded: an offset the build has, not the absent marker. +fn recorded(value: Option) -> Option { + value.filter(|value| *value != crate::builds::ABSENT) +} + +fn side_panel_row() -> &'static crate::builds::SidePanel { + &crate::builds::get().side_panel +} + +/// Settles the view fields of the browser layout object at `layout`, which the layout hook hands +/// over, and returns the field that holds the view it lays out. Reads memory only. +pub(crate) unsafe fn host_field(layout: usize) -> Option { + let row = side_panel_row(); + let mut found: Option = None; + let mut fields = || { + if found.is_none() { + found = live().and_then(|live| layout_fields(live, layout, parent_field())); + } + found.clone() + }; + let host = HOST.get(recorded(row.host_view), || fields().map(|found| found.host)); + PAGE_AREA.get(recorded(row.page_area), || { + fields().map(|found| found.page_area).filter(|fields| !fields.is_empty()) + }); + CONTENTS.get(recorded(row.contents_container), || { + fields().map(|found| found.contents).filter(|fields| !fields.is_empty()) + }); + host +} + +/// The layout object's field that holds the area below the top row, or `ABSENT`. +pub(crate) fn page_area_field() -> usize { + PAGE_AREA + .known(recorded(side_panel_row().page_area)) + .unwrap_or(crate::builds::ABSENT) +} + +/// The layout object's field that holds the view of the pages, or `ABSENT`. +pub(crate) fn contents_field() -> usize { + CONTENTS + .known(recorded(side_panel_row().contents_container)) + .unwrap_or(crate::builds::ABSENT) +} + +/// The browser view the frame view at `frame` holds, the same view the browser's layout lays out. +/// `host` is that view when the layout already ran for the window. +pub(crate) unsafe fn frame_browser_view(frame: usize, host: Option) -> Option { + let row = recorded(crate::builds::get().layout.frame_browser_window_offset); + let field = FRAME.get(row, || { + live().and_then(|live| frame_fields(live, frame, host, parent_field())) + })?; + live()? + .word(frame + field) + .filter(|view| *view != 0) +} + +/// Starts the view walk of `reflect` from `window`'s own `HWNDMessageHandler`, once per process, on +/// a worker thread: it only reads memory, and its result is kept by build fingerprint for +/// `walked_view_fields`. +pub(crate) unsafe fn walk_views_once(window: windows_sys::Win32::Foundation::HWND) { + use windows_sys::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, GWLP_USERDATA}; + static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let (Some(live), Some(build)) = (live(), fingerprint()) else { + return; + }; + if STARTED.swap(true, std::sync::atomic::Ordering::AcqRel) { + return; + } + let ranges = live.ranges; + let handler = GetWindowLongPtrW(window, GWLP_USERDATA) as usize; + std::thread::spawn(move || { + let found = crate::chromium::reflect::find_cached( + &ranges, + handler, + std::time::Duration::from_millis(500), + build, + ); + match found { + Ok((found, _)) => crate::trace::trace(&format!( + "window views: the view walk found the parent at {:#x} and the view list at {:#x}", + found.parent, found.children + )), + Err(error) => crate::trace::trace(&format!("window views: {error}")), + } + }); +} + +/// The browser module's fingerprint, which keys what the view walk found. +fn fingerprint() -> Option<(u32, u32)> { + let image = crate::chromium::image::recorded()?; + let headers = + unsafe { std::slice::from_raw_parts(image.base as *const u8, 0x1000.min(image.size)) }; + crate::chromium::reflect::fingerprint(headers) +} + +/// The parent and view list fields the view walk found in this process's build, once it ran. +pub(crate) fn walked_view_fields() -> Option<(usize, usize)> { + crate::chromium::reflect::walked_fields(fingerprint()?) +} + +/// What the widget path became: the fields found, or that it gave nothing. +static WIDGET: std::sync::Mutex<(Option>, u32)> = + std::sync::Mutex::new((None, 0)); + +/// The widget that holds `view`, found through the root of its view tree. When the build's row +/// has `View::GetWidget`'s vtable slot, `by_slot` calls it, once, to confirm the path: if the two +/// disagree neither is used, and a view is then in no widget. Without a path the slot decides. +pub(crate) unsafe fn widget_holding( + view: usize, + by_slot: Option<&dyn Fn(usize) -> usize>, +) -> usize { + let Some((live, parent)) = live().zip(parent_field()) else { + return by_slot.map_or(0, |slot| slot(view)); + }; + let mut state = WIDGET.lock().unwrap_or_else(|error| error.into_inner()); + if state.0.is_none() { + let fields = root_of(live, view, parent).and_then(|root| widget_fields(live, root, parent)); + match fields { + Some(fields) => { + let found = widget_of(live, view, parent, fields); + let agrees = by_slot.is_none_or(|slot| slot(view) == found); + if !agrees { + crate::trace::trace( + "window views: the widget path and the widget slot disagree, so neither is used", + ); + } + state.0 = Some(agrees.then_some(fields)); + } + None => { + state.1 += 1; + if state.1 >= TRIES { + state.0 = Some(None); + } + drop(state); + return by_slot.map_or(0, |slot| slot(view)); + } + } + } + let (settled, tries) = (state.0, state.1); + drop(state); + match settled { + Some(Some(fields)) => widget_of(live, view, parent, fields), + // The slot stands alone only where no path was found; a disagreement uses neither. + Some(None) if tries >= TRIES => by_slot.map_or(0, |slot| slot(view)), + _ => 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + /// Browser memory as plain words and the class names some objects carry. + #[derive(Default)] + struct Words { + words: HashMap, + names: HashMap, + } + + impl Words { + fn set(&mut self, address: usize, value: usize) { + self.words.insert(address, value); + } + fn name(&mut self, object: usize, name: &'static str) { + self.names.insert(object, name); + } + /// A list of views at `list` held by the `std::vector` at `view + field`. + fn list(&mut self, view: usize, field: usize, list: usize, items: &[usize]) { + self.set(view + field, list); + self.set(view + field + 8, list + items.len() * 8); + for (index, item) in items.iter().enumerate() { + self.set(list + index * 8, *item); + } + } + } + + impl Memory for Words { + fn word(&self, address: usize) -> Option { + // Objects are small blocks: every address inside one reads, zero where nothing is set. + let block = address & !0xFFFF; + self.words + .keys() + .any(|known| (known & !0xFFFF) == block) + .then(|| self.words.get(&address).copied().unwrap_or(0)) + } + fn class_name(&self, object: usize) -> Option { + self.names.get(&object).map(|name| (*name).to_owned()) + } + } + + const PARENT: usize = 0x198; + const LAYOUT: usize = 0x10_0000; + const BROWSER: usize = 0x20_0000; + const PAGE_AREA: usize = 0x30_0000; + const CONTENTS: usize = 0x40_0000; + const PANEL: usize = 0x50_0000; + const FRAME: usize = 0x60_0000; + const ROOT: usize = 0x70_0000; + const WIDGET: usize = 0x80_0000; + const LISTS: usize = 0x90_0000; + const OTHER: usize = 0xA0_0000; + + /// A browser window laid out as Chromium 157's layout keeps it, with its views at the fields + /// `BrowserViewLayoutViews` gives them and the tree `BrowserView` builds. + fn window(host: usize, page_area: usize, contents: usize) -> Words { + let mut memory = Words::default(); + memory.set(LAYOUT, 0x1234); // the layout's vtable + memory.set(LAYOUT + host, BROWSER); + memory.set(LAYOUT + page_area, PAGE_AREA); + memory.set(LAYOUT + contents, CONTENTS); + memory.set(LAYOUT + 0xC0, PANEL); + memory.name(BROWSER, "BrowserView"); + memory.name(PAGE_AREA, "MainBackgroundRegionView"); + memory.name(CONTENTS, "MultiContentsView"); + memory.name(PANEL, "SidePanel"); + for child in [PAGE_AREA, CONTENTS, PANEL] { + memory.set(child + PARENT, BROWSER); + } + memory.list(BROWSER, PARENT + 8, LISTS, &[PAGE_AREA, CONTENTS, PANEL]); + // The browser view sits in the root view, which belongs to the widget. + memory.set(BROWSER + PARENT, ROOT); + memory.set(ROOT + PARENT, 0); + memory.name(ROOT, "BrowserRootView"); + memory.list(ROOT, PARENT + 8, LISTS + 0x100, &[BROWSER]); + memory.set(ROOT + 0x3A0, WIDGET); + memory.set(WIDGET + 0x1D8, ROOT); + memory.name(WIDGET, "BrowserWidget"); + // The frame view's tracker of the browser view, and the tracker's observation of it. + memory.set(FRAME + 0x338, 0x5678); + memory.set(FRAME + 0x340, BROWSER); + memory.set(FRAME + 0x348, BROWSER); + memory + } + + #[test] + fn nfr6_the_side_panel_views_are_found_by_class_name() { + // Chrome 157 keeps them at 0x38, 0x50 and 0xb8; Edge has its own fields between them. + for (host, page_area, contents) in [(0x38, 0x50, 0xB8), (0x38, 0x58, 0xD8)] { + let memory = window(host, page_area, contents); + let fields = layout_fields(&memory, LAYOUT, Some(PARENT)).expect("a browser view"); + assert_eq!(fields.host, [host]); + assert_eq!(fields.page_area, [page_area]); + assert_eq!(fields.contents, [contents]); + } + } + + #[test] + fn nfr6_a_layout_view_that_is_not_the_browser_views_child_is_not_taken() { + let mut memory = window(0x38, 0x50, 0xB8); + memory.set(CONTENTS + PARENT, OTHER); + let fields = layout_fields(&memory, LAYOUT, Some(PARENT)).unwrap(); + assert!(fields.contents.is_empty()); + assert_eq!(fields.page_area, [0x50]); + // A layout with no browser view has no fields at all. + let mut bare = Words::default(); + bare.set(LAYOUT + 0x38, PAGE_AREA); + bare.name(PAGE_AREA, "MainBackgroundRegionView"); + assert_eq!(layout_fields(&bare, LAYOUT, Some(PARENT)), None); + } + + #[test] + fn nfr6_two_different_views_of_one_class_leave_the_field_unknown() { + let mut memory = window(0x38, 0x50, 0xB8); + memory.set(LAYOUT + 0x100, OTHER); + memory.name(OTHER, "MultiContentsView"); + memory.set(OTHER + PARENT, BROWSER); + let fields = layout_fields(&memory, LAYOUT, Some(PARENT)).unwrap(); + assert!(fields.contents.is_empty()); + } + + #[test] + fn nfr6_the_frame_view_field_is_the_one_holding_the_browser_view() { + let memory = window(0x38, 0x50, 0xB8); + // With the laid out view known, and without it through the browser view's own children. + assert_eq!( + frame_fields(&memory, FRAME, Some(BROWSER), Some(PARENT)), + Some(vec![0x340, 0x348]) + ); + assert_eq!( + frame_fields(&memory, FRAME, None, Some(PARENT)), + Some(vec![0x340, 0x348]) + ); + assert_eq!(frame_fields(&memory, FRAME, Some(OTHER), Some(PARENT)), None); + assert_eq!(frame_fields(&memory, FRAME, None, None), None); + } + + #[test] + fn nfr6_a_views_widget_is_found_without_a_vtable_slot() { + let memory = window(0x38, 0x50, 0xB8); + assert_eq!(root_of(&memory, CONTENTS, PARENT), Some(ROOT)); + let fields = widget_fields(&memory, ROOT, PARENT).expect("the widget fields"); + assert_eq!( + fields, + WidgetFields { + widget_in_root: 0x3A0, + root_in_widget: 0x1D8 + } + ); + assert_eq!(widget_of(&memory, CONTENTS, PARENT, fields), WIDGET); + assert_eq!(widget_of(&memory, BROWSER, PARENT, fields), WIDGET); + // A view whose tree has no widget, or whose root is not the widget's, has none. + let mut loose = window(0x38, 0x50, 0xB8); + loose.set(WIDGET + 0x1D8, OTHER); + assert_eq!(widget_of(&loose, CONTENTS, PARENT, fields), 0); + // Only a root view gives the fields. + assert_eq!(widget_fields(&memory, BROWSER, PARENT), None); + } + + #[test] + fn nfr6_a_reflected_value_must_agree_with_the_row() { + let both: &[usize] = &[0x340, 0x348]; + assert_eq!(settle(Some(both), Some(0x340)), Some(0x340)); + assert_eq!(settle(Some(both), Some(0x348)), Some(0x348)); + assert_eq!(settle(Some(&both[..1]), Some(0x3B0)), None); + assert_eq!(settle(Some(&[0x3B0][..]), None), Some(0x3B0)); + assert_eq!(settle(None, Some(0x38)), Some(0x38)); + assert_eq!(settle(Some(&[][..]), Some(0x38)), Some(0x38)); + assert_eq!(settle(None, None), None); + } +} diff --git a/rivet/runtime/windows/src/features/address_bar.rs b/rivet/runtime/windows/src/features/address_bar.rs index 6bec37f..857437d 100644 --- a/rivet/runtime/windows/src/features/address_bar.rs +++ b/rivet/runtime/windows/src/features/address_bar.rs @@ -421,7 +421,7 @@ pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) return; } let row = &crate::builds::get().side_panel; - let Some(contents) = area.bounds(row.contents_container) else { + let Some(contents) = area.contents() else { crate::trace::trace_changed( "bar layout", "address bar: the layout has no page container", diff --git a/rivet/runtime/windows/src/features/app_window.rs b/rivet/runtime/windows/src/features/app_window.rs index da9220d..3682695 100644 --- a/rivet/runtime/windows/src/features/app_window.rs +++ b/rivet/runtime/windows/src/features/app_window.rs @@ -22,12 +22,27 @@ pub(crate) fn recorded(name: &str) -> Option { }) } -/// Where a view of `build` keeps its parent and its children. They follow from where it keeps its -/// bounds by the member order of `views::View`, so they are not values of the build's row. +/// Where a view of `build` keeps its parent and its children. The view walk of `reflect` finds them +/// at run time from the window's own views: each child of the browser view names it as its parent +/// right before its list of children. They also follow from where the view keeps its bounds by the +/// member order of `views::View`, which confirms the walk. So they are not values of the build's +/// row. pub(crate) fn view_fields(build: &crate::builds::Build) -> Option<(usize, usize)> { use crate::chromium::view::View; - let parent = View::parent_offset(build.layout.view_bounds_offset)?; - Some((parent, View::children_offset(parent))) + let by_bounds = View::parent_offset(build.layout.view_bounds_offset) + .map(|parent| (parent, View::children_offset(parent))); + agreed_view_fields(crate::chromium::window_views::walked_view_fields(), by_bounds) +} + +/// The view fields from the walk and from the bounds offset. Both must agree when both are known. +pub(crate) fn agreed_view_fields( + walked: Option<(usize, usize)>, + by_bounds: Option<(usize, usize)>, +) -> Option<(usize, usize)> { + match (walked, by_bounds) { + (Some(walked), Some(by_bounds)) => (walked == by_bounds).then_some(walked), + (walked, by_bounds) => walked.or(by_bounds), + } } /// A value named in the test profile's `rivet-spike.txt`. @@ -715,6 +730,21 @@ pub(crate) fn install_features() { mod tests { use super::*; + #[test] + fn nfr6_the_view_walk_gives_the_view_fields_and_the_bounds_offset_confirms_them() { + // The walk and the bounds offset agree on Chromium 156 and later. + assert_eq!( + agreed_view_fields(Some((0x198, 0x1A0)), Some((0x198, 0x1A0))), + Some((0x198, 0x1A0)) + ); + // A walk that disagrees with the bounds offset leaves the fields unknown. + assert_eq!(agreed_view_fields(Some((0x190, 0x198)), Some((0x198, 0x1A0))), None); + // Either alone stands until the other is known. + assert_eq!(agreed_view_fields(Some((0x190, 0x198)), None), Some((0x190, 0x198))); + assert_eq!(agreed_view_fields(None, Some((0x198, 0x1A0))), Some((0x198, 0x1A0))); + assert_eq!(agreed_view_fields(None, None), None); + } + #[test] fn fr9_the_mini_window_is_the_window_the_browser_created_for_the_tab() { let tooltip = 0x10 as HWND; diff --git a/rivet/runtime/windows/src/features/frame_layout.rs b/rivet/runtime/windows/src/features/frame_layout.rs index 6cd592e..56e4b19 100644 --- a/rivet/runtime/windows/src/features/frame_layout.rs +++ b/rivet/runtime/windows/src/features/frame_layout.rs @@ -888,12 +888,13 @@ unsafe fn clip_panel(frame: *mut c_void) { let Some((set_layer, set_radius, set_masks)) = PANEL_LAYER.get() else { return; }; - // BrowserFrameViewWin holds BrowserView's BrowserWindow subobject at +0x340. - let browser_window = - *(frame.cast::().add(bv().frame_browser_window_offset) as *const *mut u8); - if browser_window.is_null() { + // The frame view keeps BrowserView's BrowserWindow subobject in its tracker of the browser view. + let Some(browser_window) = + crate::chromium::window_views::frame_browser_view(frame as usize, None) + .map(|view| view as *mut u8) + else { return; - } + }; let browser = browser_window .sub(bv().browser_window_in_view) .cast::(); diff --git a/rivet/runtime/windows/src/features/pane_infobar.rs b/rivet/runtime/windows/src/features/pane_infobar.rs index 0897948..313323f 100644 --- a/rivet/runtime/windows/src/features/pane_infobar.rs +++ b/rivet/runtime/windows/src/features/pane_infobar.rs @@ -56,8 +56,7 @@ pub(crate) fn narrow(bar: [i32; 4], contents: [i32; 4], columns: (i32, i32)) -> /// The page area step: the bars above the page take the main pane's columns while a split is /// open, and their height is kept for the second view's placement. pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { - let row = &crate::builds::get().side_panel; - let Some(contents) = area.bounds(row.contents_container) else { + let Some(contents) = area.contents() else { return; }; let page = *contents; diff --git a/rivet/runtime/windows/src/features/side_panel.rs b/rivet/runtime/windows/src/features/side_panel.rs index 8df8f8c..0e6e622 100644 --- a/rivet/runtime/windows/src/features/side_panel.rs +++ b/rivet/runtime/windows/src/features/side_panel.rs @@ -133,12 +133,7 @@ pub unsafe fn objects(window: HWND) -> Option { if base == 0 || !checked() { return None; } - let browser_window = match frame_layout::frame_view(window) { - Some(frame) => { - *((frame + crate::builds::get().layout.frame_browser_window_offset) as *const usize) - } - None => page_area::laid_out_host(window)?, - }; + let browser_window = browser_window_of(window)?; let cached = FOUND.with(|found| found.borrow().get(&(window as isize)).copied()); let vtables = [ bv().coordinator_vtable, @@ -162,15 +157,19 @@ pub unsafe fn objects(window: HWND) -> Option { Some(found) } +/// The `BrowserWindow` subobject of a window's `BrowserView`, which the frame view keeps in its +/// tracker of the browser view. A window whose frame view is not known has it from the layout, +/// which lays that same view out. +unsafe fn browser_window_of(window: HWND) -> Option { + let host = page_area::laid_out_host(window); + match frame_layout::frame_view(window) { + Some(frame) => crate::chromium::window_views::frame_browser_view(frame, host), + None => host, + } +} + unsafe fn find_objects(window: HWND, base: usize) -> Option { - // The frame view holds the `BrowserWindow` subobject of `BrowserView` at +0x340. A build whose - // frame view is not recorded has it from the layout, which lays that same view out. - let browser_window = match frame_layout::frame_view(window) { - Some(frame) => { - *((frame + crate::builds::get().layout.frame_browser_window_offset) as *const usize) - } - None => page_area::laid_out_host(window)?, - }; + let browser_window = browser_window_of(window)?; if !readable(browser_window, 8) { return None; } @@ -905,13 +904,13 @@ pub(crate) unsafe fn on_page_area(area: &mut PageArea) { let rail = rail_of(area.window); area.rail = rail; if rail > 0 { - if let Some(contents) = area.bounds(bv().contents_container) { + if let Some(contents) = area.contents() { let side_panel = area.bounds(bv().side_panel); let animation = area.bounds(bv().side_panel_animation); let outline = area.bounds(bv().contents_outline); let panel_view = area.field(bv().side_panel); let page = area - .bounds(bv().page_area) + .page() .map(|bounds| *bounds) .unwrap_or([0; 4]); // The page starts where the browser's vertical tab list ends. @@ -1228,7 +1227,7 @@ mod tests { // The traced app window layout keeps the page area, the top row and the page container here. assert_eq!( (whale.page_area, whale.toolbar, whale.contents_container), - (0x28, 0x40, 0x90) + (Some(0x28), 0x40, Some(0x90)) ); let samsung = row("Samsung Internet"); assert!(samsung.supported); @@ -1236,7 +1235,7 @@ mod tests { assert_eq!(samsung.old_layout, Some(true)); assert_eq!( (samsung.contents_container, samsung.side_panel), - (0x80, 0x98) + (Some(0x80), 0x98) ); } diff --git a/rivet/runtime/windows/src/features/sidebar_page.rs b/rivet/runtime/windows/src/features/sidebar_page.rs index f3854b6..733935a 100644 --- a/rivet/runtime/windows/src/features/sidebar_page.rs +++ b/rivet/runtime/windows/src/features/sidebar_page.rs @@ -174,7 +174,7 @@ pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) return; } let row = &crate::builds::get().side_panel; - let page = area.bounds(row.page_area).map(|bounds| *bounds); + let page = area.page().map(|bounds| *bounds); let Some(page_right) = page.map(|page| page[0] + page[2]) else { return; }; @@ -182,7 +182,7 @@ pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) let Some(side_panel) = area.bounds(offset) else { continue; }; - if let Some(contents) = area.bounds(row.contents_container) { + if let Some(contents) = area.contents() { float_over(&mut *contents, &mut *side_panel, page_right); } if let Some(outline) = area.bounds(row.contents_outline) { diff --git a/rivet/runtime/windows/src/features/widgets.rs b/rivet/runtime/windows/src/features/widgets.rs index 71459fa..54a6d97 100644 --- a/rivet/runtime/windows/src/features/widgets.rs +++ b/rivet/runtime/windows/src/features/widgets.rs @@ -67,13 +67,22 @@ pub(crate) fn rivet_widgets() -> Vec { all().iter().map(|(widget, _)| *widget).collect() } -/// The widget that holds `view`, which must point at a `views::View`: `View::GetWidget` through -/// the view's own vtable. +/// The widget that holds `view`, which must point at a `views::View`: the widget the root of its +/// view tree names, as `View::GetWidget` returns it. Where the row has `GetWidget`'s vtable slot, +/// the slot confirms the path once. pub(crate) unsafe fn widget_holding(view: *mut c_void) -> usize { - let table = *(view as *const usize); - let get_widget: Pointer = - std::mem::transmute(*(table as *const usize).add(row().get_widget_slot)); - get_widget(view) as usize + let by_slot = |view: usize| { + let Some(slot) = row().get_widget_slot else { + return 0; + }; + let table = *(view as *const usize); + let get_widget: Pointer = std::mem::transmute(*(table as *const usize).add(slot)); + get_widget(view as *const c_void) as usize + }; + let by_slot: Option<&dyn Fn(usize) -> usize> = row() + .get_widget_slot + .map(|_| &by_slot as &dyn Fn(usize) -> usize); + crate::chromium::window_views::widget_holding(view as usize, by_slot) } #[cfg(test)] diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index c625721..8be16e6 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -2810,6 +2810,8 @@ pub unsafe fn attach(window: HWND) -> bool { layout_dpi(window) )); crate::features::control::serve(window); + // The window's views are found by their class names from here on, on a worker thread. + crate::chromium::window_views::walk_views_once(window); } else { crate::features::look::first_look(window, crate::features::look::FirstLook::AttachFailed); } diff --git a/rivet/runtime/windows/src/hooks/page_area.rs b/rivet/runtime/windows/src/hooks/page_area.rs index aac6672..d34479c 100644 --- a/rivet/runtime/windows/src/hooks/page_area.rs +++ b/rivet/runtime/windows/src/hooks/page_area.rs @@ -117,6 +117,16 @@ impl PageArea<'_> { self.bounds.of(view) } + /// The bounds the layout gave the view of the pages, found by its class name or the row. + pub(crate) unsafe fn contents(&mut self) -> Option<*mut [i32; 4]> { + self.bounds(crate::chromium::window_views::contents_field()) + } + + /// The bounds the layout gave the area below the top row, found by its class name or the row. + pub(crate) unsafe fn page(&mut self) -> Option<*mut [i32; 4]> { + self.bounds(crate::chromium::window_views::page_area_field()) + } + /// The bounds the layout gave every view it placed, where the source can list them. pub(crate) unsafe fn all_bounds(&mut self) -> Vec<(usize, *mut [i32; 4])> { let views = self.bounds.views(); @@ -166,9 +176,10 @@ pub(crate) unsafe fn run( HOST_VIEWS.with(|views| views.borrow_mut().insert(window as isize, host)); // A layout without the recorded page container is traced once, which shows where it keeps it. static DUMPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - let unknown = row().contents_container != crate::builds::ABSENT + let contents = crate::chromium::window_views::contents_field(); + let unknown = contents != crate::builds::ABSENT && bounds - .of(*(this.cast::().add(row().contents_container) as *const usize)) + .of(*(this.cast::().add(contents) as *const usize)) .is_none() && crate::trace::tracing() && !DUMPED.swap(true, std::sync::atomic::Ordering::Relaxed); @@ -182,7 +193,7 @@ pub(crate) unsafe fn run( window, rail: 0, }; - if let Some(page) = area.bounds(row().page_area) { + if let Some(page) = area.page() { let page = *page; AREAS.with(|areas| { areas @@ -191,8 +202,12 @@ pub(crate) unsafe fn run( }); } let traced = |area: &mut PageArea| { - [row().page_area, row().contents_container, row().toolbar] - .map(|offset| area.bounds(offset).map(|bounds| *bounds)) + [ + crate::chromium::window_views::page_area_field(), + crate::chromium::window_views::contents_field(), + row().toolbar, + ] + .map(|offset| area.bounds(offset).map(|bounds| *bounds)) }; let before = traced(&mut area); for step in STEPS { @@ -252,10 +267,7 @@ pub(crate) unsafe fn install() -> Result<(), String> { /// the browser's layout works on. unsafe fn host_of(window: HWND) -> Option { let frame = frame_layout::frame_view(window)?; - let at = frame + crate::builds::get().layout.frame_browser_window_offset; - readable(at, 8) - .then(|| *(at as *const usize)) - .filter(|view| *view != 0) + crate::chromium::window_views::frame_browser_view(frame, None) } /// Lays the browser view out again, which runs the patched layout. A window the layout has not run diff --git a/rivet/runtime/windows/src/row_data.rs b/rivet/runtime/windows/src/row_data.rs index b1381d1..c71f0b3 100644 --- a/rivet/runtime/windows/src/row_data.rs +++ b/rivet/runtime/windows/src/row_data.rs @@ -399,15 +399,34 @@ mod tests { #[test] fn nfr6_a_row_without_a_field_is_refused_and_named() { let mut row = builds::CHROME.to_row(); - row["toolbar"] - .as_object_mut() - .unwrap() - .remove("get_widget_slot"); + row["toolbar"].as_object_mut().unwrap().remove("get_color"); let error = match builds::Build::from_row(&row) { Err(error) => error, - Ok(_) => panic!("a row with no widget slot was accepted"), + Ok(_) => panic!("a row with no colour getter was accepted"), }; - assert_eq!(error, "toolbar: get_widget_slot is missing"); + assert_eq!(error, "toolbar: get_color is missing"); + } + + #[test] + fn nfr6_a_row_without_window_offsets_is_not_blocked() { + // The window's views and widget are found by class name and the view tree, so a row made + // without these values still reads, and has none of them. + let mut row = builds::CHROME.to_row(); + for (part, key) in [ + ("layout", "frame_browser_window_offset"), + ("side_panel", "contents_container"), + ("side_panel", "host_view"), + ("side_panel", "page_area"), + ("toolbar", "get_widget_slot"), + ] { + row[part].as_object_mut().unwrap().remove(key); + } + let build = builds::Build::from_row(&row).expect("a row without window offsets reads"); + assert_eq!(build.layout.frame_browser_window_offset, None); + assert_eq!(build.side_panel.contents_container, None); + assert_eq!(build.side_panel.host_view, None); + assert_eq!(build.side_panel.page_area, None); + assert_eq!(build.toolbar.get_widget_slot, None); } #[test] From 5cbde791eac0a3699b3e92e5447559b33997ddb5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:33:26 +0000 Subject: [PATCH 04/29] Publish: develop 540e5b4 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .../platform/windows/src/bin/chrome-builds.rs | 4 +- rivet/platform/windows/src/command_ids.rs | 45 ++ rivet/platform/windows/src/lib.rs | 1 + rivet/platform/windows/src/row_class.rs | 532 ++++++++++++++++++ rivet/platform/windows/src/row_features.rs | 109 +++- rivet/platform/windows/src/row_port.rs | 258 +++++++-- rivet/platform/windows/src/row_resolve.rs | 126 ++++- .../windows/src/browsers/chromium/commands.rs | 6 + rivet/runtime/windows/src/features/tabs.rs | 106 +++- 9 files changed, 1122 insertions(+), 65 deletions(-) create mode 100644 rivet/platform/windows/src/row_class.rs diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index e37dac5..af0f457 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -325,8 +325,10 @@ fn find( drop(old); let bytes = read(module)?; let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; + // A class table of a views class is also found again by the class name its symbol gives. + let classes = row_port::class_names(&named); let (mut row, mut report) = - row_port::find_candidate(&prior, &prints, prior_pe.as_ref(), version, &pe); + row_port::find_candidate(&prior, &prints, prior_pe.as_ref(), &classes, version, &pe); // No symbols name `screen_origin` here: a prior row without it gives a row without it. row_port::seed_screen_origin(&mut row, &[], &pe, &mut report); report.review.extend(row_port::hand_only_review(&prior)); diff --git a/rivet/platform/windows/src/command_ids.rs b/rivet/platform/windows/src/command_ids.rs index fe805cb..f6543d5 100644 --- a/rivet/platform/windows/src/command_ids.rs +++ b/rivet/platform/windows/src/command_ids.rs @@ -23,6 +23,31 @@ pub const DEV_TOOLS: &[(u16, u16, u32, u32)] = &[ (159, 8154, 40023, 40005), ]; +/// `IDC_NEW_TAB` per Chromium milestone, with the branch the header was read at. It is the command +/// of Ctrl+T and of the browser's own new tab button. Milestone 143 is the base of Samsung +/// Internet 30. +pub const NEW_TAB: &[(u16, u16, usize)] = &[ + (143, 7499, 34014), + (150, 7871, 34014), + (151, 7922, 34014), + (152, 7977, 34014), + (153, 8010, 34014), + (154, 8037, 34014), + (155, 8059, 34014), + (156, 8078, 34014), + (157, 8103, 34014), + (158, 8127, 34014), + (159, 8154, 34014), +]; + +/// The new tab command id of a Chromium milestone. +pub fn new_tab(milestone: u16) -> Option { + NEW_TAB + .iter() + .find(|(known, _, _)| *known == milestone) + .map(|(_, _, id)| *id) +} + /// The paths of a row's values that are these command ids. A row generator never carries them: /// it writes the value this table gives, or zero for a milestone it does not know. pub const ROW_PATHS: &[&str] = &["toolbar.dev.inspect", "toolbar.dev.console"]; @@ -52,4 +77,24 @@ mod tests { .windows(2) .all(|pair| pair[0].0 + 1 == pair[1].0 && pair[0].1 < pair[1].1)); } + + #[test] + fn nfr6_the_new_tab_command_comes_from_chromium_command_ids() { + for milestone in (150..=159u16).chain([143]) { + assert_eq!(new_tab(milestone), Some(34014), "{milestone}"); + } + // An unread milestone never borrows a neighbour's value. + for milestone in [142, 144, 149, 160] { + assert_eq!(new_tab(milestone), None, "{milestone}"); + } + assert!(NEW_TAB + .windows(2) + .all(|pair| pair[0].0 < pair[1].0 && pair[0].1 < pair[1].1)); + // The same branches as the developer commands, which were read from the same headers. + for (milestone, branch, _) in NEW_TAB { + if let Some(dev) = DEV_TOOLS.iter().find(|dev| dev.0 == *milestone) { + assert_eq!(dev.1, *branch, "{milestone}"); + } + } + } } diff --git a/rivet/platform/windows/src/lib.rs b/rivet/platform/windows/src/lib.rs index 81c550f..f364973 100644 --- a/rivet/platform/windows/src/lib.rs +++ b/rivet/platform/windows/src/lib.rs @@ -10,6 +10,7 @@ pub mod command_ids; pub mod control; pub mod focus; pub mod hold; +pub mod row_class; pub mod row_features; pub mod row_port; pub mod row_recipe; diff --git a/rivet/platform/windows/src/row_class.rs b/rivet/platform/windows/src/row_class.rs new file mode 100644 index 0000000..6a0112a --- /dev/null +++ b/rivet/platform/windows/src/row_class.rs @@ -0,0 +1,532 @@ +//! Finds the class table of a views class in a build by the class name its `ui::metadata` holds. +//! +//! Chromium's views classes declare their metadata with `METADATA_HEADER` and `BEGIN_METADATA` +//! (`ui/base/metadata/metadata_header_macros.h` and `metadata_impl_macros.h`). `MetaData()` keeps +//! the class's `ClassMetaData` in a static pointer that code holding the class name fills on first +//! use, and `GetClassMetaData`, the second slot of the class's `ui::metadata::MetaDataProvider` +//! table, returns it, directly or through a jump to `MetaData()`. A constructor of the class writes +//! that table into the object next to the class's own table, which sits at the object's start +//! because `views::View` names `ui::LayerDelegate` as its first base (`ui/views/view.h`). +//! +//! So, from the name: the code that uses the text and its callers, the static pointer the first of +//! them to load one loads, every function that loads the same pointer as its result, the tables +//! whose second slot holds one of them, and the table the constructors that write such a table +//! write at offset zero of the same object. The load is read the way the runtime's +//! `chromium/reflect.rs` reads it, so the generator and the runtime agree on the static a table +//! names. Nothing is guessed: a step that finds nothing, or more than one table, gives no table. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use crate::chrome_build::PeFile; +use crate::row_port::x64; + +/// How many levels of callers above the code that uses the name are read. +const CALLER_DEPTH: usize = 3; +/// How many functions the callers may grow to before the name counts as too common to follow. +const CALLERS_MOST: usize = 64; +/// How many jumps a `GetClassMetaData` thunk may take to the function that loads the static. +const THUNK_DEPTH: usize = 3; +/// How far a constructor is read. +const BODY_MOST: u32 = 0x4000; + +/// Where the code at `at` gets its result: the target of its first `lea rax, [rip+d]`, or the word +/// its first `mov rax, [rip+d]` reads, after up to three jumps that may first move `this` with +/// `sub rcx, n` or `add rcx, n`. The same reading as the runtime's `reflect::load_target`. +pub fn load_target(pe: &PeFile, at: u32) -> Option<(u32, bool)> { + let mut code_at = at; + for _ in 0..3 { + let head = pe.read(code_at, 12)?; + let skip = match head[..3] { + [0x48, 0x83, 0xE9] | [0x48, 0x83, 0xC1] => 4, + [0x48, 0x81, 0xE9] | [0x48, 0x81, 0xC1] => 7, + _ => 0, + }; + if head[skip] != 0xE9 { + break; + } + let rel = i32::from_le_bytes(head[skip + 1..skip + 5].try_into().ok()?); + code_at = u32::try_from(i64::from(code_at) + skip as i64 + 5 + i64::from(rel)).ok()?; + } + let code = pe.read(code_at, 128)?; + let at = (0..code.len() - 7).find(|&i| { + code[i] == 0x48 && matches!(code[i + 1], 0x8D | 0x8B) && code[i + 2] == 0x05 + })?; + let rel = i32::from_le_bytes(code[at + 3..at + 7].try_into().ok()?); + let target = u32::try_from(i64::from(code_at) + at as i64 + 7 + i64::from(rel)).ok()?; + Some((target, code[at + 1] == 0x8B)) +} + +/// Every place outside the code that holds `name` as a zero-terminated text. +fn texts(pe: &PeFile, name: &str) -> BTreeSet { + let mut needle = name.as_bytes().to_vec(); + needle.push(0); + let mut found = BTreeSet::new(); + for (base, bytes, is_code) in pe.sections() { + if is_code || bytes.len() < needle.len() { + continue; + } + for (at, window) in bytes.windows(needle.len()).enumerate() { + if window[0] == needle[0] && window == needle.as_slice() { + found.insert(base + at as u32); + } + } + } + found +} + +/// A `lea` or `mov` of a 64-bit register with a RIP-relative operand. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct RipUse { + at: u32, + target: u32, + register: u8, + /// A `mov`, which reads the word at the target, rather than a `lea`. + word: bool, +} + +fn rip_use(bytes: &[u8], rva: u32) -> Option { + let [rex, op, modrm, ..] = *bytes else { + return None; + }; + if rex & 0xF8 != 0x48 || !matches!(op, 0x8D | 0x8B) || modrm & 0xC7 != 0x05 { + return None; + } + let rel = i32::from_le_bytes(bytes.get(3..7)?.try_into().ok()?); + Some(RipUse { + at: rva, + target: u32::try_from(i64::from(rva) + 7 + i64::from(rel)).ok()?, + register: (((rex >> 2) & 1) << 3) | ((modrm >> 3) & 7), + word: op == 0x8B, + }) +} + +/// Every RIP-relative `lea` or `mov` in the code whose target is one of `targets`. +fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { + let mut found = Vec::new(); + for (base, bytes, is_code) in pe.sections() { + if !is_code { + continue; + } + for at in 0..bytes.len().saturating_sub(7) { + if let Some(found_use) = rip_use(&bytes[at..at + 7], base + at as u32) { + if targets.contains(&found_use.target) { + found.push(found_use); + } + } + } + } + found +} + +/// Every direct `call` or `jmp` into one of `targets`, as (site, whether it is a jump). +fn branches_into(pe: &PeFile, targets: &BTreeSet) -> Vec<(u32, bool)> { + let mut found = Vec::new(); + for (base, bytes, is_code) in pe.sections() { + if !is_code { + continue; + } + for at in 0..bytes.len().saturating_sub(5) { + if !matches!(bytes[at], 0xE8 | 0xE9) { + continue; + } + let rel = i32::from_le_bytes(bytes[at + 1..at + 5].try_into().expect("in range")); + let site = base + at as u32; + let target = i64::from(site) + 5 + i64::from(rel); + if u32::try_from(target).is_ok_and(|target| targets.contains(&target)) { + found.push((site, bytes[at] == 0xE9)); + } + } + } + found +} + +/// The function part the exception table lists around an address. +fn enclosing(ranges: &BTreeMap, rva: u32) -> Option { + let (start, end) = ranges.range(..=rva).next_back()?; + (rva < *end).then_some(*start) +} + +/// The static pointers of the class metadata the code that uses the class name fills. +fn statics_of(pe: &PeFile, ranges: &BTreeMap, name: &str) -> BTreeSet<(u32, bool)> { + let texts = texts(pe, name); + if texts.is_empty() { + return BTreeSet::new(); + } + let mut layer: BTreeSet = rip_uses(pe, &texts) + .iter() + .filter(|found| !found.word) + .filter_map(|found| enclosing(ranges, found.at)) + .collect(); + let mut all = layer.clone(); + for _ in 0..CALLER_DEPTH { + if layer.is_empty() || all.len() > CALLERS_MOST { + break; + } + layer = branches_into(pe, &layer) + .into_iter() + .filter_map(|(site, _)| enclosing(ranges, site)) + .filter(|function| !all.contains(function)) + .collect(); + all.extend(&layer); + } + if all.len() > CALLERS_MOST { + return BTreeSet::new(); + } + all.iter() + .filter_map(|function| load_target(pe, *function)) + .filter(|(target, _)| !pe.is_code(*target)) + .collect() +} + +/// The functions whose result is `found`: those that load it, and the thunks that jump to them. +fn getters(pe: &PeFile, ranges: &BTreeMap, found: (u32, bool)) -> BTreeSet { + let loads = rip_uses(pe, &BTreeSet::from([found.0])); + let mut getters: BTreeSet = loads + .iter() + .filter(|each| each.register == 0 && each.word == found.1) + .filter_map(|each| enclosing(ranges, each.at)) + .filter(|function| load_target(pe, *function) == Some(found)) + .collect(); + let mut layer = getters.clone(); + for _ in 0..THUNK_DEPTH { + let mut next = BTreeSet::new(); + for (site, jump) in branches_into(pe, &layer) { + if !jump { + continue; + } + // `jmp`, `sub rcx, n; jmp` or `add rcx, n; jmp`, as a thunk of a base that is not the + // object's first moves `this` back before it jumps. + let starts = [ + Some(site), + site.checked_sub(4).filter(|start| { + pe.read(*start, 3) + .is_some_and(|head| matches!(head, [0x48, 0x83, 0xE9 | 0xC1])) + }), + site.checked_sub(7).filter(|start| { + pe.read(*start, 3) + .is_some_and(|head| matches!(head, [0x48, 0x81, 0xE9 | 0xC1])) + }), + ]; + for start in starts.into_iter().flatten() { + if !getters.contains(&start) && load_target(pe, start) == Some(found) { + next.insert(start); + } + } + } + if next.is_empty() { + break; + } + getters.extend(&next); + layer = next; + } + getters +} + +/// The tables outside the code whose second slot holds one of `functions`. +fn tables_holding(pe: &PeFile, functions: &BTreeSet) -> BTreeSet { + let wanted: HashSet = functions + .iter() + .map(|function| pe.image_base() + u64::from(*function)) + .collect(); + let mut found = BTreeSet::new(); + for (base, bytes, is_code) in pe.sections() { + if is_code { + continue; + } + for at in (8..bytes.len().saturating_sub(7)).step_by(8) { + let word = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("in range")); + if wanted.contains(&word) { + found.insert(base + at as u32 - 8); + } + } + } + found +} + +/// A table a constructor writes into an object: the table, the register that holds the object +/// and how far into the object it goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Store { + index: usize, + table: u32, + base: u8, + offset: i64, +} + +/// `mov [base + offset], register` with a 64-bit register, as (base, offset). +fn store_of(raw: &[u8], register: u8) -> Option<(u8, i64)> { + let rex = raw.first().copied().filter(|byte| byte & 0xF0 == 0x40)?; + let [_, op, modrm, ..] = *raw else { + return None; + }; + if rex & 8 == 0 || op != 0x89 { + return None; + } + let mode = modrm >> 6; + let rm = modrm & 7; + // Register to register, a SIB byte or a RIP-relative operand is not a store into an object. + if mode == 3 || rm == 4 || (mode == 0 && rm == 5) { + return None; + } + if ((((rex >> 2) & 1) << 3) | ((modrm >> 3) & 7)) != register { + return None; + } + let offset = match mode { + 0 => 0, + 1 => i64::from(*raw.get(3)? as i8), + _ => i64::from(i32::from_le_bytes(raw.get(3..7)?.try_into().ok()?)), + }; + Some((((rex & 1) << 3) | rm, offset)) +} + +/// The tables a function writes into objects: a `lea` of a table outside the code, then a store +/// of that register. +fn stores_in(pe: &PeFile, start: u32, end: u32) -> Vec { + let length = end.saturating_sub(start).min(BODY_MOST) as usize; + let Some(bytes) = pe.read(start, length) else { + return vec![]; + }; + let mut steps = Vec::new(); + let mut at = 0; + while at < bytes.len() { + let Some(instruction) = x64::decode_body(&bytes[at..]) else { + break; + }; + if instruction.length == 0 || at + instruction.length > bytes.len() { + break; + } + steps.push(&bytes[at..at + instruction.length]); + at += instruction.length; + } + let mut stores = Vec::new(); + let mut offset = 0u32; + for (index, raw) in steps.iter().enumerate() { + let rva = start + offset; + offset += raw.len() as u32; + let Some(lea) = (raw.len() == 7).then(|| rip_use(raw, rva)).flatten() else { + continue; + }; + if lea.word || pe.is_code(lea.target) { + continue; + } + if let Some((base, at)) = steps + .get(index + 1) + .and_then(|next| store_of(next, lea.register)) + { + stores.push(Store { + index, + table: lea.target, + base, + offset: at, + }); + } + } + stores +} + +/// The table each constructor that writes `provider` writes at the start of the same object. +fn first_tables(pe: &PeFile, ranges: &BTreeMap, provider: u32) -> BTreeSet { + let writers: BTreeSet = rip_uses(pe, &BTreeSet::from([provider])) + .iter() + .filter(|each| !each.word) + .filter_map(|each| enclosing(ranges, each.at)) + .collect(); + let mut found = BTreeSet::new(); + for writer in writers { + let stores = stores_in(pe, writer, ranges[&writer]); + for written in stores.iter().filter(|store| store.table == provider) { + let first = stores + .iter() + .filter(|store| { + store.base == written.base && store.offset == 0 && store.table != provider + }) + .min_by_key(|store| store.index.abs_diff(written.index)); + if let Some(first) = first { + found.insert(first.table); + } + } + } + found +} + +/// The class tables of the views class `name` in `pe`, each the table at the start of its +/// objects. More than one means the name does not tell one class table, and the caller takes none. +pub fn class_tables(pe: &PeFile, name: &str) -> BTreeSet { + let ranges = pe.function_ranges(); + let mut found = BTreeSet::new(); + for each in statics_of(pe, &ranges, name) { + let getters = getters(pe, &ranges, each); + if getters.is_empty() { + continue; + } + for provider in tables_holding(pe, &getters) { + found.extend(first_tables(pe, &ranges, provider)); + } + } + found +} + +/// The class a public table symbol names, as `??_7EdgeBrowserFrameViewWin@@6BLayerDelegate@ui@@@` +/// names `EdgeBrowserFrameViewWin`. The class name its metadata holds has no namespace. +pub fn class_of_table_symbol(symbol: &str) -> Option<&str> { + let rest = symbol.strip_prefix("??_7")?; + let name = rest.split('@').next()?; + (!name.is_empty() && name.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')) + .then_some(name) +} + +#[cfg(test)] +mod tests { + use super::*; + + const IMAGE_BASE: u64 = 0x1_8000_0000; + + /// A module with code at 0x1000, read-only data at 0x2000 and data at 0x3000, each 0x1000 + /// long, and an exception table at 0x2f00 that lists `ranges`. + fn module(code: &[(u32, Vec)], ranges: &[(u32, u32)]) -> Vec { + let mut bytes = vec![0u8; 0x400]; + bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); + bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); + bytes[0x86..0x88].copy_from_slice(&3u16.to_le_bytes()); + bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes()); + let optional = 0x98; + bytes[optional..optional + 2].copy_from_slice(&0x20bu16.to_le_bytes()); + bytes[optional + 24..optional + 32].copy_from_slice(&IMAGE_BASE.to_le_bytes()); + let directory = optional + 112 + 24; + bytes[directory..directory + 4].copy_from_slice(&0x2f00u32.to_le_bytes()); + bytes[directory + 4..directory + 8] + .copy_from_slice(&(12 * ranges.len() as u32).to_le_bytes()); + for (index, flags) in [0x6000_0020u32, 0x4000_0040, 0xC000_0040].iter().enumerate() { + let header = optional + 240 + 40 * index; + let rva = 0x1000 * (index as u32 + 1); + bytes[header + 8..header + 12].copy_from_slice(&0x1000u32.to_le_bytes()); + bytes[header + 12..header + 16].copy_from_slice(&rva.to_le_bytes()); + bytes[header + 16..header + 20].copy_from_slice(&0x1000u32.to_le_bytes()); + let raw = 0x400 + 0x1000 * index as u32; + bytes[header + 20..header + 24].copy_from_slice(&raw.to_le_bytes()); + bytes[header + 36..header + 40].copy_from_slice(&flags.to_le_bytes()); + } + bytes.resize(0x400 + 0x3000, 0); + // Code between functions is padding. + bytes[0x400..0x1400].fill(0xCC); + let mut table = Vec::new(); + for (start, end) in ranges { + table.extend_from_slice(&start.to_le_bytes()); + table.extend_from_slice(&end.to_le_bytes()); + table.extend_from_slice(&0u32.to_le_bytes()); + } + let mut code = code.to_vec(); + code.push((0x2f00, table)); + for (rva, data) in code { + let at = 0x400 + (rva - 0x1000) as usize; + bytes[at..at + data.len()].copy_from_slice(&data); + } + bytes + } + + fn rel(from: u32, length: u32, to: u32) -> [u8; 4] { + (to as i32 - (from + length) as i32).to_le_bytes() + } + + fn pointer(rva: u32) -> Vec { + (IMAGE_BASE + u64::from(rva)).to_le_bytes().to_vec() + } + + /// `name`'s metadata at 0x3000, filled by its `MetaData()` at 0x1100 from the text at 0x2100. + /// `GetClassMetaData` at 0x1200 is a thunk to it in slot 1 of the `MetaDataProvider` table at + /// 0x2200, and the constructor at 0x1400 writes the class table at 0x2400 at the object's + /// start and the provider's table 0x58 bytes in. + fn class_module(name: &str) -> Vec { + let mut meta = vec![0x48, 0x8B, 0x05]; + meta.extend(rel(0x1100, 7, 0x3000)); + // test rax, rax; jne +7 + meta.extend([0x48, 0x85, 0xC0, 0x75, 0x07]); + meta.extend([0x48, 0x8D, 0x0D]); + meta.extend(rel(0x110c, 7, 0x2100)); + meta.push(0xC3); + let mut thunk = vec![0x48, 0x83, 0xE9, 0x58, 0xE9]; + thunk.extend(rel(0x1204, 5, 0x1100)); + let mut constructor = vec![0x48, 0x8D, 0x05]; + constructor.extend(rel(0x1400, 7, 0x2400)); + // mov [rsi], rax + constructor.extend([0x48, 0x89, 0x06]); + constructor.extend([0x48, 0x8D, 0x0D]); + constructor.extend(rel(0x140a, 7, 0x2200)); + // mov [rsi + 0x58], rcx + constructor.extend([0x48, 0x89, 0x4E, 0x58]); + constructor.push(0xC3); + let mut text = name.as_bytes().to_vec(); + text.push(0); + let mut provider = pointer(0x1300); + provider.extend(pointer(0x1200)); + let mut class = pointer(0x1300); + class.extend(pointer(0x1310)); + module( + &[ + (0x1100, meta), + (0x1200, thunk), + (0x1300, vec![0xC3]), + (0x1310, vec![0xC3]), + (0x1400, constructor), + (0x2100, text), + (0x2200, provider), + (0x2400, class), + ], + &[(0x1100, 0x1120), (0x1300, 0x1301), (0x1310, 0x1311), (0x1400, 0x1420)], + ) + } + + #[test] + fn nfr6_a_frame_vtable_is_found_from_its_class_name() { + let bytes = class_module("EdgeBrowserFrameViewWin"); + let pe = PeFile::parse(&bytes).unwrap(); + // The getter reads the static the way the runtime reads it. + assert_eq!(load_target(&pe, 0x1200), Some((0x3000, true))); + assert_eq!(class_tables(&pe, "EdgeBrowserFrameViewWin"), BTreeSet::from([0x2400])); + // A name the build does not hold, or holds only as part of a longer one, gives nothing. + assert!(class_tables(&pe, "BrowserFrameViewWin").is_empty()); + assert!(class_tables(&pe, "WindowsCaptionButton").is_empty()); + } + + #[test] + fn nfr6_a_class_whose_constructor_writes_no_first_table_gives_none() { + let mut bytes = class_module("BrowserView"); + // The constructor stores another register than the one it loaded the class table into, so + // no table is known at the object's start. + let at = 0x400 + 0x407; + assert_eq!(bytes[at..at + 3], [0x48, 0x89, 0x06]); + bytes[at + 2] = 0x0E; + let pe = PeFile::parse(&bytes).unwrap(); + assert_eq!(store_of(&[0x48, 0x89, 0x0E], 1), Some((6, 0))); + assert_eq!(store_of(&[0x48, 0x89, 0x4E, 0x58], 1), Some((6, 0x58))); + assert!(class_tables(&pe, "BrowserView").is_empty()); + } + + #[test] + fn nfr6_a_class_name_counts_only_where_it_gives_the_prior_table_in_the_prior_build() { + let prior = class_module("WindowsCaptionButton"); + let prior = PeFile::parse(&prior).unwrap(); + let new = class_module("WindowsCaptionButton"); + let new = PeFile::parse(&new).unwrap(); + let place = crate::row_resolve::class_place(&prior, &new, 0x2400, "WindowsCaptionButton"); + assert_eq!(place, Ok(0x2400)); + // The prior row's table is another one: the name does not tell this table. + let other = crate::row_resolve::class_place(&prior, &new, 0x2200, "WindowsCaptionButton"); + assert!(other.unwrap_err().contains("in the prior build")); + let missing = crate::row_resolve::class_place(&prior, &new, 0x2400, "CustomFloatingCorner"); + assert!(missing.is_err()); + } + + #[test] + fn nfr6_a_table_symbol_names_its_class() { + assert_eq!( + class_of_table_symbol("??_7EdgeBrowserFrameViewWin@@6BLayerDelegate@ui@@@"), + Some("EdgeBrowserFrameViewWin") + ); + assert_eq!( + class_of_table_symbol("??_7VerticalTabStripStateControllerImpl@tabs@@6B@"), + Some("VerticalTabStripStateControllerImpl") + ); + assert_eq!(class_of_table_symbol("?Layout@BrowserView@@UEAAXXZ"), None); + } +} diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs index bfdbac9..266fa47 100644 --- a/rivet/platform/windows/src/row_features.rs +++ b/rivet/platform/windows/src/row_features.rs @@ -78,6 +78,7 @@ pub const ROW_FEATURES: &[RowFeature] = &[ "side_panel.extension_entry", "side_panel.features_coordinator", "side_panel.features_offset", + "side_panel.browser_offset", ], off: &[Off::Flag("side_panel.supported")], clear: Clear::Zero, @@ -104,6 +105,48 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Absent, checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], }, + RowFeature { + // The Sidebar's own functions and class tables. Only `features/side_panel.rs` reads them, + // and only once the Sidebar's targets are all recorded. + name: "sidebar", + paths: &[ + "side_panel.side_panel_vtable", + "side_panel.coordinator_vtable", + "side_panel.browser_view_view_vtable", + "side_panel.show", + "side_panel.entry_id_to_string", + "side_panel.toggle", + "side_panel.entry_showing", + "side_panel.registry_from", + "side_panel.get_color_provider", + "side_panel.generate_colors_css", + "side_panel.event_handler_for_point", + ], + off: &[Off::Flag("side_panel.supported")], + clear: Clear::Absent, + checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], + }, + RowFeature { + // The vertical tab controller's functions and class tables. Only + // `features/vertical_tabs.rs` reads them, and only once its targets are all recorded. + name: "vertical tabs", + paths: &[ + "vertical.slot", + "vertical.should_display", + "vertical.destructor", + "vertical.browser_view_for_browser", + "vertical.hwnd_for_view", + "vertical.notify_mode_changed", + "vertical.browser_view_view_vtable", + "vertical.region_preferred_size", + "vertical.region_preferred_size_slot", + "vertical.region_minimum_size", + "vertical.invalidate_layout", + ], + off: &[Off::Flag("vertical.supported")], + clear: Clear::Absent, + checks: &[], + }, RowFeature { name: "app window", paths: &["app_window."], @@ -126,6 +169,14 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Empty, checks: &["dev-row"], }, + RowFeature { + // Font functions recorded beside the developer colours. No runtime calls them. + name: "developer colours", + paths: &["toolbar.dev.font_list_new", "toolbar.dev.font_new"], + off: &[], + clear: Clear::Absent, + checks: &["dev-row"], + }, RowFeature { name: "frame colour", paths: &["layout.frame_ids", "layout.caption_ink_ids"], @@ -177,18 +228,26 @@ pub fn leave_out(build: &mut Value, path: &str) { /// values of the build at all, and a row holds zero for them. pub struct UnusedWhen { pub paths: &'static [&'static str], - /// The address that decides it. - pub address: &'static str, - /// Unused while that address is recorded, or while it is absent. - pub while_recorded: bool, + /// The value of the row that decides it. + pub when: When, pub why: &'static str, } +/// What a deciding value of a row must be for other values to be unused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum When { + /// An address the build records. + Recorded(&'static str), + /// An address the build does not record. + Absent(&'static str), + /// A flag that is false. + False(&'static str), +} + pub const UNUSED_WHEN: &[UnusedWhen] = &[ UnusedWhen { paths: &["tabs.tab_collection", "tabs.tab_contents"], - address: "tabs.tab_at", - while_recorded: true, + when: When::Recorded("tabs.tab_at"), why: "the build has its own GetWebContentsAt", }, UnusedWhen { @@ -198,10 +257,14 @@ pub const UNUSED_WHEN: &[UnusedWhen] = &[ "vertical.toolbar_in_view", "vertical.toolbar_leading", ], - address: "vertical.window_feature", - while_recorded: false, + when: When::Absent("vertical.window_feature"), why: "the tab strip is left out through ShouldDrawTabStrip, not the window feature", }, + UnusedWhen { + paths: &["vertical.should_draw_tab_strip"], + when: When::False("vertical.detour_strip"), + why: "the build does not leave its tab strip out by a detour", + }, ]; /// The field a value path names: `layout.frame_ids[2]` names `layout.frame_ids`. @@ -244,8 +307,13 @@ pub fn unused(build: &Value, path: &str) -> Option<&'static str> { .iter() .find(|rule| { rule.paths.iter().any(|each| covers(each, path)) - && at(build, rule.address) - .is_some_and(|value| is_recorded(value) == rule.while_recorded) + && match rule.when { + When::Recorded(address) => at(build, address).is_some_and(is_recorded), + When::Absent(address) => { + at(build, address).is_some_and(|value| !is_recorded(value)) + } + When::False(flag) => at(build, flag).and_then(Value::as_bool) == Some(false), + } }) .map(|rule| rule.why) } @@ -289,6 +357,27 @@ pub fn switch_off(build: &mut Value, feature: &RowFeature) { } } +/// Turns off the feature of that name, through every part of the row it has, and clears each of +/// its values that a path names, so a feature that is off holds nothing of another build. +pub fn turn_off(build: &mut Value, name: &str) { + for feature in ROW_FEATURES.iter().filter(|feature| feature.name == name) { + switch_off(build, feature); + for path in feature.paths.iter().filter(|path| !path.ends_with('.')) { + clear(build, path, feature.clear); + } + } +} + +/// How a value of a feature that is off is cleared where it sits: an address inside a list of +/// signatures becomes zero with the rest of that list, since a list holds no single address. +pub fn clear_value(build: &mut Value, path: &str, feature: &RowFeature) { + let how = match feature.clear { + Clear::Absent if path.contains('[') => Clear::Zero, + how => how, + }; + clear(build, path, how); +} + /// The key of a row that names the features it has off and the values that turned them off. The /// runtime reads only `frame` and `build`, so it changes nothing in a browser; the feature gate /// reads it. diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index b619d29..1f73777 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -79,6 +79,9 @@ pub struct PortReport { /// Values no instruction of the new build gave that the runtime finds by reflection, so the /// row leaves them out instead of carrying them. pub reflected: Vec, + /// Addresses no method placed in the new build that only features this row turns off hold, + /// with the values that held them. The row clears those values like the feature's others. + pub unplaced: Vec, /// Whether every carried value must be settled: the milestone changed, or values were read. #[serde(skip)] must_check: bool, @@ -88,6 +91,10 @@ pub struct PortReport { /// Why each value that was tried could not be read. #[serde(skip)] unread: BTreeMap, + /// Values of features the row turns off whatever the milestone, with the reason: an address + /// that has no place in the new build, or a recipe that failed. + #[serde(skip)] + off_values: BTreeMap, } fn is_address(value: u64) -> bool { @@ -1019,12 +1026,25 @@ fn settle_carried(row: &mut Value, report: &mut PortReport) { report .derived .extend(crate::row_recipe::follow(&mut row["build"])); - if !report.must_check { - return; + let mut off: BTreeMap<&'static str, (&'static RowFeature, Vec)> = BTreeMap::new(); + for (path, reason) in std::mem::take(&mut report.off_values) { + if let Some(feature) = row_features::feature_of(&path) { + row_features::clear_value(&mut row["build"], &path, feature); + report.unread.insert(path.clone(), reason); + off.entry(feature.name) + .or_insert((feature, Vec::new())) + .1 + .push(path); + } } + let must_check = report.must_check; + let carried = if must_check { + std::mem::take(&mut report.carried) + } else { + Vec::new() + }; let mut left = Vec::new(); - let mut off: BTreeMap<&'static str, (&'static RowFeature, Vec)> = BTreeMap::new(); - for path in std::mem::take(&mut report.carried) { + for path in carried { if row_features::is_reflected(&path) { row_features::leave_out(&mut row["build"], &path); report.unread.remove(&path); @@ -1046,8 +1066,8 @@ fn settle_carried(row: &mut Value, report: &mut PortReport) { } } let mut entries = Vec::new(); - for (name, (feature, paths)) in off { - row_features::switch_off(&mut row["build"], feature); + for (name, (_, paths)) in off { + row_features::turn_off(&mut row["build"], name); let reasons: Vec = paths .iter() .map(|path| match report.unread.remove(path) { @@ -1063,6 +1083,9 @@ fn settle_carried(row: &mut Value, report: &mut PortReport) { if !entries.is_empty() { row[row_features::SWITCHED_OFF] = json!(entries); } + if !must_check { + return; + } let mut unchecked = Vec::new(); for path in &left { match report.unread.remove(path) { @@ -1282,12 +1305,20 @@ fn finish_row( // Last, since the recipes read the addresses of the new build. let derived = crate::row_recipe::derive_row(&mut row["build"], pe); report.derived.extend(derived.read); - report.review.extend( - derived - .failed - .into_iter() - .map(|reason| format!("a value could not be read from the new build: {reason}")), - ); + for failure in derived.failed { + // A value of a feature the runtime can do without turns that feature off instead. + let path = failure.split(": ").next().unwrap_or_default(); + if crate::row_features::feature_of(path).is_some() { + report.off_values.insert( + path.to_owned(), + format!("could not be read from the new build: {failure}"), + ); + } else { + report + .review + .push(format!("a value could not be read from the new build: {failure}")); + } + } (row, report) } @@ -1450,7 +1481,7 @@ pub fn find_row(prior: &Value, version: &str, pe: &PeFile) -> Result Result, prior_pe: Option<&PeFile>, + classes: &BTreeMap, version: &str, pe: &PeFile, ) -> (Value, PortReport) { - let (row, mut report) = begin_row(prior, version, prior_pe.is_none()); + let (mut row, mut report) = begin_row(prior, version, prior_pe.is_none()); report.made_without_pdb = true; let prior_starts = prior_pe.map(PeFile::function_starts).unwrap_or_default(); let targets = fingerprint_targets(prior); @@ -1486,7 +1519,15 @@ pub fn find_candidate( // Each address its fingerprint did not pin down, with its review line, waits for the methods // that read the prior build next to the new one. let mut wanted: BTreeMap = BTreeMap::new(); - let want = |kind, candidates: Option>| row_resolve::Wanted { kind, candidates }; + let want = |target: u32, kind: row_resolve::Kind, candidates: Option>| { + row_resolve::Wanted { + kind, + candidates, + class: (kind == row_resolve::Kind::Table) + .then(|| classes.get(&target).cloned()) + .flatten(), + } + }; for target in &targets { match stored.get(&format!("{target:#x}")) { Some(Value::String(text)) => match hex(text).filter(|shape| shape.len() >= ANCHOR) { @@ -1520,7 +1561,7 @@ pub fn find_candidate( } else { row_resolve::Kind::Table }; - wanted.insert(*target, (line, want(kind, None))); + wanted.insert(*target, (line, want(*target, kind, None))); } None => report.review.push(line), } @@ -1565,15 +1606,15 @@ pub fn find_candidate( "{target:#x} matches no function start, of {} places", all.len() ); - wanted.insert(*target, (line, want(function, None))); + wanted.insert(*target, (line, want(*target, function, None))); } [] => { let line = format!("{target:#x} matches no place"); - wanted.insert(*target, (line, want(function, None))); + wanted.insert(*target, (line, want(*target, function, None))); } many => { let line = format!("{target:#x} matches {} places", many.len()); - wanted.insert(*target, (line, want(function, Some(many.to_vec())))); + wanted.insert(*target, (line, want(*target, function, Some(many.to_vec())))); } } } @@ -1581,7 +1622,7 @@ pub fn find_candidate( let table = row_resolve::Kind::Table; let Some(function) = moved.get(holds).copied() else { let line = format!("{target:#x}: the function in slot {slot} was not found"); - wanted.insert(*target, (line, want(table, None))); + wanted.insert(*target, (line, want(*target, table, None))); continue; }; match find_table(pe, *slot, function).as_slice() { @@ -1597,11 +1638,14 @@ pub fn find_candidate( many.len() ); let candidates = (!many.is_empty()).then(|| many.to_vec()); - wanted.insert(*target, (line, want(table, candidates))); + wanted.insert(*target, (line, want(*target, table, candidates))); } } } let mut followed = BTreeMap::new(); + // Each address no method placed, with its review line. Those that only features the runtime + // can do without hold do not stop the row. + let mut open: BTreeMap = BTreeMap::new(); match prior_pe { Some(prior_pe) if !wanted.is_empty() => { let table_targets: BTreeSet = tables @@ -1629,17 +1673,16 @@ pub fn find_candidate( .reasons .get(target) .map_or("no method was run", String::as_str); - report.review.push(format!("{line}; not settled: {reason}")); + open.insert(*target, format!("{line}; not settled: {reason}")); } } } report.settled.extend(resolution.settled); followed = resolution.followed; } - _ => report - .review - .extend(wanted.into_values().map(|(line, _)| line)), + _ => open.extend(wanted.into_iter().map(|(target, (line, _))| (target, line))), } + release_unplaced(prior, &mut row, open, &mut report); let places: BTreeSet = moved.values().copied().collect(); if places.len() != moved.len() { report @@ -1658,6 +1701,73 @@ pub fn find_candidate( (row, report) } +/// Settles each address no method placed in the new build. Where every value that holds it belongs +/// to a feature the runtime can do without, or is not read in this row, those values are cleared +/// and the features go off, and the address is listed in the report. An address that a part the +/// window cannot do without holds, the frame or the page area layout, stops the row with its line. +fn release_unplaced( + prior: &Value, + row: &mut Value, + open: BTreeMap, + report: &mut PortReport, +) { + use crate::row_features::{self, Clear}; + if open.is_empty() { + return; + } + let mut holders: BTreeMap> = BTreeMap::new(); + let mut note = |path: &str, value: &mut Value| { + if READ_FROM_CODE.iter().any(|field| path.ends_with(field)) { + return; + } + if let Some(address) = read_address(value).filter(|value| is_address(*value)) { + holders + .entry(address as u32) + .or_default() + .push(path.trim_start_matches('.').to_owned()); + } + }; + let mut build = prior["build"].clone(); + walk_addresses("", &mut build, &mut note); + // The frame part has no feature to turn off, so its paths always stop the row. + let mut frame = frame_addresses(&prior["frame"]); + walk_addresses("frame", &mut frame, &mut note); + for (target, line) in open { + let paths = holders.remove(&target).unwrap_or_default(); + let needed = paths.is_empty() + || paths.iter().any(|path| { + path.starts_with("frame.") + || (row_features::feature_of(path).is_none() + && row_features::unused(&row["build"], path).is_none()) + }); + if needed { + report.review.push(line); + continue; + } + for path in &paths { + match row_features::feature_of(path) { + Some(feature) => { + row_features::clear_value(&mut row["build"], path, feature); + report.off_values.insert( + path.clone(), + format!("has no place in the new build: {line}"), + ); + } + None => { + let why = row_features::unused(&row["build"], path).unwrap_or_default(); + // A list holds no single address, so a value in one becomes zero. + let how = if path.contains('[') { Clear::Zero } else { Clear::Absent }; + row_features::clear(&mut row["build"], path, how); + report.unused.push(format!("{path}: {why}")); + } + } + } + report + .unplaced + .push(format!("{line}; cleared from {}", paths.join(", "))); + } +} + /// The value at a path such as `layout.frame_ids[2]` or `toolbar.dev.colours[3][0]`. fn value_at<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { let mut current = value; @@ -1854,6 +1964,26 @@ pub fn check_against_pdb( Ok(differences) } +/// The views class each class table of the prior row is named after by the prior build's public +/// symbols, for the tables found again by their class name. A table whose symbols name two classes +/// is left out. +pub fn class_names(named: &BTreeMap)>) -> BTreeMap { + let mut out = BTreeMap::new(); + for (target, (distance, names)) in named { + if *distance != 0 { + continue; + } + let classes: BTreeSet<&str> = names + .iter() + .filter_map(|name| crate::row_class::class_of_table_symbol(stable_name(name))) + .collect(); + if let [only] = classes.into_iter().collect::>()[..] { + out.insert(*target, only.to_owned()); + } + } + out +} + /// Adds to each review line that starts with a prior address the public name that address lies /// in, from the prior build's symbols, so a person sees which function was not found. pub fn name_review_lines(review: &mut [String], named: &BTreeMap)>) { @@ -2645,6 +2775,10 @@ mod tests { row } + fn no_classes() -> BTreeMap { + BTreeMap::new() + } + fn find(row: &Value, code: &[(u32, Vec)], version: &str) -> Result> { let bytes = module(&code_refs(code)); let pe = PeFile::parse(&bytes).unwrap(); @@ -2745,7 +2879,7 @@ mod tests { ) -> (Value, PortReport) { let bytes = module(&code_refs(code)); let pe = PeFile::parse(&bytes).unwrap(); - find_candidate(&verified_row(), prints, None, version, &pe) + find_candidate(&verified_row(), prints, None, &BTreeMap::new(), version, &pe) } /// `module` with an exception table at 0x10f000 that lists `starts`. @@ -2802,7 +2936,8 @@ mod tests { new[3].1 = paint_reading(new_loads); let bytes = with_ranges(&new, &ranges(0x2000, new[3].1.len())); let pe = PeFile::parse(&bytes).unwrap(); - find_candidate(&verified_row(), &prints, Some(&prior_pe), "1.0.0.3", &pe) + let classes = BTreeMap::new(); + find_candidate(&verified_row(), &prints, Some(&prior_pe), &classes, "1.0.0.3", &pe) } #[test] @@ -2874,7 +3009,8 @@ mod tests { let (prints, _) = fingerprints_of(&verified, &prior_pe); let bytes = with_starts(&code, &[0x103100, 0x103200, 0x103300]); let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = find_candidate(&verified, &prints, Some(&prior_pe), "1.0.0.3", &pe); + let (row, report) = + find_candidate(&verified, &prints, Some(&prior_pe), &no_classes(), "1.0.0.3", &pe); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); // A part moved out of another function starts where it may, and a whole function does not. @@ -2885,13 +3021,15 @@ mod tests { )); let bytes = with_starts(&split, &[0x103100, 0x103200, 0x103300, 0x105308]); let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = find_candidate(&verified, &prints, Some(&prior_pe), "1.0.0.3", &pe); + let (row, report) = + find_candidate(&verified, &prints, Some(&prior_pe), &no_classes(), "1.0.0.3", &pe); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); // Bytes that match only inside another function are no place at all. let bytes = with_starts(&code, &[0x103100, 0x103200]); let pe = PeFile::parse(&bytes).unwrap(); - let (_, report) = find_candidate(&verified, &prints, Some(&prior_pe), "1.0.0.3", &pe); + let (_, report) = + find_candidate(&verified, &prints, Some(&prior_pe), &no_classes(), "1.0.0.3", &pe); assert!( report .review @@ -2955,6 +3093,62 @@ mod tests { ); } + #[test] + fn nfr6_unplaced_functions_of_a_feature_that_is_off_do_not_block_the_row() { + // Edge 157's row stopped on functions no method placed, most of which only features the + // runtime can do without hold. The prior build gave these two no fingerprint. + let mut prior = verified_row(); + prior["build"]["split"] = json!({ + "supported": true, + "remove_split": "0x101400", + "remove_split_prologue": "4883ec28488b0d10000000", + "signatures": [["0x101400", "4883ec28"]], + }); + prior["build"]["vertical"] = json!({ + "supported": false, + "detour_strip": false, + "should_draw_tab_strip": "0x101500", + "should_draw_tab_strip_prologue": "4883ec28", + }); + let bytes = module(&code_refs(&shifted_code(0x2000, 0x44))); + let pe = PeFile::parse(&bytes).unwrap(); + let prints = prints_of_prior(); + let (row, report) = find_candidate(&prior, &prints, None, &no_classes(), "1.0.0.3", &pe); + assert_eq!(report.review, Vec::::new()); + assert_eq!(report.unplaced.len(), 2, "{:?}", report.unplaced); + assert!(report.unplaced[0].starts_with("0x101400: no fingerprint")); + assert!(report.unplaced[0].ends_with("split.remove_split, split.signatures[0][0]")); + let build = &row["build"]; + // The feature is off and holds nothing of the prior build. + assert_eq!(build["split"]["supported"], false); + assert_eq!(build["split"]["remove_split"], "0x0"); + assert_eq!(build["split"]["signatures"][0][0], "0x0"); + assert_eq!(row[crate::row_features::SWITCHED_OFF][0]["feature"], "split view"); + assert!( + report.switched_off[0] + .starts_with("split view is off: split.remove_split has no place"), + "{:?}", + report.switched_off + ); + // A function this build does not read is absent, and turns nothing off. + assert_eq!(build["vertical"]["should_draw_tab_strip"], "0x7fff0000"); + assert_eq!(report.switched_off.len(), 1, "{:?}", report.switched_off); + // The rest of the row is found. + assert_eq!(build["toolbar"]["paint"], "0x103300"); + + // The same address held by a part the window cannot do without still stops the row. + prior["build"]["layout"] = json!({"frame_vtable": "0x101400"}); + let prints = prints_of_prior(); + let (row, report) = find_candidate(&prior, &prints, None, &no_classes(), "1.0.0.3", &pe); + assert!( + report.review.iter().any(|line| line == "0x101400: no fingerprint"), + "{:?}", + report.review + ); + assert!(report.unplaced.iter().all(|line| !line.contains("0x101400"))); + assert_eq!(row["build"]["split"]["supported"], true); + } + #[test] fn nfr6_a_row_made_without_its_pdb_is_checked_against_the_pdb_row() { let (mut row, _) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index f6d0bf3..f65f0f9 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -14,7 +14,13 @@ //! - a text it uses: it refers to a text the new build holds once, and exactly one function there //! refers to that text; //! - for a class table, references to it (a function known in both builds loads it from the same -//! spot) and its slots (exactly one candidate holds the same functions in the same slots). +//! spot) and its slots (exactly one candidate holds the same functions in the same slots); +//! - for the class table of a views class, its class name: `row_class` reads the table from the +//! name the class's `ui::metadata` holds, and the same reading must give the prior table in the +//! prior build; +//! - its fingerprint: a place a class table gives, by its class name or by a slot, that is one of +//! the places the fingerprint matched. Those methods do not search among the fingerprint's +//! places, so the two agree independently. //! //! Anything else stays unresolved with its reason, and its row goes to a person. @@ -680,6 +686,8 @@ pub enum Method { Text, References, Slots, + ClassName, + Fingerprint, } impl fmt::Display for Method { @@ -691,6 +699,8 @@ impl fmt::Display for Method { Method::Text => "a text it uses", Method::References => "references to it", Method::Slots => "its slots", + Method::ClassName => "its class name", + Method::Fingerprint => "its fingerprint", }) } } @@ -752,6 +762,47 @@ pub enum Kind { pub struct Wanted { pub kind: Kind, pub candidates: Option>, + /// For a class table, the views class the prior build's public symbol names it after. + pub class: Option, +} + +/// The class table a views class name gives in the new build, once the same reading gives the +/// prior table in the prior build. +pub fn class_place( + old_pe: &PeFile, + new_pe: &PeFile, + target: u32, + class: &str, +) -> Result { + let old = crate::row_class::class_tables(old_pe, class); + if old != BTreeSet::from([target]) { + return Err(format!( + "its class name {class} gives {} tables in the prior build, not the prior table alone", + old.len() + )); + } + let new = crate::row_class::class_tables(new_pe, class); + match new.iter().copied().collect::>().as_slice() { + [only] => Ok(*only), + many => Err(format!( + "its class name {class} gives {} tables in the new build", + many.len() + )), + } +} + +/// What the fingerprint adds to the places a class table gives: agreement when the table gives +/// exactly one place and that place is one of the fingerprint's. +pub fn fingerprint_agrees( + given: &BTreeSet, + candidates: Option<&[u32]>, +) -> Option<(Method, u32)> { + let [only] = given.iter().copied().collect::>()[..] else { + return None; + }; + candidates + .is_some_and(|candidates| candidates.contains(&only)) + .then_some((Method::Fingerprint, only)) } /// What the methods found. @@ -818,6 +869,23 @@ pub fn resolve( } let callers = calls_into(&new, &called); + // A class name gives a table from the build alone, so it is read once. + let mut by_class = BTreeMap::new(); + let mut class_reasons = BTreeMap::new(); + for (target, want) in wanted { + let Some(class) = want.class.as_deref().filter(|_| want.kind == Kind::Table) else { + continue; + }; + match class_place(old_pe, new_pe, *target, class) { + Ok(place) => { + by_class.insert(*target, place); + } + Err(reason) => { + class_reasons.insert(*target, reason); + } + } + } + let mut pending: BTreeSet = wanted.keys().copied().collect(); for _ in 0..ROUNDS { let followed = follow(&mut old, &mut new, &known); @@ -849,7 +917,9 @@ pub fn resolve( for place in by_its_calls(&mut new, calls, &candidates) { answers.push((Method::ItsCalls, place)); } - for place in by_table_slot(&old, &new, &known, &table_pairs, target) { + let slotted = by_table_slot(&old, &new, &known, &table_pairs, target); + answers.extend(fingerprint_agrees(&slotted, want.candidates.as_deref())); + for place in slotted { answers.push((Method::TableSlot, place)); } if let Some(place) = by_text(&texts_of[&target], &users) { @@ -860,11 +930,29 @@ pub fn resolve( if let Some(place) = by_reference(&followed, target) { answers.push((Method::References, place)); } - let candidates = match &want.candidates { + let mut candidates = match &want.candidates { Some(list) => list.clone(), None => table_candidates(&old, &new, &known, target), }; - for place in by_slots(&old, &new, &known, target, &candidates) { + // The table a class name gives is also compared slot by slot, which checks + // its structure apart from the name. + if let Some(place) = by_class.get(&target) { + if !candidates.contains(place) { + candidates.push(*place); + } + } + let mut slots = by_slots(&old, &new, &known, target, &candidates); + if let Some(place) = by_class.get(&target).copied() { + answers.push((Method::ClassName, place)); + let given = BTreeSet::from([place]); + answers.extend(fingerprint_agrees(&given, want.candidates.as_deref())); + // Several tables holding the same slots is no answer of their own; the + // class name tells which of them is the class's. + if slots.len() > 1 && slots.contains(&place) { + slots = vec![place]; + } + } + for place in slots { answers.push((Method::Slots, place)); } } @@ -882,6 +970,10 @@ pub fn resolve( found_any = true; } Err(reason) => { + let reason = match class_reasons.get(&target) { + Some(class) => format!("{reason}; {class}"), + None => reason, + }; resolution.reasons.insert(target, reason); } } @@ -1231,6 +1323,7 @@ pub(crate) mod tests { Wanted { kind: Kind::Function, candidates: Some(NEW_TARGETS.to_vec()), + class: None, }, )]); resolve(&old, &new, &known, &wanted, &BTreeSet::from([OLD_TABLE])) @@ -1242,11 +1335,34 @@ pub(crate) mod tests { assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); assert_eq!( resolution.settled, - ["0x101100 -> 0x103100 by calls into it and its table slot"] + ["0x101100 -> 0x103100 by calls into it and its table slot and its fingerprint"] ); assert!(resolution.reasons.is_empty(), "{:?}", resolution.reasons); } + #[test] + fn nfr6_a_class_table_is_taken_where_its_class_name_and_fingerprint_agree() { + // Edge 157's frame table: two tables hold the frame's layout function in slot 24, and its + // class name tells which of them is the frame view's. + let candidates: &[u32] = &[0x11b5_19a8, 0x11b5_2528]; + let by_name = BTreeSet::from([candidates[1]]); + let mut answers = vec![(Method::ClassName, candidates[1])]; + answers.extend(fingerprint_agrees(&by_name, Some(candidates))); + assert_eq!(answers[1], (Method::Fingerprint, candidates[1])); + let (place, methods) = decide(&answers, Some(candidates)).unwrap(); + assert_eq!(place, candidates[1]); + assert_eq!(methods.len(), 2); + // A class name alone is one method. + let alone = decide(&answers[..1], None).unwrap_err(); + assert!(alone.starts_with("only its class name found it"), "{alone}"); + // A place that is not one of the fingerprint's places gets no agreement from it. + assert_eq!(fingerprint_agrees(&BTreeSet::from([0x11b5_3000]), Some(candidates)), None); + // A table slot that gives two places gives the fingerprint nothing to agree with. + let both: BTreeSet = candidates.iter().copied().collect(); + assert_eq!(fingerprint_agrees(&both, Some(candidates)), None); + assert_eq!(fingerprint_agrees(&by_name, None), None); + } + #[test] fn nfr6_methods_that_disagree_leave_the_function_unresolved() { let resolution = run(&new_module(NEW_TARGETS[1]), true); diff --git a/rivet/runtime/windows/src/browsers/chromium/commands.rs b/rivet/runtime/windows/src/browsers/chromium/commands.rs index 4ada104..99f2283 100644 --- a/rivet/runtime/windows/src/browsers/chromium/commands.rs +++ b/rivet/runtime/windows/src/browsers/chromium/commands.rs @@ -45,6 +45,12 @@ pub(crate) fn dev_tools(browser: &str, version: [u16; 4]) -> (u32, u32) { .unwrap_or((0, 0)) } +/// The new tab command id of a build, from Chromium's public header for its milestone, or `None` +/// when that milestone's header was not read. +pub(crate) fn new_tab(browser: &str, version: [u16; 4]) -> Option { + chromium_milestone(browser, version).and_then(rivet_platform_windows::command_ids::new_tab) +} + /// Whether a browser keeps Chromium's command ids without public source to confirm it. Brave /// publishes its changes and adds its own ids only from 56000, so it keeps Chromium's. Edge, Whale /// and Samsung Internet take the value of their Chromium milestone, which needs a regression check diff --git a/rivet/runtime/windows/src/features/tabs.rs b/rivet/runtime/windows/src/features/tabs.rs index 66ca561..ebcacdb 100644 --- a/rivet/runtime/windows/src/features/tabs.rs +++ b/rivet/runtime/windows/src/features/tabs.rs @@ -628,25 +628,58 @@ pub unsafe fn new_tab(window: HWND) -> bool { opened } +/// How a Rivet window opens a tab in a build. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum NewTabBy { + /// The browser's own new tab command, sent as its menu sends it. It ends in `chrome::NewTab` + /// like the function below, on the same thread, so the new tab hook sees Rivet's own tab. + Command(usize), + /// `chrome::NewTab` itself, for a build whose milestone has no command id that was read. + Function(usize), +} + +/// How a Rivet window of `build` opens a tab: the public command when the build's milestone has +/// one, else the recorded function, else not at all. +pub(crate) fn new_tab_by(build: &Build) -> Option { + let command = crate::browsers::chromium::commands::new_tab(build.browser, build.version); + choose_new_tab(command, build.tabs.new_tab, build.tabs.new_tab_address) +} + +fn choose_new_tab( + command: Option, + new_tab: usize, + new_tab_address: Option, +) -> Option { + if let Some(id) = command { + return Some(NewTabBy::Command(id)); + } + // A build that passes its window interface takes another first argument than the browser. + (new_tab != crate::builds::ABSENT && new_tab_address.is_none()) + .then_some(NewTabBy::Function(new_tab)) +} + unsafe fn open_new_tab(window: HWND) -> bool { - let Some(base) = base() else { return false }; - if bv().new_tab == crate::builds::ABSENT || bv().new_tab_address.is_some() { - // The browser's own new-tab command, as its menu sends it. - const IDC_NEW_TAB: usize = 34014; - windows_sys::Win32::UI::WindowsAndMessaging::SendMessageW( - window, - windows_sys::Win32::UI::WindowsAndMessaging::WM_COMMAND, - IDC_NEW_TAB, - 0, - ); - return true; + match new_tab_by(crate::builds::get()) { + Some(NewTabBy::Command(id)) => { + windows_sys::Win32::UI::WindowsAndMessaging::SendMessageW( + window, + windows_sys::Win32::UI::WindowsAndMessaging::WM_COMMAND, + id, + 0, + ); + true + } + Some(NewTabBy::Function(rva)) => { + let Some(base) = base() else { return false }; + let Some(browser) = browser(base, window) else { + return false; + }; + // Chrome accepts the new-tab command source value 5. + function::(base, rva)(browser, 5); + true + } + None => false, } - let Some(browser) = browser(base, window) else { - return false; - }; - // Chrome accepts the new-tab command source value 5. - function::(base, bv().new_tab)(browser, 5); - true } /// One-shot diagnostic for the isolated test profile. @@ -914,3 +947,42 @@ mod first_page_tests { assert_eq!(first_page(true, false, false, start()), None); } } + +#[cfg(test)] +mod new_tab_tests { + use super::{choose_new_tab, new_tab_by, NewTabBy}; + use crate::builds; + + #[test] + fn nfr6_a_new_tab_uses_the_public_command() { + // Every build Rivet knows opens a tab with the browser's own command, also those that + // record `chrome::NewTab`, so the function is only the new tab hook's. + for build in builds::compiled() { + assert_eq!( + new_tab_by(build), + Some(NewTabBy::Command(34014)), + "{} {:?}", + build.browser, + build.version + ); + } + // A milestone whose header was not read has no command, and only a recorded function that + // takes the browser itself opens a tab there. + assert_eq!( + crate::browsers::chromium::commands::new_tab("Google Chrome", [160, 0, 1, 1]), + None + ); + let function = 0x0123_4560; + assert_eq!( + choose_new_tab(None, function, None), + Some(NewTabBy::Function(function)) + ); + assert_eq!(choose_new_tab(None, function, Some(0x68)), None); + assert_eq!(choose_new_tab(None, builds::ABSENT, None), None); + // With a command the function is never called, recorded or not. + assert_eq!( + choose_new_tab(Some(34014), function, None), + Some(NewTabBy::Command(34014)) + ); + } +} From 6a3bc075650b250ce6672e241f50c1285beecbb1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:34:53 +0000 Subject: [PATCH 05/29] Publish: develop 536e0b2 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_port.rs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 1f73777..9e2c2ae 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -1554,17 +1554,13 @@ pub fn find_candidate( } _ => { let line = format!("{target:#x}: no fingerprint"); - match prior_pe { - Some(prior_pe) => { - let kind = if prior_pe.is_code(*target) { - row_resolve::Kind::Function - } else { - row_resolve::Kind::Table - }; - wanted.insert(*target, (line, want(*target, kind, None))); - } - None => report.review.push(line), - } + // Without the prior module no method can place it, but it is still settled with + // the other open addresses, so a feature that is off does not stop the row. + let kind = match prior_pe { + Some(prior_pe) if !prior_pe.is_code(*target) => row_resolve::Kind::Table, + _ => row_resolve::Kind::Function, + }; + wanted.insert(*target, (line, want(*target, kind, None))); } } } From 9bb350d58e012b34adf5d5b439b3d74dad5f5605 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:06:09 +0000 Subject: [PATCH 06/29] Publish: develop ae7b049 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .github/scripts/rows/fetch-browser.ps1 | 28 ++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/.github/scripts/rows/fetch-browser.ps1 b/.github/scripts/rows/fetch-browser.ps1 index 926c4f9..61ec9c9 100644 --- a/.github/scripts/rows/fetch-browser.ps1 +++ b/.github/scripts/rows/fetch-browser.ps1 @@ -78,10 +78,34 @@ if ($Browser -eq 'Brave') { # Brave publishes only update-client installers. Their payload is split into several branch # streams that 7-Zip reads as one, so the files come out damaged. A runner is thrown away after # the job and has no Brave of its own, so the silent installer installs this exact build. - $installed = Join-Path $env:ProgramFiles 'BraveSoftware\Brave-Browser\Application' - if (Test-Path $installed) { throw "This runner already has Brave at $installed, so the build would not be the one asked for." } + # The installer picks a machine or a user install by itself, and its update client may still be + # copying files after the setup process has exited, so every place is checked until the build's + # own version folder appears. + $places = @( + (Join-Path $env:ProgramFiles 'BraveSoftware\Brave-Browser\Application'), + (Join-Path ${env:ProgramFiles(x86)} 'BraveSoftware\Brave-Browser\Application'), + (Join-Path $env:LOCALAPPDATA 'BraveSoftware\Brave-Browser\Application') + ) + foreach ($place in $places) { + if (Test-Path $place) { throw "This runner already has Brave at $place, so the build would not be the one asked for." } + } $setup = Start-Process $package -Wait -PassThru if ($setup.ExitCode -ne 0) { throw "Brave's installer exited with $($setup.ExitCode)" } + $installed = $null + $until = (Get-Date).AddMinutes(10) + while (-not $installed -and (Get-Date) -lt $until) { + $installed = $places | Where-Object { + (Test-Path (Join-Path $_ 'brave.exe')) -and (Test-Path (Join-Path $_ "$Version\chrome.dll")) + } | Select-Object -First 1 + if (-not $installed) { Start-Sleep -Seconds 5 } + } + if (-not $installed) { + $seen = foreach ($root in $env:ProgramFiles, ${env:ProgramFiles(x86)}, $env:LOCALAPPDATA) { + Get-ChildItem (Join-Path $root 'BraveSoftware') -Recurse -Depth 3 -ErrorAction SilentlyContinue | + ForEach-Object FullName + } + throw "Brave's installer exited with 0, but no place holds brave.exe and $Version\chrome.dll after 10 minutes. Under BraveSoftware: $(@($seen) -join '; ')" + } $unpacked = $installed } else { 7z x $package "-o$unpacked" -y | Out-Null From 220ddb403e8340bcf0769595c39c775908c34c01 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:16:34 +0000 Subject: [PATCH 07/29] Publish: develop 25eb578 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/lib.rs | 1 + rivet/platform/windows/src/row_command.rs | 505 ++++++++++++++++++ rivet/platform/windows/src/row_port.rs | 41 +- rivet/platform/windows/src/row_resolve.rs | 325 ++++++++++- .../windows/src/chromium/live_tables.rs | 333 ++++++++++++ rivet/runtime/windows/src/chromium/mod.rs | 1 + .../windows/src/chromium/window_views.rs | 44 ++ .../windows/src/features/frame_layout.rs | 38 +- rivet/runtime/windows/src/frame.rs | 6 + 9 files changed, 1279 insertions(+), 15 deletions(-) create mode 100644 rivet/platform/windows/src/row_command.rs create mode 100644 rivet/runtime/windows/src/chromium/live_tables.rs diff --git a/rivet/platform/windows/src/lib.rs b/rivet/platform/windows/src/lib.rs index f364973..2734201 100644 --- a/rivet/platform/windows/src/lib.rs +++ b/rivet/platform/windows/src/lib.rs @@ -11,6 +11,7 @@ pub mod control; pub mod focus; pub mod hold; pub mod row_class; +pub mod row_command; pub mod row_features; pub mod row_port; pub mod row_recipe; diff --git a/rivet/platform/windows/src/row_command.rs b/rivet/platform/windows/src/row_command.rs new file mode 100644 index 0000000..5a46bb9 --- /dev/null +++ b/rivet/platform/windows/src/row_command.rs @@ -0,0 +1,505 @@ +//! Finds a function a browser command runs from its public command id. +//! +//! `chrome::BrowserCommandController::HandleCommandWithDisposition` runs every browser command +//! through one `switch (id)` (`chrome/browser/ui/browser_command_controller.cc`), and each case +//! calls the command's function first: `case IDC_NEW_TAB` calls `chrome::NewTab(browser_, ...)`. +//! The ids are public (`chrome/app/chrome_command_ids.h`, kept in `command_ids`). A switch that +//! dense compiles to a jump table: the id less the lowest case is checked against the number of +//! cases, then the table gives the case's code. So the case of an id is read from the table, and +//! the function is the first one its code calls. +//! +//! A build holds other switches over command ids, so the reading is checked on the prior build +//! first: the switches whose case for the id calls the prior row's function there tell the lowest +//! case of the dispatch switch, and in the new build only switches with that same lowest case are +//! read. Nothing is taken unless they all name one function. + +use std::collections::BTreeSet; + +use crate::chrome_build::PeFile; +use crate::row_port::x64; + +/// How far a case's code is read for its first call. +const CASE_REACH: usize = 0x80; + +/// A jump table switch: the lowest case it subtracts, the highest index it takes, its table and +/// where an index past it goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Switch { + pub at: u32, + pub lowest: i64, + pub bound: u32, + pub table: u32, + pub default: u32, +} + +fn i32_at(bytes: &[u8], at: usize) -> Option { + Some(i32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) +} + +fn rip_target(rva: u32, length: usize, displacement: i32) -> Option { + u32::try_from(i64::from(rva) + length as i64 + i64::from(displacement)).ok() +} + +/// `lea r64, [rip + d]; movsxd r64, dword [r + index * 4]; add r64, r64; jmp r64` at `at`, as the +/// table it loads. +fn table_jump(bytes: &[u8], at: usize, rva: u32) -> Option { + let code = bytes.get(at..at + 17)?; + let [rex, 0x8D, modrm, ..] = *code else { + return None; + }; + if rex & 0xFB != 0x48 || modrm & 0xC7 != 0x05 { + return None; + } + let register = (((rex >> 2) & 1) << 3) | ((modrm >> 3) & 7); + let table = rip_target(rva, 7, i32_at(code, 3)?)?; + // movsxd with a SIB byte that scales the index by four and takes the table as its base. + let [load_rex, 0x63, load_modrm, sib] = code[7..11] else { + return None; + }; + if load_rex & 0xF8 != 0x48 || load_modrm & 0xC7 != 0x04 || sib >> 6 != 2 { + return None; + } + if ((load_rex & 1) << 3) | (sib & 7) != register { + return None; + } + // add r64, r64 + let [add_rex, add, add_modrm] = code[11..14] else { + return None; + }; + if add_rex & 0xF8 != 0x48 || !matches!(add, 0x01 | 0x03) || add_modrm >> 6 != 3 { + return None; + } + // jmp r64, with a REX prefix for r8 to r15. + let jump = if code[14] == 0x41 { + &code[15..17] + } else { + &code[14..16] + }; + (jump[0] == 0xFF && jump[1] & 0xF8 == 0xE0).then_some(table) +} + +/// The `ja` that ends at `end`, as its target, with where it starts. +fn above_before(bytes: &[u8], end: usize, base: u32) -> Option<(usize, u32)> { + if let Some(start) = end.checked_sub(6) { + if bytes.get(start..start + 2) == Some(&[0x0F, 0x87][..]) { + let target = rip_target(base + start as u32, 6, i32_at(bytes, start + 2)?)?; + return Some((start, target)); + } + } + let start = end.checked_sub(2)?; + let [0x77, rel] = *bytes.get(start..end)? else { + return None; + }; + Some(( + start, + rip_target(base + start as u32, 2, i32::from(rel as i8))?, + )) +} + +/// The `cmp r32, imm` that ends at `end`, as its immediate, with where it starts. +fn compare_before(bytes: &[u8], end: usize) -> Option<(usize, u32)> { + let at = |length: usize| { + let start = end.checked_sub(length)?; + Some((start, bytes.get(start..end)?)) + }; + // cmp eax, imm32 + if let Some((start, [0x3D, ..])) = at(5) { + return Some((start, i32_at(bytes, start + 1)? as u32)); + } + for rex in [false, true] { + let skip = usize::from(rex); + if let Some((start, code)) = at(6 + skip) { + if (!rex || code[0] == 0x41) && code[skip] == 0x81 && code[skip + 1] & 0xF8 == 0xF8 { + return Some((start, i32_at(bytes, start + skip + 2)? as u32)); + } + } + if let Some((start, code)) = at(3 + skip) { + if (!rex || code[0] == 0x41) && code[skip] == 0x83 && code[skip + 1] & 0xF8 == 0xF8 { + return Some((start, code[skip + 2] as i8 as i32 as u32)); + } + } + } + None +} + +/// The lowest case a switch subtracts before `end`: `lea r32, [r - n]`, `add r32, -n` or +/// `sub r32, n`, nearest first. Zero when the switch takes the id as it is. +fn lowest_before(bytes: &[u8], end: usize) -> i64 { + for stop in (end.saturating_sub(16)..=end).rev() { + for start in stop.saturating_sub(7)..stop { + let Some(code) = bytes.get(start..stop) else { + continue; + }; + let skip = usize::from(matches!(code.first(), Some(0x40..=0x4F)) && code.len() > 1); + let rest = &code[skip..]; + let value = match *rest { + // lea r32, [r + disp32] or [r + disp8], with no SIB byte. + [0x8D, modrm, ..] if modrm >> 6 == 2 && modrm & 7 != 4 && rest.len() == 6 => { + i32_at(rest, 2).map(|value| -i64::from(value)) + } + [0x8D, modrm, disp] if modrm >> 6 == 1 && modrm & 7 != 4 => { + Some(-i64::from(disp as i8)) + } + [0x05, ..] if rest.len() == 5 => i32_at(rest, 1).map(|value| -i64::from(value)), + [0x2D, ..] if rest.len() == 5 => i32_at(rest, 1).map(i64::from), + [0x81, modrm, ..] if rest.len() == 6 && modrm & 0xF8 == 0xC0 => { + i32_at(rest, 2).map(|value| -i64::from(value)) + } + [0x81, modrm, ..] if rest.len() == 6 && modrm & 0xF8 == 0xE8 => { + i32_at(rest, 2).map(i64::from) + } + _ => None, + }; + if let Some(value) = value { + return value; + } + } + } + 0 +} + +/// Every jump table switch in the build's code. +pub fn switches(pe: &PeFile) -> Vec { + let mut found = Vec::new(); + for (base, bytes, is_code) in pe.sections() { + if !is_code { + continue; + } + for at in 0..bytes.len().saturating_sub(17) { + if bytes[at + 1] != 0x8D { + continue; + } + let rva = base + at as u32; + let Some(table) = table_jump(bytes, at, rva) else { + continue; + }; + if pe.read(table, 4).is_none() { + continue; + } + // The bound check ends right before the table load, or before a `mov r32, r32` that + // clears the index's upper half. + let Some((above, default)) = [at, at.saturating_sub(2), at.saturating_sub(3)] + .into_iter() + .find_map(|end| above_before(bytes, end, base)) + else { + continue; + }; + let Some((compare, bound)) = compare_before(bytes, above) else { + continue; + }; + found.push(Switch { + at: rva, + lowest: lowest_before(bytes, compare), + bound, + table, + default, + }); + } + } + found +} + +/// Where a switch sends `id`, unless it sends it where it sends an id it has no case for. +pub fn case_of(pe: &PeFile, switch: &Switch, id: i64) -> Option { + let index = u32::try_from(id - switch.lowest).ok()?; + if index > switch.bound { + return None; + } + let entry = i32::from_le_bytes(pe.read(switch.table + index * 4, 4)?.try_into().ok()?); + let case = rip_target(switch.table, 0, entry)?; + (case != switch.default && pe.is_code(case)).then_some(case) +} + +/// The first function the code at `at` calls before it leaves, after one jump it may start with. +pub fn first_call(pe: &PeFile, at: u32) -> Option { + let mut at = at; + let mut followed = false; + let bytes = pe.read(at, CASE_REACH)?; + let mut bytes = bytes.to_vec(); + let mut offset = 0; + while offset < bytes.len() { + let rva = at + offset as u32; + match bytes[offset] { + 0xE8 => return rip_target(rva, 5, i32_at(&bytes, offset + 1)?), + 0xE9 if offset == 0 && !followed => { + at = rip_target(rva, 5, i32_at(&bytes, 1)?)?; + bytes = pe.read(at, CASE_REACH)?.to_vec(); + followed = true; + continue; + } + 0xC3 | 0xE9 | 0xEB | 0xCC => return None, + _ => {} + } + let instruction = x64::decode_body(&bytes[offset..])?; + if instruction.length == 0 { + return None; + } + offset += instruction.length; + } + None +} + +/// The function each switch's case for `id` calls first, with the switch. +pub fn command_calls(pe: &PeFile, id: i64) -> Vec<(Switch, u32)> { + calls_through(pe, &switches(pe), id) +} + +/// The function each of `switches`' case for `id` calls first, with the switch. +fn calls_through(pe: &PeFile, switches: &[Switch], id: i64) -> Vec<(Switch, u32)> { + switches + .iter() + .filter_map(|switch| { + let case = case_of(pe, switch, id)?; + Some((*switch, first_call(pe, case)?)) + }) + .collect() +} + +/// The function the command `id` runs in the new build, read the same way that gives `target` in +/// the prior build: only switches whose lowest case is that of a prior switch that sends the id to +/// `target` count, all of them must call one function, and in the prior build every such switch +/// calls `target`. +pub fn command_place( + old_pe: &PeFile, + new_pe: &PeFile, + target: u32, + id: i64, +) -> Result { + let old = (old_pe, switches(old_pe)); + let new = (new_pe, switches(new_pe)); + command_place_in((old.0, &old.1), (new.0, &new.1), target, id) +} + +/// `command_place` with the switches of both builds already read. +pub fn command_place_in( + old: (&PeFile, &[Switch]), + new: (&PeFile, &[Switch]), + target: u32, + id: i64, +) -> Result { + let prior = calls_through(old.0, old.1, id); + let lowest: BTreeSet = prior + .iter() + .filter(|(_, called)| *called == target) + .map(|(switch, _)| switch.lowest) + .collect(); + if lowest.is_empty() { + return Err(format!( + "no switch of the prior build sends command {id} to it" + )); + } + let others = prior + .iter() + .filter(|(switch, called)| lowest.contains(&switch.lowest) && *called != target) + .count(); + if others > 0 { + return Err(format!( + "{others} switches of the prior build like its dispatch send command {id} elsewhere" + )); + } + let called: BTreeSet = calls_through(new.0, new.1, id) + .into_iter() + .filter(|(switch, _)| lowest.contains(&switch.lowest)) + .map(|(_, called)| called) + .collect(); + match called.into_iter().collect::>().as_slice() { + [only] => Ok(*only), + many => Err(format!( + "command {id} reaches {} functions through the dispatch in the new build", + many.len() + )), + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::row_resolve::tests::{call, module}; + + pub const DISPATCH: u32 = 0x101000; + const OTHER_SWITCH: u32 = 0x101800; + const TABLE: u32 = 0x201000; + const OTHER_TABLE: u32 = 0x203000; + const DEFAULT: u32 = 0x101f00; + const BACK: u32 = 0x102000; + const ELSEWHERE: u32 = 0x104000; + const LOWEST: i32 = 33000; + const NEW_TAB_ID: i64 = 34014; + + fn rel(from: u32, length: u32, to: u32) -> [u8; 4] { + ((i64::from(to) - i64::from(from) - i64::from(length)) as i32).to_le_bytes() + } + + /// A switch at `at` over ids from `lowest` with `bound + 1` cases in the table at `table`: + /// `lea eax, [rdx - lowest]; cmp eax, bound; ja default; lea rcx, [rip + table]; + /// movsxd rax, [rcx + rax * 4]; add rax, rcx; jmp rax`. + fn switch_code(at: u32, lowest: i32, bound: u32, table: u32) -> Vec { + let mut code = vec![0x8D, 0x82]; + code.extend((-lowest).to_le_bytes()); + code.push(0x3D); + code.extend(bound.to_le_bytes()); + code.extend([0x0F, 0x87]); + code.extend(rel(at + code.len() as u32 - 2, 6, DEFAULT)); + code.extend([0x48, 0x8D, 0x0D]); + code.extend(rel(at + code.len() as u32 - 3, 7, table)); + code.extend([0x48, 0x63, 0x04, 0x81, 0x48, 0x01, 0xC8, 0xFF, 0xE0]); + code + } + + /// A case that loads the browser and a constant and calls `to`, then leaves the switch. + fn case_code(at: u32, to: u32) -> Vec { + let mut code = vec![0x48, 0x8B, 0x4E, 0x10, 0xBA, 0x01, 0, 0, 0]; + code.extend(call(at + code.len() as u32, to)); + code.extend([0xEB, 0x00]); + code + } + + /// A table of `bound + 1` entries from `table`, each the distance to `default` except `cases`. + fn table_of(table: u32, bound: u32, cases: &[(u32, u32)]) -> Vec { + let mut bytes = Vec::new(); + for index in 0..=bound { + let to = cases + .iter() + .find(|(case, _)| *case == index) + .map_or(DEFAULT, |(_, to)| *to); + bytes.extend(((i64::from(to) - i64::from(table)) as i32).to_le_bytes()); + } + bytes + } + + /// A build whose dispatch over ids from 33000 sends IDC_BACK to `BACK` and IDC_NEW_TAB to + /// `new_tab`, and that holds a second switch, over ids from 34000, whose case for 34014 calls + /// another function. `new_tab` gets the bytes in `body` once, or at each of `copies`. + pub fn dispatch_module(new_tab: Option, copies: &[u32]) -> Vec { + let bound = 1100; + let back_case = 0x101100; + let new_tab_case = 0x101140; + let other_case = 0x101900; + let mut parts = vec![ + (DISPATCH, switch_code(DISPATCH, LOWEST, bound, TABLE)), + (back_case, case_code(back_case, BACK)), + ( + OTHER_SWITCH, + switch_code(OTHER_SWITCH, 34000, 40, OTHER_TABLE), + ), + (other_case, case_code(other_case, ELSEWHERE)), + (DEFAULT, vec![0xC3]), + (BACK, vec![0xC3]), + (ELSEWHERE, vec![0xC3]), + (OTHER_TABLE, table_of(OTHER_TABLE, 40, &[(14, other_case)])), + ]; + let mut cases = vec![(0, back_case)]; + if let Some(new_tab) = new_tab { + parts.push((new_tab_case, case_code(new_tab_case, new_tab))); + cases.push(((NEW_TAB_ID - i64::from(LOWEST)) as u32, new_tab_case)); + } + parts.push((TABLE, table_of(TABLE, bound, &cases))); + let body = [ + 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x83, 0xC4, 0x20, 0x5E, 0xC3, + ]; + let mut ranges = vec![(DISPATCH, DISPATCH + 0x40)]; + for at in copies { + parts.push((*at, body.to_vec())); + ranges.push((*at, *at + body.len() as u32)); + } + module(&parts, &ranges) + } + + pub const OLD_NEW_TAB: u32 = 0x103000; + pub const NEW_NEW_TAB: u32 = 0x103400; + + #[test] + fn nfr6_a_switch_case_is_read_from_its_jump_table() { + let bytes = dispatch_module(Some(OLD_NEW_TAB), &[OLD_NEW_TAB]); + let pe = PeFile::parse(&bytes).unwrap(); + let found = switches(&pe); + // The table load follows `lea`, `cmp` and `ja`: 6, 5 and 6 bytes. + let dispatch = found + .iter() + .find(|switch| switch.at == DISPATCH + 17) + .unwrap(); + assert_eq!( + ( + dispatch.lowest, + dispatch.bound, + dispatch.table, + dispatch.default + ), + (i64::from(LOWEST), 1100, TABLE, DEFAULT) + ); + let back = case_of(&pe, dispatch, 33000).and_then(|case| first_call(&pe, case)); + assert_eq!(back, Some(BACK)); + // An id with no case goes where the switch sends any id it does not know. + assert_eq!(case_of(&pe, dispatch, 33001), None); + assert_eq!(case_of(&pe, dispatch, 40000), None); + let mut called: Vec = command_calls(&pe, NEW_TAB_ID) + .into_iter() + .map(|(_, to)| to) + .collect(); + called.sort(); + assert_eq!(called, [OLD_NEW_TAB, ELSEWHERE]); + } + + /// What the resolver makes of `chrome::NewTab` between the two builds, with the places its + /// fingerprint matched off the exception table's function starts. + fn resolve_new_tab(loose: Vec) -> crate::row_resolve::Resolution { + use crate::row_resolve::{resolve, Kind, Wanted}; + use std::collections::BTreeMap; + let old = dispatch_module(Some(OLD_NEW_TAB), &[OLD_NEW_TAB]); + let new = dispatch_module(Some(NEW_NEW_TAB), &[NEW_NEW_TAB]); + let (old, new) = (PeFile::parse(&old).unwrap(), PeFile::parse(&new).unwrap()); + let wanted = BTreeMap::from([( + OLD_NEW_TAB, + Wanted { + kind: Kind::Function, + candidates: None, + class: None, + command: Some(NEW_TAB_ID), + loose, + }, + )]); + let none = BTreeSet::new(); + resolve(&old, &new, &BTreeMap::new(), &wanted, &none, &none) + } + + #[test] + fn nfr6_new_tab_is_taken_where_its_command_and_fingerprint_agree() { + let resolution = resolve_new_tab(vec![NEW_NEW_TAB]); + assert_eq!(resolution.places.get(&OLD_NEW_TAB), Some(&NEW_NEW_TAB)); + assert_eq!( + resolution.settled, + ["0x103000 -> 0x103400 by its fingerprint and its command id"] + ); + // The command id alone is one method. + let alone = resolve_new_tab(Vec::new()); + assert!(alone.places.is_empty()); + let reason = &alone.reasons[&OLD_NEW_TAB]; + assert!( + reason.starts_with("only its command id found it"), + "{reason}" + ); + } + + #[test] + fn nfr6_new_tab_is_found_from_the_new_tab_command() { + let old = dispatch_module(Some(OLD_NEW_TAB), &[OLD_NEW_TAB]); + let new = dispatch_module(Some(NEW_NEW_TAB), &[NEW_NEW_TAB]); + let (old, new) = (PeFile::parse(&old).unwrap(), PeFile::parse(&new).unwrap()); + // Only the dispatch's own switch counts; the other switch's case calls another function. + assert_eq!( + command_place(&old, &new, OLD_NEW_TAB, NEW_TAB_ID), + Ok(NEW_NEW_TAB) + ); + // The prior build must send the command to the prior row's function. + let refused = command_place(&old, &new, 0x103800, NEW_TAB_ID).unwrap_err(); + assert!( + refused.starts_with("no switch of the prior build"), + "{refused}" + ); + // A new build whose dispatch has no case for the command gives nothing. + let gone = dispatch_module(None, &[]); + let gone = PeFile::parse(&gone).unwrap(); + let none = command_place(&old, &gone, OLD_NEW_TAB, NEW_TAB_ID).unwrap_err(); + assert!(none.contains("reaches 0 functions"), "{none}"); + } +} diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 9e2c2ae..c574c68 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -1192,6 +1192,32 @@ fn write_command_ids(row: &mut Value, version: &str, report: &mut PortReport) { } } +/// The prior row's functions that a browser command runs first, with the command's public id: +/// `chrome::NewTab`, the first call of the `IDC_NEW_TAB` case of the browser's command switch. The +/// id must be the same at the prior and the new build's Chromium milestone, which Chrome, Edge and +/// Brave carry as the first part of their version. +fn command_targets(prior: &Value, version: &str) -> BTreeMap { + let browser = prior["build"]["browser"].as_str().unwrap_or_default(); + if !matches!(browser, "Google Chrome" | "Microsoft Edge" | "Brave") { + return BTreeMap::new(); + } + let milestone = |version: &str| version.split('.').next()?.parse::().ok(); + let prior_version = prior["frame"]["version"].as_str().unwrap_or_default(); + let ids = ( + milestone(prior_version).and_then(crate::command_ids::new_tab), + milestone(version).and_then(crate::command_ids::new_tab), + ); + let (Some(id), Some(same)) = ids else { + return BTreeMap::new(); + }; + let address = + read_address(&prior["build"]["tabs"]["new_tab"]).filter(|value| is_address(*value)); + match address { + Some(address) if id == same => BTreeMap::from([(address as u32, id as i64)]), + _ => BTreeMap::new(), + } +} + /// Finds each address of a row through the public names of both builds. fn port_by_name( prior: &Value, @@ -1519,6 +1545,7 @@ pub fn find_candidate( // Each address its fingerprint did not pin down, with its review line, waits for the methods // that read the prior build next to the new one. let mut wanted: BTreeMap = BTreeMap::new(); + let commands = command_targets(prior, version); let want = |target: u32, kind: row_resolve::Kind, candidates: Option>| { row_resolve::Wanted { kind, @@ -1526,6 +1553,10 @@ pub fn find_candidate( class: (kind == row_resolve::Kind::Table) .then(|| classes.get(&target).cloned()) .flatten(), + command: (kind == row_resolve::Kind::Function) + .then(|| commands.get(&target).copied()) + .flatten(), + loose: Vec::new(), } }; for target in &targets { @@ -1602,7 +1633,9 @@ pub fn find_candidate( "{target:#x} matches no function start, of {} places", all.len() ); - wanted.insert(*target, (line, want(*target, function, None))); + let mut asked = want(*target, function, None); + asked.loose = all.to_vec(); + wanted.insert(*target, (line, asked)); } [] => { let line = format!("{target:#x} matches no place"); @@ -1658,7 +1691,11 @@ pub fn find_candidate( .iter() .map(|(target, (_, want))| (*target, want.clone())) .collect(); - let resolution = row_resolve::resolve(prior_pe, pe, &moved, &asked, &table_targets); + // The tables the prior build's public symbols name after a class are the tables of + // views classes the slot shift compares. + let views: BTreeSet = classes.keys().copied().collect(); + let resolution = + row_resolve::resolve(prior_pe, pe, &moved, &asked, &table_targets, &views); for (target, (line, _)) in &wanted { match resolution.places.get(target) { Some(place) => { diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index f65f0f9..6e5cc49 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -11,6 +11,10 @@ //! build, and exactly one candidate makes the same calls from the same spots; //! - its table slot: a class table known in both builds holds it, at the slot that lines up once //! the slots around it are compared, since a milestone can add or remove a virtual function; +//! - its slot shift: for a virtual function of a views class, the table of a second views class +//! lines the same slot up by the same shift. Every views class derives from `views::View`, whose +//! virtual functions keep one slot in all their tables (`ui/views/view.h`), so a second table +//! confirms the slot number apart from the first; //! - a text it uses: it refers to a text the new build holds once, and exactly one function there //! refers to that text; //! - for a class table, references to it (a function known in both builds loads it from the same @@ -18,9 +22,17 @@ //! - for the class table of a views class, its class name: `row_class` reads the table from the //! name the class's `ui::metadata` holds, and the same reading must give the prior table in the //! prior build; -//! - its fingerprint: a place a class table gives, by its class name or by a slot, that is one of -//! the places the fingerprint matched. Those methods do not search among the fingerprint's -//! places, so the two agree independently. +//! - a known caller: a function known in both builds calls it in the prior build, and of the places +//! its fingerprint matched, the caller's new body calls exactly one. Public source tells which +//! function calls which (a frame view's `OnPaint` calls `gfx::Canvas::DrawColor`), and the call +//! is a fact of the caller apart from the fingerprint's bytes, so with the fingerprint it is two +//! methods. Each place a virtual function's table slot settles is a known caller in the next +//! round, so drawing helpers follow the functions they are called from; +//! - its command id: for a function a browser command runs first, the case of the command's public +//! id in the browser's command switch, read by `row_command` the same way in both builds; +//! - its fingerprint: a place a class table or a command id gives that is one of the places the +//! fingerprint matched. Those methods do not search among the fingerprint's places, so the two +//! agree independently. //! //! Anything else stays unresolved with its reason, and its row goes to a person. @@ -536,6 +548,75 @@ fn by_table_slot( found } +/// The places a views class table gives a function by its slot, where the table of a second views +/// class, known in both builds, lines the same slot up by the same shift. `views` names the prior +/// build's tables of views classes. A slot of `views::View` is the same slot in every views class +/// table, and one of a derived class is the same slot in that class's subclasses, so a slot that two +/// tables line up alike is a slot number found twice, by tables found apart. +fn by_slot_shift( + old: &Side, + new: &Side, + known: &BTreeMap, + tables: &[(u32, u32)], + views: &BTreeSet, + target: u32, +) -> BTreeSet { + let mut found = BTreeSet::new(); + for pair in tables.iter().filter(|pair| views.contains(&pair.0)) { + for slot in 0..TABLE_SLOTS { + let Some(function) = entry(old.pe, pair.0, i64::from(slot)) else { + break; + }; + if function != target { + continue; + } + let Some(shift) = line_up(old, new, known, *pair, slot) else { + continue; + }; + let confirmed = tables + .iter() + .filter(|other| other.0 != pair.0 && views.contains(&other.0)) + .any(|other| line_up(old, new, known, *other, slot) == Some(shift)); + if confirmed { + if let Some(place) = entry(new.pe, pair.1, i64::from(slot) + shift) { + found.insert(place); + } + } + } + } + found +} + +/// The places the known callers of `target` give it among `candidates`: for each function that +/// calls it in the prior build and whose new place is known, the one candidate its new body calls, +/// when it calls exactly one. `callers` holds the prior build's callers of each wanted function. +fn by_known_callers( + new: &mut Side, + known: &BTreeMap, + callers: &BTreeSet, + candidates: &[u32], +) -> BTreeSet { + let mut found = BTreeSet::new(); + if candidates.is_empty() { + return found; + } + for caller in callers { + let Some(place) = known.get(caller).filter(|place| new.pe.is_code(**place)) else { + continue; + }; + let called: BTreeSet = new + .body(*place) + .iter() + .filter_map(|step| step.call) + .filter(|callee| candidates.contains(callee)) + .collect(); + if let [only] = called.into_iter().collect::>()[..] { + found.insert(only); + } + } + found +} + /// The candidate tables whose slots hold the same functions as the old table, and how many agree. fn by_slots( old: &Side, @@ -688,6 +769,9 @@ pub enum Method { Slots, ClassName, Fingerprint, + SlotShift, + Command, + KnownCaller, } impl fmt::Display for Method { @@ -701,6 +785,9 @@ impl fmt::Display for Method { Method::Slots => "its slots", Method::ClassName => "its class name", Method::Fingerprint => "its fingerprint", + Method::SlotShift => "its slot shift", + Method::Command => "its command id", + Method::KnownCaller => "a known caller", }) } } @@ -764,6 +851,12 @@ pub struct Wanted { pub candidates: Option>, /// For a class table, the views class the prior build's public symbol names it after. pub class: Option, + /// For a function a browser command runs first, the command's public id. + pub command: Option, + /// Places the fingerprint matched that the exception table does not list as function starts. + /// They name no place alone, but a place another method finds among them is one the + /// fingerprint agrees with. + pub loose: Vec, } /// The class table a views class name gives in the new build, once the same reading gives the @@ -820,14 +913,16 @@ pub struct Resolution { } /// Looks for each wanted address with every method, in rounds, since a place found in one round -/// is known in the next. `known` holds the places the fingerprints found, and `tables` names the -/// prior row's addresses that are class tables. +/// is known in the next. `known` holds the places the fingerprints found, `tables` names the +/// prior row's addresses that are class tables, and `views` those of them that are tables of views +/// classes. pub fn resolve( old_pe: &PeFile, new_pe: &PeFile, known: &BTreeMap, wanted: &BTreeMap, tables: &BTreeSet, + views: &BTreeSet, ) -> Resolution { let mut old = Side::new(old_pe); let mut new = Side::new(new_pe); @@ -868,6 +963,14 @@ pub fn resolve( expected.insert(*target, calls); } let callers = calls_into(&new, &called); + // The prior build's callers of each wanted function with fingerprint places, for the method of + // a known caller. + let with_candidates: BTreeSet = wanted + .iter() + .filter(|(_, want)| want.kind == Kind::Function && want.candidates.is_some()) + .map(|(target, _)| *target) + .collect(); + let prior_callers = calls_into(&old, &with_candidates); // A class name gives a table from the build alone, so it is read once. let mut by_class = BTreeMap::new(); @@ -886,6 +989,30 @@ pub fn resolve( } } + // A command id gives a function from both builds alone, so it is read once. + let mut by_command = BTreeMap::new(); + let commands: Vec<(u32, i64)> = wanted + .iter() + .filter(|(_, want)| want.kind == Kind::Function) + .filter_map(|(target, want)| Some((*target, want.command?))) + .collect(); + if !commands.is_empty() { + let old_switches = crate::row_command::switches(old_pe); + let new_switches = crate::row_command::switches(new_pe); + for (target, id) in commands { + let old = (old_pe, old_switches.as_slice()); + let new = (new_pe, new_switches.as_slice()); + match crate::row_command::command_place_in(old, new, target, id) { + Ok(place) => { + by_command.insert(target, place); + } + Err(reason) => { + class_reasons.insert(target, reason); + } + } + } + } + let mut pending: BTreeSet = wanted.keys().copied().collect(); for _ in 0..ROUNDS { let followed = follow(&mut old, &mut new, &known); @@ -922,9 +1049,31 @@ pub fn resolve( for place in slotted { answers.push((Method::TableSlot, place)); } + for place in by_slot_shift(&old, &new, &known, &table_pairs, views, target) { + answers.push((Method::SlotShift, place)); + } if let Some(place) = by_text(&texts_of[&target], &users) { answers.push((Method::Text, place)); } + let from = prior_callers.get(&target); + if let (Some(list), Some(from)) = (&want.candidates, from) { + let given = by_known_callers(&mut new, &known, from, list); + answers.extend(fingerprint_agrees(&given, Some(list.as_slice()))); + for place in given { + answers.push((Method::KnownCaller, place)); + } + } + if let Some(place) = by_command.get(&target).copied() { + answers.push((Method::Command, place)); + let matched = want + .candidates + .as_ref() + .is_some_and(|candidates| candidates.contains(&place)) + || want.loose.contains(&place); + if matched { + answers.push((Method::Fingerprint, place)); + } + } } Kind::Table => { if let Some(place) = by_reference(&followed, target) { @@ -1324,9 +1473,18 @@ pub(crate) mod tests { kind: Kind::Function, candidates: Some(NEW_TARGETS.to_vec()), class: None, + command: None, + loose: Vec::new(), }, )]); - resolve(&old, &new, &known, &wanted, &BTreeSet::from([OLD_TABLE])) + resolve( + &old, + &new, + &known, + &wanted, + &BTreeSet::from([OLD_TABLE]), + &BTreeSet::new(), + ) } #[test] @@ -1381,6 +1539,161 @@ pub(crate) mod tests { assert!(reason.starts_with("only calls into it found it"), "{reason}"); } + const VIEW_TARGET: u32 = 0x105000; + const VIEW_TABLE: u32 = 0x201000; + const OTHER_VIEW_TABLE: u32 = 0x201400; + + /// A build with two tables of views classes. The first holds, among small functions, the + /// target in slot 6; the second holds small functions only. In a new build each table gets one + /// more slot at slot 2 when `inserted` says so, as when a milestone adds a virtual function to + /// `views::View`, and the target's code changed, so its fingerprint finds nothing. + fn views_module(new: bool, inserted: [bool; 2]) -> Vec { + let mut parts = vec![]; + let mut ranges = vec![]; + let mut slots = |base: u32, first: u8, holds_target: bool, insert: bool| { + let mut list = vec![]; + for n in 0..12u8 { + let at = base + 0x10 * u32::from(n); + parts.push((at, small(first + n))); + list.push(at); + } + if holds_target { + list.insert(6, VIEW_TARGET); + } + if insert { + let at = base + 0x100; + parts.push((at, small(first + 0x40))); + list.insert(2, at); + } + list + }; + let first = slots(0x105400, 0, true, new && inserted[0]); + let second = slots(0x105800, 0x80, false, new && inserted[1]); + parts.push((VIEW_TABLE, table(&first))); + parts.push((OTHER_VIEW_TABLE, table(&second))); + let mut code = TARGET.to_vec(); + if new { + // mov rsi, rdx instead of mov rsi, rcx. + code[7] = 0xD6; + } + parts.push((VIEW_TARGET, code)); + ranges.push((VIEW_TARGET, VIEW_TARGET + 14)); + module(&parts, &ranges) + } + + fn run_views(inserted: [bool; 2], views: &[u32]) -> Resolution { + let old_bytes = views_module(false, [false; 2]); + let new_bytes = views_module(true, inserted); + let old = PeFile::parse(&old_bytes).unwrap(); + let new = PeFile::parse(&new_bytes).unwrap(); + let known = BTreeMap::from([ + (VIEW_TABLE, VIEW_TABLE), + (OTHER_VIEW_TABLE, OTHER_VIEW_TABLE), + ]); + let wanted = BTreeMap::from([( + VIEW_TARGET, + Wanted { + kind: Kind::Function, + candidates: None, + class: None, + command: None, + loose: Vec::new(), + }, + )]); + let tables = BTreeSet::from([VIEW_TABLE, OTHER_VIEW_TABLE]); + let views: BTreeSet = views.iter().copied().collect(); + resolve(&old, &new, &known, &wanted, &tables, &views) + } + + #[test] + fn nfr6_a_virtual_function_is_read_from_its_views_class_table_by_slot() { + // Both tables moved the slot by one: the slot number is found twice, and the function is + // the one the first table holds there. + let resolution = run_views([true, true], &[VIEW_TABLE, OTHER_VIEW_TABLE]); + assert_eq!(resolution.places.get(&VIEW_TARGET), Some(&VIEW_TARGET)); + assert_eq!( + resolution.settled, + ["0x105000 -> 0x105000 by its table slot and its slot shift"] + ); + } + + #[test] + fn nfr6_a_virtual_function_needs_a_second_views_table_to_agree_on_its_slot() { + // Without a second table of a views class, the slot is found once. + let alone = run_views([true, true], &[VIEW_TABLE]); + assert!(alone.places.is_empty()); + let reason = &alone.reasons[&VIEW_TARGET]; + assert!(reason.starts_with("only its table slot found it"), "{reason}"); + // A second table that lines the slot up another way confirms nothing. + let apart = run_views([true, false], &[VIEW_TABLE, OTHER_VIEW_TABLE]); + assert!(apart.places.is_empty()); + let reason = &apart.reasons[&VIEW_TARGET]; + assert!(reason.starts_with("only its table slot found it"), "{reason}"); + } + + /// push rbx; mov ebx, 5; xor eax, eax; call `first`; [call `second`;] nop; pop rbx; ret: a + /// caller whose body around the call changed, so no call site of it pairs with the prior one. + fn changed_caller(at: u32, first: u32, second: Option) -> Vec { + let mut bytes = vec![0x53, 0xBB, 0x05, 0, 0, 0, 0x31, 0xC0]; + bytes.extend(call(at + bytes.len() as u32, first)); + if let Some(second) = second { + bytes.extend(call(at + bytes.len() as u32, second)); + } + bytes.extend([0x90, 0x5B, 0xC3]); + bytes + } + + fn run_known_caller(second: Option) -> Resolution { + let old_bytes = old_module(); + let caller = changed_caller(NEW_CALLER, NEW_TARGETS[0], second); + let new_bytes = module( + &[ + (NEW_CALLER, caller), + (NEW_TARGETS[0], TARGET.to_vec()), + (NEW_TARGETS[1], TARGET.to_vec()), + ], + &[ + (NEW_CALLER, NEW_CALLER + 24), + (NEW_TARGETS[0], NEW_TARGETS[0] + 14), + (NEW_TARGETS[1], NEW_TARGETS[1] + 14), + ], + ); + let old = PeFile::parse(&old_bytes).unwrap(); + let new = PeFile::parse(&new_bytes).unwrap(); + let known = BTreeMap::from([(OLD_CALLER, NEW_CALLER)]); + let wanted = BTreeMap::from([( + OLD_TARGET, + Wanted { + kind: Kind::Function, + candidates: Some(NEW_TARGETS.to_vec()), + class: None, + command: None, + loose: Vec::new(), + }, + )]); + let none = BTreeSet::new(); + resolve(&old, &new, &known, &wanted, &none, &none) + } + + #[test] + fn nfr6_a_drawing_helper_is_found_by_the_call_from_its_caller() { + // The caller, as a frame view's paint calls `DrawColor`, is known in both builds, and of + // the two places the helper's fingerprint matched, its new body calls one. + let resolution = run_known_caller(None); + assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); + assert_eq!( + resolution.settled, + ["0x101100 -> 0x103100 by its fingerprint and a known caller"] + ); + } + + #[test] + fn nfr6_a_caller_that_calls_every_fingerprint_place_names_no_helper() { + let resolution = run_known_caller(Some(NEW_TARGETS[1])); + assert!(resolution.places.is_empty()); + assert_eq!(resolution.reasons[&OLD_TARGET], "no method found it"); + } + #[test] fn nfr6_a_place_outside_the_fingerprint_matches_is_refused() { let answers = [(Method::CallsInto, 0x103300), (Method::TableSlot, 0x103300)]; diff --git a/rivet/runtime/windows/src/chromium/live_tables.rs b/rivet/runtime/windows/src/chromium/live_tables.rs new file mode 100644 index 0000000..e81be26 --- /dev/null +++ b/rivet/runtime/windows/src/chromium/live_tables.rs @@ -0,0 +1,333 @@ +//! Reads the class tables of the views every browser window has from live objects, so a row needs +//! no class table address for them. +//! +//! A C++ object's first word is the table of its class. Every views class derives from +//! `views::View`, whose first base is `ui::LayerDelegate` (`ui/views/view.h`), so a view's first +//! word is its class's own table, the one whose slots hold the class's virtual functions. The views +//! are found by the class names their `ui::metadata` holds, through the view tree public Chromium +//! source describes: +//! +//! - `views::NonClientView` holds the window's frame view and its client view as children +//! (`ui/views/window/non_client_view.h`), and the client view of a browser window is the +//! `BrowserView` (`chrome/browser/ui/views/frame/browser_view.h`). So the frame view is the child of +//! the browser view's parent whose class name names a frame view. +//! - The frame view's caption buttons are `WindowsCaptionButton` views below it +//! (`chrome/browser/ui/views/frame/windows_caption_button.h`). +//! +//! A table is taken only when every live view of its class has the same one, it lies in read-only +//! data, its first slots lie in code, and, where the row also has the table, the two agree. + +use crate::chromium::window_views::Memory; + +/// The browser view's class name. +pub(crate) const BROWSER_VIEW: &str = "BrowserView"; +/// The caption buttons' class name. +pub(crate) const CAPTION_BUTTON: &str = "WindowsCaptionButton"; +/// The corner wedges' class name, where a browser has them. +pub(crate) const CORNER: &str = "CustomFloatingCorner"; + +/// How many views below the root are read at most. +const MOST_VIEWS: usize = 4000; +/// How many children one view may list. +const MOST_CHILDREN: usize = 256; + +/// The views a view lists at `children`, a `std::vector`. +fn children(memory: &M, view: usize, children: usize) -> Vec { + let (Some(begin), Some(end)) = ( + memory.word(view + children), + memory.word(view + children + 8), + ) else { + return Vec::new(); + }; + if begin == 0 || end < begin || (end - begin) % 8 != 0 || (end - begin) / 8 > MOST_CHILDREN { + return Vec::new(); + } + (begin..end) + .step_by(8) + .filter_map(|at| memory.word(at)) + .filter(|child| *child != 0) + .collect() +} + +/// Whether a class name names a browser frame view, as `BrowserFrameViewWin`, or a browser's own +/// subclass of one, as `EdgeBrowserFrameViewWin`, does. +pub(crate) fn is_frame_view(name: &str) -> bool { + name.contains("FrameView") +} + +/// Every view below `root`, the root included, whose class name `wanted` accepts, in tree order. +/// Only a child that names its parent at `parent` is followed, so a list read wrongly is not walked. +pub(crate) fn views_below( + memory: &M, + root: usize, + parent: usize, + wanted: &dyn Fn(&str) -> bool, +) -> Vec { + let mut found = Vec::new(); + let mut stack = vec![root]; + let mut seen = 0; + while let Some(view) = stack.pop() { + seen += 1; + if seen > MOST_VIEWS { + break; + } + if memory.class_name(view).is_some_and(|name| wanted(&name)) { + found.push(view); + } + let listed = children(memory, view, parent + 8); + for child in listed.into_iter().rev() { + if memory.word(child + parent) == Some(view) { + stack.push(child); + } + } + } + found +} + +/// The frame view of the window whose browser view is `browser_view`: the child of the browser +/// view's parent named as a frame view. `None` when there is not exactly one. +pub(crate) fn frame_view( + memory: &M, + browser_view: usize, + parent: usize, +) -> Option { + let holder = memory.word(browser_view + parent).filter(|holder| *holder != 0)?; + let frames: Vec = children(memory, holder, parent + 8) + .into_iter() + .filter(|child| *child != browser_view) + .filter(|child| memory.word(child + parent) == Some(holder)) + .filter(|child| { + memory + .class_name(*child) + .is_some_and(|name| is_frame_view(&name)) + }) + .collect(); + match frames.as_slice() { + [only] => Some(*only), + _ => None, + } +} + +/// The class table every one of `views` begins with, when they all begin with the same one and +/// `is_table` accepts it. `None` for no views or views of different tables. +pub(crate) fn shared_table( + memory: &M, + views: &[usize], + is_table: &dyn Fn(usize) -> bool, +) -> Option { + let mut tables = views.iter().map(|view| memory.word(*view)); + let first = tables.next()??; + (tables.all(|table| table == Some(first)) && is_table(first)).then_some(first) +} + +/// One class table from what the live views gave and what the row has, both as offsets in the +/// module. Both must agree when both are known; a row without one takes the live table, and a build +/// where no live view gave one keeps the row's. +pub(crate) fn settle_table(live: Option, row: Option) -> Option { + match (live, row) { + (Some(live), Some(row)) => (live == row).then_some(row), + (Some(live), None) => Some(live), + (None, row) => row, + } +} + +/// The class tables of the window's views, as addresses. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct Tables { + pub browser_view: Option, + pub frame: Option, + pub caption: Option, + pub corner: Option, +} + +/// Reads the tables from the window whose browser view is `browser_view`. +pub(crate) fn tables_of( + memory: &M, + browser_view: usize, + parent: usize, + is_table: &dyn Fn(usize) -> bool, +) -> Tables { + let named = |name: &str| memory.class_name(browser_view).as_deref() == Some(name); + if !named(BROWSER_VIEW) { + return Tables::default(); + } + let frame = frame_view(memory, browser_view, parent); + let below = |class: &'static str| { + frame + .map(|frame| views_below(memory, frame, parent, &|name| name == class)) + .unwrap_or_default() + }; + Tables { + browser_view: shared_table(memory, &[browser_view], is_table), + frame: frame.and_then(|frame| shared_table(memory, &[frame], is_table)), + caption: shared_table(memory, &below(CAPTION_BUTTON), is_table), + corner: shared_table(memory, &below(CORNER), is_table), + } +} + +/// The tables the live views of this process gave, as offsets in the module, once read. +static FOUND: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Reads the window's class tables once per process from the browser view the view walk found, +/// as offsets in the module at `base`. +pub(crate) fn note( + memory: &M, + browser_view: usize, + parent: usize, + base: usize, + is_table: &dyn Fn(usize) -> bool, +) -> Tables { + let mut found = FOUND.lock().unwrap_or_else(|error| error.into_inner()); + if let Some(tables) = *found { + return tables; + } + let live = tables_of(memory, browser_view, parent, is_table); + let offset = |table: Option| table.map(|table| table - base); + let tables = Tables { + browser_view: offset(live.browser_view), + frame: offset(live.frame), + caption: offset(live.caption), + corner: offset(live.corner), + }; + if tables != Tables::default() { + *found = Some(tables); + } + tables +} + +/// The class table a feature uses, as an offset in the module: the row's and the live one settled +/// together, or the address the build does not have when they disagree or neither is known. +pub(crate) fn table(row: usize, live: Option) -> usize { + let row = (row != crate::builds::ABSENT).then_some(row); + settle_table(live, row).unwrap_or(crate::builds::ABSENT) +} + +/// The tables read so far, as offsets in the module. +pub(crate) fn found() -> Tables { + FOUND + .lock() + .unwrap_or_else(|error| error.into_inner()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + /// A view tree in plain memory: objects whose first word is a table, with parent and child + /// list fields where `views::View` keeps them, and class names by object. + #[derive(Default)] + struct Tree { + words: HashMap, + names: HashMap, + next_list: usize, + } + + const PARENT: usize = 0x198; + + impl Tree { + fn view(&mut self, at: usize, table: usize, name: &str) { + self.words.insert(at, table); + self.names.insert(at, name.to_owned()); + } + + fn adopt(&mut self, parent: usize, children: &[usize]) { + self.next_list += 0x1000; + let list = 0x90_0000 + self.next_list; + for (index, child) in children.iter().enumerate() { + self.words.insert(list + index * 8, *child); + self.words.insert(child + PARENT, parent); + } + self.words.insert(parent + PARENT + 8, list); + self.words.insert(parent + PARENT + 16, list + children.len() * 8); + } + } + + impl Memory for Tree { + fn word(&self, address: usize) -> Option { + Some(self.words.get(&address).copied().unwrap_or(0)) + } + fn class_name(&self, object: usize) -> Option { + self.names.get(&object).cloned() + } + } + + const BASE: usize = 0x1_8000_0000; + const NON_CLIENT: usize = 0x10_0000; + const BROWSER: usize = 0x20_0000; + const FRAME: usize = 0x30_0000; + const CONTAINER: usize = 0x40_0000; + const BUTTONS: [usize; 3] = [0x50_0000, 0x51_0000, 0x52_0000]; + + fn is_table(table: usize) -> bool { + table >= BASE + 0x100_0000 && table < BASE + 0x200_0000 + } + + /// A browser window's tree: a non-client view holding the frame view and the browser view, + /// and three caption buttons in a container of the frame view. + fn window(frame_name: &str, button_tables: [usize; 3]) -> Tree { + let mut tree = Tree::default(); + tree.view(NON_CLIENT, BASE + 0x100_1000, "NonClientView"); + tree.view(BROWSER, BASE + 0x100_2000, BROWSER_VIEW); + tree.view(FRAME, BASE + 0x100_3000, frame_name); + tree.view(CONTAINER, BASE + 0x100_4000, "WindowsCaptionButtonContainer"); + for (button, table) in BUTTONS.iter().zip(button_tables) { + tree.view(*button, table, CAPTION_BUTTON); + } + tree.adopt(NON_CLIENT, &[FRAME, BROWSER]); + tree.adopt(FRAME, &[CONTAINER]); + tree.adopt(CONTAINER, &BUTTONS); + tree + } + + #[test] + fn nfr6_a_views_class_table_is_read_from_its_live_views() { + let caption = BASE + 0x100_5000; + let tree = window("EdgeBrowserFrameViewWin", [caption; 3]); + let tables = tables_of(&tree, BROWSER, PARENT, &is_table); + assert_eq!(tables.browser_view, Some(BASE + 0x100_2000)); + assert_eq!(tables.frame, Some(BASE + 0x100_3000)); + assert_eq!(tables.caption, Some(caption)); + // The window has no corner wedges, so their table stays the row's. + assert_eq!(tables.corner, None); + let buttons = views_below(&tree, FRAME, PARENT, &|name| name == CAPTION_BUTTON); + assert_eq!(buttons, BUTTONS); + } + + #[test] + fn nfr6_live_views_of_one_class_must_share_their_table() { + let (one, other) = (BASE + 0x100_5000, BASE + 0x100_6000); + let tree = window("BrowserFrameViewWin", [one, one, other]); + assert_eq!(tables_of(&tree, BROWSER, PARENT, &is_table).caption, None); + // A first word outside the module's tables is no class table. + let tree = window("BrowserFrameViewWin", [0x1234; 3]); + assert_eq!(tables_of(&tree, BROWSER, PARENT, &is_table).caption, None); + // Only a view named as a frame view is the frame view. + let tree = window("OpaqueTitleBar", [BASE + 0x100_5000; 3]); + let tables = tables_of(&tree, BROWSER, PARENT, &is_table); + assert_eq!((tables.frame, tables.caption), (None, None)); + // The walk starts only from a view named as the browser view. + let tree = window("BrowserFrameViewWin", [BASE + 0x100_5000; 3]); + assert_eq!(tables_of(&tree, FRAME, PARENT, &is_table), Tables::default()); + } + + #[test] + fn nfr6_a_row_without_a_class_table_takes_the_live_one() { + let absent = crate::builds::ABSENT; + assert_eq!(table(absent, Some(0x1185_ff40)), 0x1185_ff40); + assert_eq!(table(0x1185_ff40, Some(0x1185_ff40)), 0x1185_ff40); + assert_eq!(table(0x1185_ff40, Some(0x11b5_2528)), absent); + assert_eq!(table(0x1185_ff40, None), 0x1185_ff40); + assert_eq!(table(absent, None), absent); + } + + #[test] + fn nfr6_a_live_table_and_the_rows_must_agree() { + assert_eq!(settle_table(Some(0x10), Some(0x10)), Some(0x10)); + assert_eq!(settle_table(Some(0x10), Some(0x18)), None); + assert_eq!(settle_table(Some(0x10), None), Some(0x10)); + assert_eq!(settle_table(None, Some(0x18)), Some(0x18)); + assert_eq!(settle_table(None, None), None); + } +} diff --git a/rivet/runtime/windows/src/chromium/mod.rs b/rivet/runtime/windows/src/chromium/mod.rs index 8cef86b..d604aca 100644 --- a/rivet/runtime/windows/src/chromium/mod.rs +++ b/rivet/runtime/windows/src/chromium/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod image; +pub(crate) mod live_tables; pub(crate) mod memory; pub(crate) mod reflect; pub(crate) mod screen; diff --git a/rivet/runtime/windows/src/chromium/window_views.rs b/rivet/runtime/windows/src/chromium/window_views.rs index 94e412d..d9b511d 100644 --- a/rivet/runtime/windows/src/chromium/window_views.rs +++ b/rivet/runtime/windows/src/chromium/window_views.rs @@ -438,6 +438,50 @@ pub(crate) unsafe fn walk_views_once(window: windows_sys::Win32::Foundation::HWN }); } +/// Reads the class tables of `window`'s views from the live views once per process: the browser +/// view the view walk found, its frame view and the frame view's caption buttons and corners. The +/// walk's result is reused when the worker thread already has it. Reads memory only. +pub(crate) unsafe fn read_tables( + window: windows_sys::Win32::Foundation::HWND, +) -> crate::chromium::live_tables::Tables { + use crate::chromium::live_tables; + use windows_sys::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, GWLP_USERDATA}; + let known = live_tables::found(); + if known != live_tables::Tables::default() { + return known; + } + let (Some(live), Some(build), Some(image)) = + (live(), fingerprint(), crate::chromium::image::recorded()) + else { + return known; + }; + let handler = GetWindowLongPtrW(window, GWLP_USERDATA) as usize; + let found = crate::chromium::reflect::find_cached( + &live.ranges, + handler, + std::time::Duration::from_millis(300), + build, + ); + let Ok((found, _)) = found else { + return known; + }; + let Some(browser_view) = found.browser_view else { + return known; + }; + let ranges = live.ranges; + // A class table lies in read-only data and its first slot holds code. + let is_table = |table: usize| { + table >= ranges.rdata.0 + && table < ranges.rdata.1 + && live + .word(table) + .is_some_and(|slot| slot >= ranges.text.0 && slot < ranges.text.1) + }; + let tables = live_tables::note(live, browser_view, found.parent, image.base, &is_table); + crate::trace::trace(&format!("window views: class tables from live views {tables:x?}")); + tables +} + /// The browser module's fingerprint, which keys what the view walk found. fn fingerprint() -> Option<(u32, u32)> { let image = crate::chromium::image::recorded()?; diff --git a/rivet/runtime/windows/src/features/frame_layout.rs b/rivet/runtime/windows/src/features/frame_layout.rs index 56e4b19..310d70a 100644 --- a/rivet/runtime/windows/src/features/frame_layout.rs +++ b/rivet/runtime/windows/src/features/frame_layout.rs @@ -129,6 +129,30 @@ pub(crate) fn needs_top_inset(build: &Build) -> Needs { Needs::targets(vec![Target::new("top inset", build.layout.top_inset, &[])]) } +/// The frame view's class table: the row's, read again from the window's live frame view. +fn frame_table() -> usize { + use crate::chromium::live_tables; + live_tables::table(bv().frame_vtable, live_tables::found().frame) +} + +/// The caption buttons' class table, settled with the live buttons' as `frame_table` is. +fn caption_table() -> usize { + use crate::chromium::live_tables; + live_tables::table(bv().caption_vtable, live_tables::found().caption) +} + +/// The corner wedges' class table, settled with the live wedges' as `frame_table` is. +fn corner_table() -> usize { + use crate::chromium::live_tables; + live_tables::table(bv().corner_vtable, live_tables::found().corner) +} + +/// The browser view's class table, settled with the live browser view's as `frame_table` is. +fn browser_view_table() -> usize { + use crate::chromium::live_tables; + live_tables::table(bv().browser_view_view_vtable, live_tables::found().browser_view) +} + fn recorded_image() -> Result { image::recorded().ok_or_else(|| "this browser build is not supported yet".to_owned()) } @@ -394,7 +418,7 @@ unsafe extern "system" fn corner_paint(view: *const c_void, canvas: *const c_voi } unsafe fn install_corner_paint(image: &Image) -> Result<(), String> { - let slot_rva = bv().corner_vtable + bv().on_paint_slot * 8; + let slot_rva = corner_table() + bv().on_paint_slot * 8; if !image.has(bv().corner_paint, bv().corner_paint_prologue) { return Err("this browser build has no recorded corner paint".into()); } @@ -420,7 +444,7 @@ pub unsafe fn install_frame_paint(paint: Paint) -> Result<(), String> { return Err("this browser build has no verified colour provider layout".into()); } let image = recorded_image()?; - let slot_rva = bv().frame_vtable + bv().on_paint_slot * 8; + let slot_rva = frame_table() + bv().on_paint_slot * 8; if !image.points_to(slot_rva, bv().on_paint) { return Err("this browser build has no recorded frame paint".into()); } @@ -765,7 +789,7 @@ pub unsafe fn install_caption_paint() -> Result<(), String> { return Err("this browser build has no verified colour provider layout".into()); } let image = recorded_image()?; - let slot_rva = bv().caption_vtable + bv().caption_paint_slot * 8; + let slot_rva = caption_table() + bv().caption_paint_slot * 8; if !image.points_to(slot_rva, bv().caption_paint) || !image.has(bv().caption_paint, bv().caption_paint_prologue) || !image.has(bv().get_color_provider, bv().get_color_provider_prologue) @@ -805,7 +829,7 @@ pub unsafe fn install_caption_height(height: CaptionHeight) -> Result<(), String return Ok(()); } let image = recorded_image()?; - let slot_rva = bv().caption_vtable + bv().caption_size_slot * 8; + let slot_rva = caption_table() + bv().caption_size_slot * 8; if !image.points_to(slot_rva, bv().caption_size) { return Err("this browser build has no recorded caption button size".into()); } @@ -851,7 +875,7 @@ pub unsafe fn install_top_inset(extra: ExtraTop) -> Result<(), String> { return Ok(()); } let image = recorded_image()?; - let slot_rva = bv().frame_vtable + bv().top_inset_slot * 8; + let slot_rva = frame_table() + bv().top_inset_slot * 8; if !image.points_to(slot_rva, bv().top_inset) { return Err("this browser build has no recorded top inset".into()); } @@ -903,7 +927,7 @@ unsafe fn clip_panel(frame: *mut c_void) { }; let base = image.base; let Some(index) = - (0..0x100).find(|index| *browser.add(*index) == base + bv().browser_view_view_vtable) + (0..0x100).find(|index| *browser.add(*index) == base + browser_view_table()) else { return; }; @@ -1052,7 +1076,7 @@ pub unsafe fn install_caption_layout(height: CaptionHeight) -> Result<(), String return Ok(()); } let image = recorded_image()?; - let slot_rva = bv().frame_vtable + bv().layout_slot * 8; + let slot_rva = frame_table() + bv().layout_slot * 8; if !image.points_to(slot_rva, bv().layout) { return Err("this browser build has no recorded frame layout".into()); } diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index 8be16e6..f031b6f 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -2867,6 +2867,12 @@ fn attach_steps() -> Vec> { false, Some("rivet: not attaching to this browser"), ), + // The class tables of the frame view, its caption buttons and corners and the browser view + // are read from the window's live views before the features that replace their slots. + Step::Setup(|attach| unsafe { + crate::chromium::window_views::read_tables(attach.window); + true + }), feature( Feature::FrameColour, frame_layout::needs_colour, From b6f64779bfc049f16aa35ac2bccc46c470658aab Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:18:32 +0000 Subject: [PATCH 08/29] Publish: develop 973d065 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 24 ++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index 6e5cc49..6679072 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -1057,10 +1057,17 @@ pub fn resolve( } let from = prior_callers.get(&target); if let (Some(list), Some(from)) = (&want.candidates, from) { + // A known caller is a call from a function known in both builds, the same + // kind of fact as the calls into it, so it is never counted beside them and + // the fingerprint's places only limit where it may point. let given = by_known_callers(&mut new, &known, from, list); - answers.extend(fingerprint_agrees(&given, Some(list.as_slice()))); for place in given { - answers.push((Method::KnownCaller, place)); + let seen = answers + .iter() + .any(|(method, at)| *method == Method::CallsInto && *at == place); + if !seen { + answers.push((Method::KnownCaller, place)); + } } } if let Some(place) = by_command.get(&target).copied() { @@ -1676,15 +1683,14 @@ pub(crate) mod tests { } #[test] - fn nfr6_a_drawing_helper_is_found_by_the_call_from_its_caller() { + fn nfr6_a_drawing_helper_is_not_placed_by_its_caller_alone() { // The caller, as a frame view's paint calls `DrawColor`, is known in both builds, and of - // the two places the helper's fingerprint matched, its new body calls one. + // the two places the helper's fingerprint matched, its new body calls one. That call is the + // same kind of fact as the calls into it, and the fingerprint matched both places, so it is + // one method and the helper waits for a second one. let resolution = run_known_caller(None); - assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); - assert_eq!( - resolution.settled, - ["0x101100 -> 0x103100 by its fingerprint and a known caller"] - ); + assert!(resolution.places.is_empty(), "{:?}", resolution.places); + assert!(resolution.settled.is_empty(), "{:?}", resolution.settled); } #[test] From 909bfd1bd2a0a9cb0e049e582a0690cb9b1d1e20 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:37:48 +0000 Subject: [PATCH 09/29] Publish: develop c6a328e to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .github/scripts/rows/fetch-symbols.ps1 | 32 - .github/workflows/browser-rows.yml | 281 ++--- .../platform/windows/src/bin/chrome-builds.rs | 761 +++----------- rivet/platform/windows/src/chrome_build.rs | 57 +- rivet/platform/windows/src/row_class.rs | 203 +++- rivet/platform/windows/src/row_port.rs | 984 ++++++------------ rivet/platform/windows/src/row_recipe.rs | 4 +- rivet/platform/windows/src/row_resolve.rs | 6 +- rivet/platform/windows/src/row_watch.rs | 2 +- rivet/runtime/windows/rows/table.json | 14 +- rivet/runtime/windows/src/builds/tests.rs | 30 - scripts/check.sh | 1 + scripts/tests/browser-rows.test.sh | 10 +- scripts/tests/no-pdb.test.sh | 43 + scripts/tests/row-port.ps1 | 62 -- scripts/tests/row-score.ps1 | 98 ++ 16 files changed, 871 insertions(+), 1717 deletions(-) delete mode 100644 .github/scripts/rows/fetch-symbols.ps1 create mode 100755 scripts/tests/no-pdb.test.sh delete mode 100644 scripts/tests/row-port.ps1 create mode 100644 scripts/tests/row-score.ps1 diff --git a/.github/scripts/rows/fetch-symbols.ps1 b/.github/scripts/rows/fetch-symbols.ps1 deleted file mode 100644 index 118c4d7..0000000 --- a/.github/scripts/rows/fetch-symbols.ps1 +++ /dev/null @@ -1,32 +0,0 @@ -param( - [Parameter(Mandatory = $true)][string]$Browser, - [Parameter(Mandatory = $true)][string]$Key, - [Parameter(Mandatory = $true)][string]$Out, - # Prints the address without fetching it. - [switch]$ResolveOnly -) - -$ErrorActionPreference = 'Stop' -# Each maker publishes its symbols in its own place. Brave keeps them gzipped. These are only for -# making rows on the build machine: a Rivet on a person's computer never downloads a PDB. -$url, $packed = switch ($Browser) { - 'Google Chrome' { "https://chromium-browser-symsrv.commondatastorage.googleapis.com/chrome.dll.pdb/$Key/chrome.dll.pdb", $false } - 'Microsoft Edge' { "https://msdl.microsoft.com/download/symbols/msedge.dll.pdb/$Key/msedge.dll.pdb", $false } - 'Brave' { "https://brave-symbols.s3.brave.com/chrome.dll.pdb/$Key/chrome.dll.pdb", $true } - default { throw "No public symbols are known for $Browser" } -} -if ($ResolveOnly) { $url; return } -$target = if ($packed) { "$Out.gz" } else { $Out } -curl.exe -fsSL --retry 3 -o $target $url -# curl exits with 22 when the server answers with an error, which for a symbol server means the PDB -# is not published yet. The caller may then make the row without it, so that case has its own type. -if ($LASTEXITCODE -eq 22) { throw [System.IO.FileNotFoundException]::new("The symbol server has no PDB at $url yet") } -if ($LASTEXITCODE -ne 0) { throw "Could not download ${url}: curl exited with $LASTEXITCODE" } -if ($packed) { - $in = [IO.File]::OpenRead($target) - $gzip = [IO.Compression.GZipStream]::new($in, [IO.Compression.CompressionMode]::Decompress) - $to = [IO.File]::Create($Out) - $gzip.CopyTo($to) - $to.Dispose(); $gzip.Dispose(); $in.Dispose() - Remove-Item $target -} diff --git a/.github/workflows/browser-rows.yml b/.github/workflows/browser-rows.yml index d0c5a42..5b0cbf5 100644 --- a/.github/workflows/browser-rows.yml +++ b/.github/workflows/browser-rows.yml @@ -1,9 +1,9 @@ # Keeps Rivet's supported-build table ahead of Chrome, Edge and Brave. # # A browser updates itself whenever its maker says, and Rivet does not hold it back. So this job -# watches what the makers publish, builds a whole row for each new build from public symbols, -# proves the row on the real browser, and publishes a signed table that reaches people without -# reinstalling Rivet. A row the generator cannot vouch for, such as the first of a new milestone, +# watches what the makers publish, builds a whole row for each new build from the verified row of +# the build before it, proves the row on the real browser, and publishes a signed table that reaches +# people without reinstalling Rivet. A row the generator cannot vouch for, such as the first of a new milestone, # becomes a pull request for a person and is not published. # # Needs on the default branch: this file. Needs in the repository's secrets: @@ -18,11 +18,16 @@ # that failed, its reason and the capture of the failing window. Each step records its reason in # `failure.txt` before it stops. # -# A maker can ship a build before its PDB reaches the symbol server. Then the row is made from the -# fingerprints of the prior row's functions, each of which must match one place in the new module, -# and every offset, slot and size is read again from the new module as for a row made from symbols. -# Such a row is marked, so once the PDB appears the job makes the row again from it and compares the -# two. A difference opens an issue. +# No browser's debug symbols are downloaded or read. A maker can ship a build long before its +# symbols appear, or never publish them. A row is made from the verified prior row, the fingerprints +# of its functions, the prior build's module and the new build's module: each function must match +# one place, or two independent methods must agree on it, and every offset, slot and size is read +# again from the new module. A feature whose values are not found is off in the row, and a part the +# window cannot do without stops the row for a person. +# +# A run started by hand with `score` makes, the same way, the rows of builds that already have a +# verified row, and compares them value by value. It is a measurement: it publishes, proposes and +# reports nothing, and fails only when a value it found differs from the verified one. name: Browser rows on: @@ -44,6 +49,10 @@ on: description: "With trial: the builds to make, as browser@version separated by semicolons, instead of those the feeds list." required: false default: "" + score: + description: "Score the generator on builds that have a verified row, as browser@prior>new separated by semicolons, or 'default' for scripts/tests/row-score.ps1's list. Nothing is published." + required: false + default: "" permissions: contents: write @@ -59,7 +68,7 @@ concurrency: env: RELEASE_TAG: builds-table - # Symbols are several gigabytes, and a run does no more than this many builds. + # Each build is a download of hundreds of megabytes, and a run does no more than this many builds. MOST_PER_RUN: "3" jobs: @@ -112,7 +121,7 @@ jobs: watch: name: Find builds with no row needs: gate - if: needs.gate.outputs.enabled == 'true' && github.event.inputs.withdraw == '' + if: needs.gate.outputs.enabled == 'true' && github.event.inputs.withdraw == '' && github.event.inputs.score == '' runs-on: windows-latest defaults: run: @@ -193,41 +202,8 @@ jobs: "::warning::$($build.browser) $($build.version) has no row and cannot be fetched yet: $_" } } - # A row made without its PDB is made again from the PDB once the symbol server has it, and - # the two are compared. Such a row may wait in develop's table or on a row branch. - $sources = @([pscustomobject]@{ source = 'develop'; file = 'rivet/runtime/windows/rows/table.json' }) - foreach ($line in @(git ls-remote --heads origin)) { - $branch = ($line -split "`t")[1] -replace '^refs/heads/', '' - if (-not ($branch -like 'feat/row-*' -or $branch -like 'feat/rows-*') -or $branch -like 'feat/row-pdb-*') { continue } - git fetch --quiet --depth 1 origin $branch - if ($LASTEXITCODE -ne 0) { continue } - $file = Join-Path $feeds ("table-" + ($branch -replace '[^A-Za-z0-9.]+', '-') + ".json") - git show "FETCH_HEAD:rivet/runtime/windows/rows/table.json" | Set-Content $file - if ($LASTEXITCODE -eq 0) { $sources += [pscustomobject]@{ source = $branch; file = $file } } - } - $open = @(gh issue list --state open --label browser-rows --limit 100 --json title | ConvertFrom-Json | ForEach-Object title) - $seen = @{} - $rechecks = foreach ($source in $sources) { - foreach ($row in @((Get-Content -Raw $source.file | ConvertFrom-Json).rows)) { - $mark = $row.made_without_pdb - if (-not $mark) { continue } - $browser = $row.frame.browser - $version = $row.frame.version - if ($seen["$browser $version"]) { continue } - $seen["$browser $version"] = $true - # A confirmation waits for review, and a difference waits on its issue. - $slug = "$($browser -replace ' ','-')-$version".ToLower() - git ls-remote --exit-code --heads origin "feat/row-pdb-$slug" | Out-Null - if ($LASTEXITCODE -eq 0) { continue } - if ($open -contains "Row differs from its PDB: $browser $version") { continue } - $url = ./.github/scripts/rows/fetch-symbols.ps1 -Browser $browser -Key $mark.pdb_key -Out unused -ResolveOnly - curl.exe -fsSL -r 0-0 -o NUL $url - if ($LASTEXITCODE -ne 0) { "$browser $version still has no PDB."; continue } - [pscustomobject]@{ browser = $browser; version = $version; channel = $mark.channel; download = $mark.download; recheck = $source.source } - } - } $global:LASTEXITCODE = 0 - $builds = @(@($builds) + @($rechecks) | Where-Object { $_ -and $_ -isnot [string] } | Select-Object -First ([int]$env:MOST_PER_RUN)) + $builds = @(@($builds) | Where-Object { $_ -and $_ -isnot [string] } | Select-Object -First ([int]$env:MOST_PER_RUN)) # Through the pipeline: -InputObject would wrap the whole list as one element of another list. $json = if ($builds.Count) { $builds | ConvertTo-Json -Compress -AsArray } else { "[]" } "builds=$json" >> $env:GITHUB_OUTPUT @@ -263,7 +239,7 @@ jobs: name: row-tools path: tools - - name: Get the build and its symbols + - name: Get the build id: build run: | trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Get the build: $_"; break } @@ -272,114 +248,50 @@ jobs: -Channel "${{ matrix.build.channel }}" -Download "${{ matrix.build.download }}" ` -Out (Join-Path $env:RUNNER_TEMP "browser") -Output $env:GITHUB_OUTPUT - - name: Download the symbols of this build and of the row before it - id: symbols - env: - RECHECK: ${{ matrix.build.recheck }} + - name: Get the build of the row before it + id: prior run: | - trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Download the symbols: $_"; break } + trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Get the prior build: $_"; break } $browser = "${{ matrix.build.browser }}" $version = "${{ matrix.build.version }}" $temp = $env:RUNNER_TEMP $prior = Join-Path $temp "prior.json" - $tables = @("--table", "rivet/runtime/windows/rows/table.json") - $before = $version - if ($env:RECHECK) { - # The row made without its PDB, from where it is kept, and the prior row it was made from. - $stored = Join-Path $temp "stored-table.json" - if ($env:RECHECK -eq 'develop') { - Copy-Item rivet/runtime/windows/rows/table.json $stored - } else { - git fetch --quiet --depth 1 origin $env:RECHECK - if ($LASTEXITCODE -ne 0) { throw "Could not fetch $env:RECHECK" } - git show "FETCH_HEAD:rivet/runtime/windows/rows/table.json" | Set-Content $stored - if ($LASTEXITCODE -ne 0) { throw "$env:RECHECK has no table" } - } - $row = @((Get-Content -Raw $stored | ConvertFrom-Json).rows) | - Where-Object { $_.frame.browser -eq $browser -and $_.frame.version -eq $version } | Select-Object -First 1 - if (-not $row.made_without_pdb) { throw "$env:RECHECK holds no row of $browser $version made without its PDB" } - $before = $row.made_without_pdb.prior_version - $tables += @("--table", $stored) - } - ./tools/rivet-rows.exe prior $browser $before @tables | Set-Content $prior + ./tools/rivet-rows.exe prior $browser $version --table rivet/runtime/windows/rows/table.json | Set-Content $prior if ($LASTEXITCODE -ne 0) { throw "rivet-rows found no prior row for $browser $version" } - $priorRow = Get-Content -Raw $prior | ConvertFrom-Json - $priorVersion = $priorRow.frame.version - $priorKey = $null - foreach ($file in @($tables | Where-Object { $_ -ne '--table' })) { - if (-not $priorKey) { $priorKey = (Get-Content -Raw $file | ConvertFrom-Json).symbols."$browser $priorVersion" } - } - if (-not $priorKey) { throw "The table holds no symbol key for the prior row $browser $priorVersion. Add it to rows/table.json with chrome-builds pdb-key." } - $newKey = ./tools/chrome-builds.exe pdb-key "${{ steps.build.outputs.module }}" - if ($LASTEXITCODE -ne 0) { throw "chrome-builds could not read the symbol key of the new module" } - # The prior row's PDB names what the row is made from, so without it nothing is made. - ./.github/scripts/rows/fetch-symbols.ps1 -Browser $browser -Key $priorKey -Out (Join-Path $temp "prior.pdb") + $priorVersion = (Get-Content -Raw $prior | ConvertFrom-Json).frame.version + # The prior build's own module gives what its row was made from: its function starts, + # its class names and the instructions the methods compare with the new build. + $found = Join-Path $temp "prior-build.txt" + $fetch = @{ Browser = $browser; Version = $priorVersion; Out = (Join-Path $temp "prior-browser"); Output = $found } try { - ./.github/scripts/rows/fetch-symbols.ps1 -Browser $browser -Key ($newKey -split '/')[1] -Out (Join-Path $temp "new.pdb") - "no_pdb=false" >> $env:GITHUB_OUTPUT - } catch [System.IO.FileNotFoundException] { - if ($env:RECHECK) { throw } - "::warning::$($_.Exception.Message). The row is made from the fingerprints of the $browser $priorVersion row." - "no_pdb=true" >> $env:GITHUB_OUTPUT - # The prior build gives the fingerprints when the prior row stored none, and in any case - # tells which prior addresses are function starts, so a match elsewhere does not count. - $found = Join-Path $temp "prior-build.txt" - $fetch = @{ Browser = $browser; Version = $priorVersion; Out = (Join-Path $temp "prior-browser"); Output = $found } - try { - ./.github/scripts/rows/fetch-browser.ps1 @fetch -Channel "${{ matrix.build.channel }}" - } catch { - if ("${{ matrix.build.channel }}" -eq 'stable') { throw "The symbol server has no PDB for $browser $version, and the prior build $priorVersion could not be fetched for its fingerprints: $_" } - ./.github/scripts/rows/fetch-browser.ps1 @fetch -Channel stable - } - $priorModule = (Get-Content $found | Where-Object { $_ -like 'module=*' } | Select-Object -First 1) -replace '^module=', '' - $priorModuleKey = ./tools/chrome-builds.exe pdb-key $priorModule - if (($priorModuleKey -split '/')[1] -ne $priorKey) { throw "The fetched $browser $priorVersion is not the build the prior row was made for" } - "prior_module=$priorModule" >> $env:GITHUB_OUTPUT + ./.github/scripts/rows/fetch-browser.ps1 @fetch -Channel "${{ matrix.build.channel }}" + } catch { + if ("${{ matrix.build.channel }}" -eq 'stable') { throw "The prior build $browser $priorVersion could not be fetched: $_" } + ./.github/scripts/rows/fetch-browser.ps1 @fetch -Channel stable } + $priorModule = (Get-Content $found | Where-Object { $_ -like 'module=*' } | Select-Object -First 1) -replace '^module=', '' + "module=$priorModule" >> $env:GITHUB_OUTPUT - name: Make the row id: made env: - NO_PDB: ${{ steps.symbols.outputs.no_pdb }} - PRIOR_MODULE: ${{ steps.symbols.outputs.prior_module }} - RECHECK: ${{ matrix.build.recheck }} - CHANNEL: ${{ matrix.build.channel }} - DOWNLOAD: ${{ matrix.build.download }} + PRIOR_MODULE: ${{ steps.prior.outputs.module }} run: | trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Make the row: $_"; break } $temp = $env:RUNNER_TEMP - $browser = "${{ matrix.build.browser }}" - $version = "${{ matrix.build.version }}" - if ($env:NO_PDB -eq 'true') { - # Every function is looked for by its fingerprint, and one that does not match exactly - # one place leaves the row for review. Offsets, slots and sizes are read as below. - ./tools/chrome-builds.exe find "$temp/prior.json" "$temp/prior.pdb" $env:PRIOR_MODULE "${{ steps.build.outputs.module }}" $version $env:CHANNEL "$env:DOWNLOAD" "$temp/row.json" "$temp/report.json" - $code = $LASTEXITCODE - if ($code -ne 0 -and $code -ne 3) { throw "chrome-builds find exited with $code" } - } else { - ./tools/chrome-builds.exe port "$temp/prior.json" "$temp/prior.pdb" "$temp/new.pdb" "${{ steps.build.outputs.module }}" $version "$temp/row.json" "$temp/report.json" - $code = $LASTEXITCODE - if ($code -ne 0 -and $code -ne 3) { throw "chrome-builds port exited with $code; report.json says why" } - } - if ($env:RECHECK) { - # The PDB is out now: the row made from it must agree with the row made without it. - ./tools/chrome-builds.exe pdb-check "$temp/stored-table.json" $browser $version "$temp/row.json" | Tee-Object "$temp/differences.txt" - $check = $LASTEXITCODE - if ($check -ne 0 -and $check -ne 4) { throw "chrome-builds pdb-check exited with $check" } - "checked=$(if ($check -eq 0) { 'agree' } else { 'differ' })" >> $env:GITHUB_OUTPUT - "for_review=recheck" >> $env:GITHUB_OUTPUT - Get-Content "$temp/report.json" - exit 0 - } - # Fingerprints let a Rivet find these functions in a later build that has no row yet. A row - # whose addresses cannot all be fingerprinted is still a good row, just without them. A row - # made without its PDB that is not vouched for still holds prior addresses, which would - # fingerprint the wrong code, so it gets none. - if ($env:NO_PDB -eq 'true' -and $code -ne 0) { - "A row made without its PDB that needs review gets no fingerprints." - } else { + # Every function is looked for by its fingerprint and the methods that read the prior + # build next to the new one. Offsets, slots and sizes are read from the new module. + ./tools/chrome-builds.exe find "$temp/prior.json" $env:PRIOR_MODULE "${{ steps.build.outputs.module }}" "${{ matrix.build.version }}" "$temp/row.json" "$temp/report.json" + $code = $LASTEXITCODE + if ($code -ne 0 -and $code -ne 3) { throw "chrome-builds find exited with $code; report.json says why" } + # Fingerprints, read from this build's own module at the places the row holds, let the + # next build's row start from this one. A row that needs review may still hold a prior + # address, which would fingerprint the wrong code, so it gets none. + if ($code -eq 0) { ./tools/chrome-builds.exe fingerprint "$temp/row.json" "${{ steps.build.outputs.module }}" "$temp/row.json" if ($LASTEXITCODE -ne 0) { "The row has no fingerprints." } + } else { + "A row that needs review gets no fingerprints." } "for_review=$($code -eq 3)".ToLower() >> $env:GITHUB_OUTPUT Get-Content "$temp/report.json" @@ -398,8 +310,8 @@ jobs: Set-Content (Join-Path $temp "test-key.txt") $env:RIVET_TABLE_PUBLIC_KEY $env:LOCALAPPDATA = Join-Path $temp "local" New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null - Set-Content "$temp/part.json" '{"schema":1,"sequence":0,"symbols":{},"rows":[]}' - ./tools/chrome-builds.exe table-add "$temp/part.json" "$temp/row.json" "${{ steps.build.outputs.module }}" + Set-Content "$temp/part.json" '{"schema":1,"sequence":0,"rows":[]}' + ./tools/chrome-builds.exe table-add "$temp/part.json" "$temp/row.json" ./tools/chrome-builds.exe table-sign "$temp/part.json" "$temp/test.bin" Push-Location rivet cargo build -p rivet -p rivet-runtime-windows @@ -453,60 +365,8 @@ jobs: ${{ runner.temp }}/session/features/traces/**/*.log ${{ runner.temp }}/session/features/*/*.png ${{ runner.temp }}/session/features/profiles/*/Crashpad/reports/*.dmp - ${{ runner.temp }}/differences.txt retention-days: 30 - - name: Tell a person that a row made without its PDB differs from it - if: steps.made.outputs.checked == 'differ' && !inputs.trial - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RECHECK: ${{ matrix.build.recheck }} - run: | - $temp = $env:RUNNER_TEMP - $browser = "${{ matrix.build.browser }}" - $version = "${{ matrix.build.version }}" - $reasons = Join-Path $temp "differences-reasons.txt" - Set-Content $reasons "The row in $env:RECHECK was made from fingerprints, and the row its PDB gives differs from it:" - Get-Content "$temp/differences.txt" | Add-Content $reasons - ./.github/scripts/rows/report-failure.ps1 ` - -Title "Row differs from its PDB: $browser $version" ` - -Reasons $reasons -Files "${{ steps.files.outputs.artifact-url }}" - - - name: Confirm a row made without its PDB - if: steps.made.outputs.checked == 'agree' && !inputs.trial - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RECHECK: ${{ matrix.build.recheck }} - run: | - $temp = $env:RUNNER_TEMP - $browser = "${{ matrix.build.browser }}" - $version = "${{ matrix.build.version }}" - git config user.name "rivet-browser-rows" - git config user.email "rivet-browser-rows@users.noreply.github.com" - # A row on its own branch is confirmed there. A row in develop is confirmed by a pull request. - if ($env:RECHECK -eq 'develop') { - $branch = "feat/row-pdb-$($browser -replace ' ','-')-$version".ToLower() - git switch -c $branch - } else { - $branch = $env:RECHECK - git fetch --quiet --depth 1 origin $branch - git switch -c $branch FETCH_HEAD - } - ./tools/chrome-builds.exe pdb-check rivet/runtime/windows/rows/table.json $browser $version "$temp/row.json" - if ($LASTEXITCODE -ne 0) { throw "chrome-builds pdb-check exited with $LASTEXITCODE on $branch" } - git add rivet/runtime/windows/rows/table.json - git commit -m "Fix: Confirm the row of $browser $version with its PDB" - git push origin "HEAD:$branch" - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $note = "The row of $browser $version was made from fingerprints because its PDB was not published. The PDB is out now, the row made from it agrees, and the mark is removed in run $env:GITHUB_RUN_ID." - if ($env:RECHECK -eq 'develop') { - gh pr create --base develop --head $branch --title "Fix: Confirm the row of $browser $version with its PDB" --body $note - gh workflow run test.yml --ref $branch - } else { - gh pr comment $branch --body $note - $global:LASTEXITCODE = 0 - } - - name: Tell a person that this build failed if: failure() && !inputs.trial env: @@ -530,15 +390,12 @@ jobs: git config user.name "rivet-browser-rows" git config user.email "rivet-browser-rows@users.noreply.github.com" git switch -c $branch - ./tools/chrome-builds.exe table-add rivet/runtime/windows/rows/table.json "$temp/row.json" "${{ steps.build.outputs.module }}" + ./tools/chrome-builds.exe table-add rivet/runtime/windows/rows/table.json "$temp/row.json" git add rivet/runtime/windows/rows/table.json git commit -m "Feat: Propose a row for ${{ matrix.build.browser }} ${{ matrix.build.version }}" git push -u origin $branch $report = Get-Content -Raw "$temp/report.json" | ConvertFrom-Json - $body = "The generator could not vouch for this row, so it was not published.`n`n" - if ($report.made_without_pdb) { - $body += "The symbol server had no PDB for this build, so the row was made from the fingerprints of the $($report.prior_version) row: $($report.fingerprinted.Count) of $($report.addresses) addresses matched exactly one place. When the PDB appears, the row job makes the row again from it and compares the two.`n`n" - } + $body = "The generator could not vouch for this row, so it was not published. It was made from the $($report.prior_version) row: $($report.fingerprinted.Count) of $($report.addresses) addresses matched exactly one place by fingerprint, and $($report.settled.Count) were settled by two methods.`n`n" $body += (($report.review | ForEach-Object { "- $_" }) -join "`n") if ($report.switched_off.Count -gt 0) { $body += "`n`nThese features are off in this row, because a value they need could not be read from this build:`n`n" @@ -621,3 +478,37 @@ jobs: git push -u origin $branch gh pr create --base develop --head $branch --title "Feat: Record rows published by the table job" --body "These rows are already published in the signed table and passed the row proof in run $env:GITHUB_RUN_ID. Merging adds them to the table compiled into the next Rivet." gh workflow run test.yml --ref $branch + + score: + name: Score the generator against verified rows + # A measurement: it needs no signing key, and it publishes, proposes and reports nothing. + if: github.event.inputs.score != '' + runs-on: windows-latest + permissions: + contents: read + defaults: + run: + shell: pwsh + steps: + - uses: actions/checkout@v4 + + - name: Build the row tools + working-directory: rivet + run: cargo build --release -p rivet-platform-windows -p rivet-runtime-windows --bins + + - name: Make each row without symbols and compare it with its verified row + env: + SCORE: ${{ github.event.inputs.score }} + run: | + $pairs = if ($env:SCORE -eq 'default') { @() } else { @($env:SCORE -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } + ./scripts/tests/row-score.ps1 ` + -Rows rivet/target/release/rivet-rows.exe -Generator rivet/target/release/chrome-builds.exe ` + -Table rivet/runtime/windows/rows/table.json -Pairs $pairs -Fetch ` + -Work (Join-Path $env:RUNNER_TEMP "score") + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: row-score + path: ${{ runner.temp }}/score/*.json + retention-days: 30 diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index af0f457..d70f005 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -1,25 +1,17 @@ -//! Adds a Chromium build to Rivet's supported-build table from the build's public symbols. +//! Makes and publishes rows of Rivet's supported-build table. No browser's debug symbols are read: +//! a new row comes from the verified prior row, its fingerprints, the prior module and the new one. //! -//! `chrome-builds pdb-key ` prints the symbol-server path of the module's PDB. -//! `chrome-builds extract
[frame-class]` -//! resolves the layout hook's addresses with DbgHelp, checks them against the module file and -//! updates the table. The frame class is `BrowserFrameViewWin` unless the browser builds its -//! windows from a subclass of it. -//! `chrome-builds port ` -//! makes a whole row for a new build from the row of a prior build, and exits 3 when the row needs -//! a person's review. -//! `chrome-builds find ` -//! makes a candidate row for a new build whose PDB is not published, from the fingerprints of the -//! prior row: those it stored, or else those read now from the prior build's module. It marks the -//! row as made without its PDB and exits 3 when the row needs a person's review. -//! `chrome-builds pdb-check ` compares a row made -//! without its PDB with the row its PDB gives. It removes the mark when they agree and exits 4, -//! printing each difference, when they do not. +//! `chrome-builds find ` +//! makes a candidate row for a new build and exits 3 when the row needs a person's review. +//! `chrome-builds score ` +//! makes the row of a build that already has a verified row the same way, compares the two value +//! by value and writes the score of each feature. It exits 5 when a value it found is wrong. +//! `chrome-builds fingerprint ` adds the fingerprints of a row's +//! functions, read from its own module, so the next build's row can start from them. //! `chrome-builds pending ` //! prints the builds that have no row yet, most urgent first. //! `chrome-builds table-key` prints a new signing key pair. -//! `chrome-builds table-add ` puts a row into a table, with the -//! symbol key the next build's row will need. +//! `chrome-builds table-add ` puts a row into a table. //! `chrome-builds table-read ` writes out a table that verifies under //! `RIVET_TABLE_PUBLIC_KEY`. //! `chrome-builds table-merge ...` adds the rows of other tables to a table. @@ -30,35 +22,17 @@ use std::path::Path; use std::process::ExitCode; -use rivet_platform_windows::chrome_build::{self, ChromeBuild, PeFile}; -use rivet_platform_windows::row_port::{self, NewBuild}; +use rivet_platform_windows::chrome_build::{self, PeFile}; +use rivet_platform_windows::row_port::{self, PortReport}; use rivet_platform_windows::{row_watch, signed_table}; -/// How many bytes of `views::HWNDForView` the runtime compares before patching. -const PROLOGUE: usize = 15; - fn main() -> ExitCode { let arguments: Vec = std::env::args().skip(1).collect(); let result = match arguments.iter().map(String::as_str).collect::>().as_slice() { - ["pdb-key", module] => pdb_key(Path::new(module)), - ["names", pdb, needles @ ..] => names(Path::new(pdb), needles), - ["near", pdb, addresses @ ..] => near(Path::new(pdb), addresses), - ["extract", module, pdbs, browser, version, table] => extract( - Path::new(module), - Path::new(pdbs), - browser, - version, - Path::new(table), - "BrowserFrameViewWin", - ), - ["extract", module, pdbs, browser, version, table, class] => { - extract(Path::new(module), Path::new(pdbs), browser, version, Path::new(table), class) - } - ["port", prior, old_pdb, new_pdb, module, version, row, report] => { - return match port( + ["find", prior, prior_module, module, version, row, report] => { + return match find( Path::new(prior), - Path::new(old_pdb), - Path::new(new_pdb), + Path::new(prior_module), Path::new(module), version, Path::new(row), @@ -72,30 +46,16 @@ fn main() -> ExitCode { } } } - ["find", prior, old_pdb, old_module, module, version, channel, download, row, report] => { - return match find( + ["score", prior, prior_module, module, verified, out] => { + return match score( Path::new(prior), - Path::new(old_pdb), - old_module, + Path::new(prior_module), Path::new(module), - version, - channel, - download, - Path::new(row), - Path::new(report), + Path::new(verified), + Path::new(out), ) { Ok(true) => ExitCode::SUCCESS, - Ok(false) => ExitCode::from(3), - Err(error) => { - eprintln!("chrome-builds: {error}"); - ExitCode::FAILURE - } - } - } - ["pdb-check", table, browser, version, row] => { - return match pdb_check(Path::new(table), browser, version, Path::new(row)) { - Ok(true) => ExitCode::SUCCESS, - Ok(false) => ExitCode::from(4), + Ok(false) => ExitCode::from(5), Err(error) => { eprintln!("chrome-builds: {error}"); ExitCode::FAILURE @@ -114,7 +74,7 @@ fn main() -> ExitCode { println!("private {private}"); println!("public {public}"); }), - ["table-add", table, row, module] => table_add(Path::new(table), Path::new(row), Path::new(module)), + ["table-add", table, row] => table_add(Path::new(table), Path::new(row)), ["table-read", signed, out] => table_read(Path::new(signed), Path::new(out)), ["table-merge", table, parts @ ..] => table_merge(Path::new(table), parts), ["table-sign", table, signed] => table_sign(Path::new(table), Path::new(signed), None), @@ -124,7 +84,7 @@ fn main() -> ExitCode { ["table-withdraw", published, signed, builds @ ..] if !builds.is_empty() => { table_withdraw(Path::new(published), Path::new(signed), builds) } - _ => Err("usage: chrome-builds pdb-key | extract
[frame-class] | port | find | pdb-check | pending | gate [row.json] | fingerprint | release-sign ... | release-check | table-key | table-add | table-read | table-merge ... | table-sign [published-file] | table-withdraw ...".into()), + _ => Err("usage: chrome-builds find | score | pending | gate [row.json] | fingerprint | release-sign ... | release-check | table-key | table-add | table-read | table-merge ... | table-sign [published-file] | table-withdraw ...".into()), }; match result { Ok(()) => ExitCode::SUCCESS, @@ -135,246 +95,139 @@ fn main() -> ExitCode { } } -/// Prints the address and decorated name of every public symbol whose name holds one of the needles. -fn names(pdb: &Path, needles: &[&str]) -> Result<(), String> { - symbols::publics(pdb, &mut |address, name| { - if needles.iter().any(|needle| name.contains(needle)) { - println!("{address:08X} {name}"); - } - }) -} - -/// Prints, for each address in hex, the public symbol that starts at or just before it. -fn near(pdb: &Path, addresses: &[&str]) -> Result<(), String> { - let wanted: Vec = addresses - .iter() - .filter_map(|text| u32::from_str_radix(text.trim_start_matches("0x"), 16).ok()) - .collect(); - let mut best: Vec> = vec![None; wanted.len()]; - symbols::publics(pdb, &mut |address, name| { - for (slot, target) in wanted.iter().enumerate() { - if address <= *target && best[slot].as_ref().is_none_or(|(at, _)| address > *at) { - best[slot] = Some((address, name.to_owned())); - } - } - })?; - for (target, found) in wanted.iter().zip(best) { - match found { - Some((at, name)) => println!("{target:08X} is {:#x} past {at:08X} {name}", target - at), - None => println!("{target:08X} has no symbol before it"), - } - } - Ok(()) -} - fn read(path: &Path) -> Result, String> { std::fs::read(path).map_err(|error| format!("could not read {}: {error}", path.display())) } -fn port( - prior: &Path, - old_pdb: &Path, - new_pdb: &Path, +/// Makes the row of `version` from the prior row, the prior row's own module and the new module. +fn make( + prior: &serde_json::Value, + prior_module: &Path, module: &Path, version: &str, - row_path: &Path, - report_path: &Path, -) -> Result { - let prior: serde_json::Value = serde_json::from_slice(&read(prior)?) - .map_err(|error| format!("the prior row is not JSON: {error}"))?; - let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; - let mut old = Vec::new(); - symbols::publics(old_pdb, &mut |address, name| { - old.push((address, name.to_owned())) - })?; - old.sort(); - // The frame entry keeps plain numbers. - let mut targets = row_port::addresses_of(&prior["build"]); - for key in ["frame_view_vtable", "client_view_bounds", "hwnd_for_view"] { - targets.extend(prior["frame"][key].as_u64().map(|value| value as u32)); +) -> Result<(serde_json::Value, PortReport), String> { + let prior_bytes = read(prior_module)?; + let prior_pe = + PeFile::parse(&prior_bytes).ok_or("the prior module is not a 64-bit PE image")?; + // A module of another build would give fingerprints and class names of the wrong functions. + let start = prior["frame"]["hwnd_for_view"] + .as_u64() + .and_then(|address| u32::try_from(address).ok()); + let prologue = prior["frame"]["hwnd_for_view_prologue"] + .as_str() + .and_then(chrome_build::hex); + match (start, prologue) { + (Some(start), Some(prologue)) + if prior_pe.read(start, prologue.len()) == Some(prologue.as_slice()) => {} + _ => return Err("the prior module is not the build of the prior row".into()), } - let named = row_port::name_addresses(&targets, &old); - let wanted = row_port::wanted_names(&named); - drop(old); - let mut new = std::collections::HashMap::>::new(); - // `views::View::ConvertPointToScreen` is found by its own name, for a prior row without it. - let mut screen_origin = Vec::new(); - symbols::publics(new_pdb, &mut |address, name| { - if row_port::is_screen_origin_name(name) { - screen_origin.push(address); - } - let name = row_port::stable_name(name); - if wanted.contains(name) { - new.entry(name.to_owned()).or_default().push(address); + // The fingerprints the prior row stored were read from this module when the row was made. + // A row stored without them gets them from the module now. + let prints = match prior["fingerprints"].as_object() { + Some(stored) => stored.clone(), + None => { + let (prints, missing) = row_port::fingerprints_of(prior, &prior_pe); + if !missing.is_empty() { + println!( + "the prior build gives no fingerprint for {}", + missing.join(", ") + ); + } + prints } - })?; - let unnamed = row_port::unnamed_code(&prior, &named, &pe); - let names = symbols::private_names(old_pdb, &unnamed)?; - let places = symbols::private_places(new_pdb, &names.values().cloned().collect::>())?; - let private = names - .iter() - .filter_map( - |(address, name)| match places.get(name).map(Vec::as_slice) { - Some([place]) => Some((*address, *place)), - _ => None, - }, - ) - .collect(); - let (mut row, mut report) = row_port::port_row( - &prior, - &named, - &NewBuild { - version, - pe: &pe, - symbols: &new, - private: &private, - }, - ); - row_port::seed_screen_origin(&mut row, &screen_origin, &pe, &mut report); - report.review.extend(row_port::hand_only_review(&prior)); - let text = |value: &dyn erased::Json| value.pretty(); - std::fs::write(row_path, text(&row)).map_err(|error| error.to_string())?; - std::fs::write(report_path, text(&report)).map_err(|error| error.to_string())?; + }; + // Each class table of the prior row is found again by its views class's name too. + let classes = row_port::prior_classes(prior, &prior_pe); + let bytes = read(module)?; + let pe = PeFile::parse(&bytes).ok_or("the new module is not a 64-bit PE image")?; + let (mut row, mut report) = + row_port::find_candidate(prior, &prints, Some(&prior_pe), &classes, version, &pe); + row_port::leave_out_screen_origin(&mut row, &mut report); + report.review.extend(row_port::hand_only_review(prior)); println!( - "{} {}: {} of {} addresses, {} for review", - report.browser, - report.version, - report.mapped, - report.addresses, - report.review.len() + "exception tables: {} function starts in the prior build, {} in the new one; {} class tables named", + prior_pe.function_starts().len(), + pe.function_starts().len(), + classes.len() ); - Ok(report.review.is_empty()) + Ok((row, report)) } -/// Makes a candidate row for a build with no published PDB from the prior row's fingerprints. The -/// prior PDB names each prior address, so a person sees which function a review line is about. -#[allow(clippy::too_many_arguments)] +/// Makes a candidate row for a new build. True when nothing needs a person's review. fn find( prior_path: &Path, - old_pdb: &Path, - old_module: &str, + prior_module: &Path, module: &Path, version: &str, - channel: &str, - download: &str, row_path: &Path, report_path: &Path, ) -> Result { let prior = json_file(prior_path)?; - let stored = prior["fingerprints"].as_object(); - let prior_bytes = match old_module { - "-" => None, - path => Some(read(Path::new(path))?), - }; - let prior_pe = match &prior_bytes { - Some(bytes) => { - Some(PeFile::parse(bytes).ok_or("the prior module is not a 64-bit PE image")?) - } - None => None, - }; - let prints = match (stored, &prior_pe) { - (Some(stored), None) => stored.clone(), - (None, None) => { - return Err("the prior row has no fingerprints, and no prior module was given to read them from".into()); - } - (_, Some(pe)) => { - // Fingerprints read from another build would find the wrong functions. - let start = prior["frame"]["hwnd_for_view"] - .as_u64() - .and_then(|address| u32::try_from(address).ok()); - let prologue = prior["frame"]["hwnd_for_view_prologue"] - .as_str() - .and_then(chrome_build::hex); - match (start, prologue) { - (Some(start), Some(prologue)) - if pe.read(start, prologue.len()) == Some(prologue.as_slice()) => {} - _ => return Err("the prior module is not the build of the prior row".into()), - } - match stored { - Some(stored) => stored.clone(), - None => { - let (prints, missing) = row_port::fingerprints_of(&prior, pe); - if !missing.is_empty() { - println!( - "the prior build gives no fingerprint for {}", - missing.join(", ") - ); - } - prints - } - } - } - }; - // A fingerprint taken at a function start counts only function starts of the new build, and - // what fingerprints leave open is looked for by reading the prior build next to the new one. - let prior_starts = prior_pe - .as_ref() - .map(PeFile::function_starts) - .unwrap_or_default(); - let mut old = Vec::new(); - symbols::publics(old_pdb, &mut |address, name| { - old.push((address, name.to_owned())) - })?; - old.sort(); - let mut targets = row_port::addresses_of(&prior["build"]); - for key in ["frame_view_vtable", "client_view_bounds", "hwnd_for_view"] { - targets.extend(prior["frame"][key].as_u64().map(|value| value as u32)); - } - let named = row_port::name_addresses(&targets, &old); - drop(old); - let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; - // A class table of a views class is also found again by the class name its symbol gives. - let classes = row_port::class_names(&named); - let (mut row, mut report) = - row_port::find_candidate(&prior, &prints, prior_pe.as_ref(), &classes, version, &pe); - // No symbols name `screen_origin` here: a prior row without it gives a row without it. - row_port::seed_screen_origin(&mut row, &[], &pe, &mut report); - report.review.extend(row_port::hand_only_review(&prior)); - row_port::name_review_lines(&mut report.review, &named); - let key = pe - .pdb_key() - .ok_or("the new module has no CodeView record")?; - row_port::mark_without_pdb(&mut row, &key, &report.prior_version, channel, download); + let (row, report) = make(&prior, prior_module, module, version)?; let text = |value: &dyn erased::Json| value.pretty(); std::fs::write(row_path, text(&row)).map_err(|error| error.to_string())?; std::fs::write(report_path, text(&report)).map_err(|error| error.to_string())?; println!( - "exception tables: {} function starts in the prior build, {} in the new one", - prior_starts.len(), - pe.function_starts().len() - ); - println!( - "{} {} without its PDB: {} of {} addresses found by fingerprint, {} settled by two methods, {} values read, {} carried, {} for review", + "{} {} from {}: {} of {} addresses found by fingerprint, {} settled by two methods, {} values read, {} carried, {} features off, {} for review", report.browser, report.version, + report.prior_version, report.fingerprinted.len(), report.addresses, report.settled.len(), report.derived.len(), report.carried.len(), + report.switched_off.len(), report.review.len() ); Ok(report.review.is_empty()) } -/// Compares a row made without its PDB with the row the PDB gives, and removes the mark when they -/// agree. -fn pdb_check(table_path: &Path, browser: &str, version: &str, row: &Path) -> Result { - let mut table = json_file(table_path)?; - let from_pdb = json_file(row)?; - let differences = row_port::check_against_pdb(&mut table, browser, version, &from_pdb)?; - for line in &differences { - println!("{line}"); +/// Makes the row of a build that already has a verified row, and scores it against that row. +/// True when no value it found is wrong. Nothing is written but the score. +fn score( + prior_path: &Path, + prior_module: &Path, + module: &Path, + verified_path: &Path, + out: &Path, +) -> Result { + let prior = json_file(prior_path)?; + let verified = json_file(verified_path)?; + let version = verified["frame"]["version"] + .as_str() + .ok_or("the verified row has no frame version")? + .to_owned(); + let (row, report) = make(&prior, prior_module, module, &version)?; + let score = row_port::score_row(&row, &report, &verified); + std::fs::write( + out, + serde_json::to_string_pretty(&score).map_err(|error| error.to_string())? + "\n", + ) + .map_err(|error| error.to_string())?; + println!( + "{} {} from {}:", + score.browser, score.version, score.prior_version + ); + for (feature, each) in &score.features { + let state = if each.off { "off" } else { "on" }; + println!( + " {feature}: {state}, {} equal, {} different, {} not held", + each.equal, + each.different.len(), + each.not_held.len() + ); + for line in &each.different { + println!(" wrong: {line}"); + } } - if !differences.is_empty() { - return Ok(false); + if !score.review.is_empty() { + println!( + " the row would stop for review: {}", + score.review.join("; ") + ); } - let text = serde_json::to_string_pretty(&table).map_err(|error| error.to_string())? + "\n"; - std::fs::write(table_path, text).map_err(|error| error.to_string())?; - println!("{browser} {version}: the row made from fingerprints agrees with its PDB"); - Ok(true) + Ok(score.wrong() == 0) } mod erased { @@ -417,18 +270,9 @@ fn pending( Ok(()) } -fn table_add(table_path: &Path, row: &Path, module: &Path) -> Result<(), String> { +fn table_add(table_path: &Path, row: &Path) -> Result<(), String> { let row = json_file(row)?; let mut table = json_file(table_path)?; - let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; - let key = pe.pdb_key().ok_or("the image has no CodeView record")?; - let name = format!( - "{} {}", - row["frame"]["browser"].as_str().unwrap_or_default(), - row["frame"]["version"].as_str().unwrap_or_default() - ); - table["symbols"][name] = key.into(); signed_table::upsert_row(&mut table, row)?; let text = serde_json::to_string_pretty(&table).map_err(|error| error.to_string())? + "\n"; std::fs::write(table_path, text).map_err(|error| error.to_string()) @@ -513,373 +357,6 @@ fn table_withdraw(published: &Path, signed: &Path, builds: &[&str]) -> Result<() Ok(()) } -fn pdb_key(module: &Path) -> Result<(), String> { - let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; - let key = pe.pdb_key().ok_or("the image has no CodeView record")?; - let pdb = format!( - "{}.pdb", - module - .file_name() - .and_then(|name| name.to_str()) - .ok_or("bad module name")? - ); - println!("{pdb}/{key}/{pdb}"); - Ok(()) -} - -fn extract( - module: &Path, - pdbs: &Path, - browser: &str, - version: &str, - table_path: &Path, - frame_class: &str, -) -> Result<(), String> { - let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("not a 64-bit PE image")?; - let symbols = symbols::Session::open(module, pdbs)?; - // The function is declared on `BrowserFrameViewWin` whichever subclass builds the windows. - let client_view_bounds = symbols.address("BrowserFrameViewWin::GetBoundsForClientView")?; - let hwnd_for_view = symbols.address("views::HWNDForView")?; - // The class has several vtables because of multiple inheritance. Exactly one of them holds - // the client-view bounds function. - let (frame_view_vtable, client_view_slot) = symbols - .vtables(frame_class)? - .into_iter() - .find_map(|vtable| Some((vtable, pe.vtable_slot(vtable, client_view_bounds)?))) - .ok_or("no vtable of the frame class holds GetBoundsForClientView")?; - let prologue = pe - .read(hwnd_for_view, PROLOGUE) - .ok_or("views::HWNDForView is outside the image")?; - let build = ChromeBuild { - browser: browser.into(), - version: version.into(), - module: module - .file_name() - .and_then(|name| name.to_str()) - .ok_or("bad module name")? - .into(), - frame_view_vtable, - client_view_slot, - client_view_bounds, - hwnd_for_view, - hwnd_for_view_prologue: prologue.iter().map(|byte| format!("{byte:02x}")).collect(), - }; - let text = std::fs::read_to_string(table_path).unwrap_or_else(|_| "[]".into()); - let mut table = chrome_build::builds(&text); - chrome_build::upsert(&mut table, build.clone()); - let text = serde_json::to_string_pretty(&table).map_err(|error| error.to_string())? + "\n"; - std::fs::write(table_path, text) - .map_err(|error| format!("could not write {}: {error}", table_path.display()))?; - println!( - "{}", - serde_json::to_string(&build).map_err(|error| error.to_string())? - ); - Ok(()) -} - -#[cfg(windows)] -mod symbols { - use std::collections::{BTreeMap, HashMap}; - use std::os::windows::ffi::OsStrExt; - use std::path::Path; - - use windows_sys::Win32::System::Diagnostics::Debug::{ - SymCleanup, SymEnumSymbolsW, SymFromAddrW, SymFromNameW, SymInitializeW, SymLoadModuleExW, - SymSetOptions, SYMBOL_INFOW, SYMOPT_UNDNAME, - }; - use windows_sys::Win32::System::Threading::GetCurrentProcess; - - /// The base the module is loaded at for symbol lookups. Results are reported as RVAs. - const BASE: u64 = 0x1_8000_0000; - /// Accept a PDB whose age differs from the image, which Google's symbol server serves. - const SYMOPT_LOAD_ANYTHING: u32 = 0x40; - - fn wide(path: &Path) -> Vec { - path.as_os_str().encode_wide().chain(Some(0)).collect() - } - - /// Where a PDB opened on its own is placed: wide enough for every browser's module. - const IMAGE_SIZE: u32 = 0x2000_0000; - /// Reads only the linker's public names, which are decorated and stable between builds. - const SYMOPT_PUBLICS_ONLY: u32 = 0x4000; - - /// Visits every public symbol of a PDB, with its address in the module and its decorated name. - pub fn publics(pdb: &Path, visit: &mut dyn FnMut(u32, &str)) -> Result<(), String> { - unsafe extern "system" fn each( - info: *const SYMBOL_INFOW, - _size: u32, - context: *const core::ffi::c_void, - ) -> i32 { - let info = &*info; - let visit = &mut *(context as *mut &mut dyn FnMut(u32, &str)); - let name = std::slice::from_raw_parts(info.Name.as_ptr(), info.NameLen as usize); - if let Ok(address) = u32::try_from(info.Address - BASE) { - visit(address, &String::from_utf16_lossy(name)); - } - 1 - } - unsafe { - SymSetOptions(SYMOPT_LOAD_ANYTHING | SYMOPT_PUBLICS_ONLY); - if SymInitializeW(GetCurrentProcess(), std::ptr::null(), 0) == 0 { - return Err("DbgHelp could not start".into()); - } - let base = SymLoadModuleExW( - GetCurrentProcess(), - std::ptr::null_mut(), - wide(pdb).as_ptr(), - std::ptr::null(), - BASE, - IMAGE_SIZE, - std::ptr::null(), - 0, - ); - if base == 0 { - SymCleanup(GetCurrentProcess()); - return Err(format!("DbgHelp could not load {}", pdb.display())); - } - let mask: Vec = "*".encode_utf16().chain(Some(0)).collect(); - let mut visit = visit; - let done = SymEnumSymbolsW( - GetCurrentProcess(), - BASE, - mask.as_ptr(), - Some(each), - (&raw mut visit).cast(), - ); - SymCleanup(GetCurrentProcess()); - if done == 0 { - return Err(format!("DbgHelp could not list {}", pdb.display())); - } - } - Ok(()) - } - - fn load_all(pdb: &Path) -> Result<(), String> { - unsafe { - SymSetOptions(SYMOPT_LOAD_ANYTHING | SYMOPT_UNDNAME); - if SymInitializeW(GetCurrentProcess(), std::ptr::null(), 0) == 0 { - return Err("DbgHelp could not start".into()); - } - let base = SymLoadModuleExW( - GetCurrentProcess(), - std::ptr::null_mut(), - wide(pdb).as_ptr(), - std::ptr::null(), - BASE, - IMAGE_SIZE, - std::ptr::null(), - 0, - ); - if base == 0 { - SymCleanup(GetCurrentProcess()); - return Err(format!("DbgHelp could not load {}", pdb.display())); - } - } - Ok(()) - } - - /// The function that starts at each address, from the PDB's private symbols. - pub fn private_names(pdb: &Path, addresses: &[u32]) -> Result, String> { - load_all(pdb)?; - let mut names = BTreeMap::new(); - for address in addresses { - unsafe { - // SYMBOL_INFOW ends in the name, whose room the caller provides. - let mut storage = vec![0u64; (std::mem::size_of::() + 2048) / 8]; - let info = storage.as_mut_ptr().cast::(); - (*info).SizeOfStruct = std::mem::size_of::() as u32; - (*info).MaxNameLen = 1000; - let mut distance = 0u64; - if SymFromAddrW( - GetCurrentProcess(), - BASE + u64::from(*address), - &mut distance, - info, - ) != 0 - && distance == 0 - { - let name = - std::slice::from_raw_parts((*info).Name.as_ptr(), (*info).NameLen as usize); - names.insert( - *address, - String::from_utf16_lossy(name) - .trim_end_matches(['\0', ' ']) - .to_owned(), - ); - } - } - } - unsafe { SymCleanup(GetCurrentProcess()) }; - Ok(names) - } - - /// Where each function name lies, from the PDB's private symbols. - pub fn private_places( - pdb: &Path, - names: &[String], - ) -> Result>, String> { - unsafe extern "system" fn each( - info: *const SYMBOL_INFOW, - _size: u32, - context: *const core::ffi::c_void, - ) -> i32 { - let info = &*info; - let found = &mut *(context as *mut Vec<(String, u32)>); - let name = std::slice::from_raw_parts(info.Name.as_ptr(), info.NameLen as usize); - if let Ok(address) = u32::try_from(info.Address - BASE) { - found.push((String::from_utf16_lossy(name), address)); - } - 1 - } - load_all(pdb)?; - let mut places: HashMap> = HashMap::new(); - for name in names { - let mask: Vec = name.encode_utf16().chain(Some(0)).collect(); - let mut found: Vec<(String, u32)> = Vec::new(); - unsafe { - SymEnumSymbolsW( - GetCurrentProcess(), - BASE, - mask.as_ptr(), - Some(each), - (&raw mut found).cast(), - ); - } - let mut exact: Vec = found - .into_iter() - .filter(|(other, _)| other.trim_end_matches(['\0', ' ']) == name) - .map(|(_, place)| place) - .collect(); - exact.sort_unstable(); - exact.dedup(); - places.insert(name.clone(), exact); - } - unsafe { SymCleanup(GetCurrentProcess()) }; - Ok(places) - } - - pub struct Session; - - impl Session { - pub fn open(module: &Path, pdbs: &Path) -> Result { - unsafe { - SymSetOptions(SYMOPT_UNDNAME | SYMOPT_LOAD_ANYTHING); - if SymInitializeW(GetCurrentProcess(), wide(pdbs).as_ptr(), 0) == 0 { - return Err("DbgHelp could not start".into()); - } - let base = SymLoadModuleExW( - GetCurrentProcess(), - std::ptr::null_mut(), - wide(module).as_ptr(), - std::ptr::null(), - BASE, - 0, - std::ptr::null(), - 0, - ); - if base == 0 { - return Err("DbgHelp could not load the module's symbols".into()); - } - } - Ok(Self) - } - - pub fn address(&self, name: &str) -> Result { - let name_wide: Vec = name.encode_utf16().chain(Some(0)).collect(); - unsafe { - let mut info: SYMBOL_INFOW = std::mem::zeroed(); - info.SizeOfStruct = std::mem::size_of::() as u32; - if SymFromNameW(GetCurrentProcess(), name_wide.as_ptr(), &mut info) == 0 { - return Err(format!("the symbols have no {name}")); - } - u32::try_from(info.Address - BASE).map_err(|_| format!("{name} is out of range")) - } - } - - pub fn vtables(&self, class: &str) -> Result, String> { - unsafe extern "system" fn visit( - info: *const SYMBOL_INFOW, - _size: u32, - context: *const core::ffi::c_void, - ) -> i32 { - let info = &*info; - let found = &mut *(context as *mut Vec<(String, u64)>); - let name = std::slice::from_raw_parts(info.Name.as_ptr(), info.NameLen as usize); - found.push((String::from_utf16_lossy(name), info.Address)); - 1 - } - let mask: Vec = format!("{class}::*") - .encode_utf16() - .chain(Some(0)) - .collect(); - let mut found: Vec<(String, u64)> = Vec::new(); - unsafe { - SymEnumSymbolsW( - GetCurrentProcess(), - BASE, - mask.as_ptr(), - Some(visit), - &mut found as *mut _ as *const _, - ); - } - let vtables: Vec = found - .into_iter() - .filter(|(name, _)| { - name.trim_end_matches(['\0', ' ']) == format!("{class}::`vftable'") - }) - .filter_map(|(_, address)| u32::try_from(address - BASE).ok()) - .collect(); - if vtables.is_empty() { - return Err(format!("the symbols have no {class} vtable")); - } - Ok(vtables) - } - } - - impl Drop for Session { - fn drop(&mut self) { - unsafe { SymCleanup(GetCurrentProcess()) }; - } - } -} - -#[cfg(not(windows))] -mod symbols { - use std::path::Path; - - pub fn publics(_pdb: &Path, _visit: &mut dyn FnMut(u32, &str)) -> Result<(), String> { - Err("symbol extraction needs Windows DbgHelp".into()) - } - pub fn private_names( - _pdb: &Path, - _addresses: &[u32], - ) -> Result, String> { - Err("symbol extraction needs Windows DbgHelp".into()) - } - pub fn private_places( - _pdb: &Path, - _names: &[String], - ) -> Result>, String> { - Err("symbol extraction needs Windows DbgHelp".into()) - } - - pub struct Session; - - impl Session { - pub fn open(_module: &Path, _pdbs: &Path) -> Result { - Err("symbol extraction needs Windows DbgHelp".into()) - } - pub fn address(&self, _name: &str) -> Result { - unreachable!() - } - pub fn vtables(&self, _class: &str) -> Result, String> { - unreachable!() - } - } -} - /// Refuses a browser that did not pass every feature check, so it is never listed as supported. /// The row is the one being published: a check of a feature it turns off is not required. fn gate(results: &Path, browser: &str, row: Option<&Path>) -> Result<(), String> { diff --git a/rivet/platform/windows/src/chrome_build.rs b/rivet/platform/windows/src/chrome_build.rs index 7328df3..5805740 100644 --- a/rivet/platform/windows/src/chrome_build.rs +++ b/rivet/platform/windows/src/chrome_build.rs @@ -2,9 +2,8 @@ //! new ones. //! //! Each entry records where one build keeps the frame view's client-view bounds function. The -//! runtime only patches a loaded module that matches an entry exactly. The `chrome-builds` tool -//! fills entries from Google's public symbols, so a new browser release needs a data change, not -//! a code change. +//! runtime only patches a loaded module that matches an entry exactly, so a new browser release +//! needs a data change, not a code change. use serde::{Deserialize, Serialize}; @@ -61,13 +60,12 @@ pub fn hex(value: &str) -> Option> { .collect() } -/// A PE image read from a file, with enough structure to map RVAs and find its debug record. +/// A PE image read from a file, with enough structure to map RVAs and find its functions. pub struct PeFile<'a> { bytes: &'a [u8], image_base: u64, sections: Vec<(u32, u32, u32)>, code_sections: Vec<(u32, u32)>, - debug_directory: (u32, u32), exception_directory: (u32, u32), } @@ -103,11 +101,6 @@ impl<'a> PeFile<'a> { return None; } let image_base = u64_at(bytes, optional + 24)?; - // Data directory 6 is the debug directory. - let debug_directory = ( - u32_at(bytes, optional + 112 + 48)?, - u32_at(bytes, optional + 116 + 48)?, - ); // Data directory 3 is the exception table, which lists where functions start. let exception_directory = ( u32_at(bytes, optional + 112 + 24)?, @@ -142,7 +135,6 @@ impl<'a> PeFile<'a> { image_base, sections, code_sections, - debug_directory, exception_directory, }) } @@ -191,32 +183,6 @@ impl<'a> PeFile<'a> { u32::try_from(value.checked_sub(self.image_base)?).ok() } - /// The symbol-server key of the image's PDB: GUID and age from its CodeView record. - pub fn pdb_key(&self) -> Option { - let (directory, size) = self.debug_directory; - for index in 0..size / 28 { - let entry = self.offset(directory + index * 28)?; - // Type 2 is CodeView. - if u32_at(self.bytes, entry + 12)? != 2 { - continue; - } - let record = u32_at(self.bytes, entry + 24)? as usize; - if self.bytes.get(record..record + 4)? != b"RSDS" { - return None; - } - let guid = self.bytes.get(record + 4..record + 20)?; - let age = u32_at(self.bytes, record + 20)?; - let tail: String = guid[8..].iter().map(|byte| format!("{byte:02X}")).collect(); - return Some(format!( - "{:08X}{:04X}{:04X}{tail}{age:X}", - u32_at(guid, 0)?, - u16_at(guid, 4)?, - u16_at(guid, 6)?, - )); - } - None - } - /// The start of every function the exception table lists. A function that needs no unwind /// data, such as a leaf that touches no stack, is not listed. pub fn function_starts(&self) -> std::collections::BTreeSet { @@ -288,23 +254,6 @@ mod tests { bytes } - #[test] - fn nfr3_reads_the_symbol_server_key_of_an_image() { - let mut section = vec![0u8; 0x100]; - section[12..16].copy_from_slice(&2u32.to_le_bytes()); - section[24..28].copy_from_slice(&0x240u32.to_le_bytes()); - section[0x40..0x44].copy_from_slice(b"RSDS"); - let guid = [ - 0x51, 0x19, 0x13, 0x7b, 0xa2, 0x33, 0x0f, 0x9e, 0x4c, 0x4c, 0x44, 0x20, 0x50, 0x44, - 0x42, 0x2e, - ]; - section[0x44..0x54].copy_from_slice(&guid); - section[0x54..0x58].copy_from_slice(&1u32.to_le_bytes()); - let bytes = image(§ion); - let pe = PeFile::parse(&bytes).unwrap(); - assert_eq!(pe.pdb_key().unwrap(), "7B13195133A29E0F4C4C44205044422E1"); - } - #[test] fn nfr3_finds_a_function_in_a_vtable() { let mut section = vec![0u8; 0x100]; diff --git a/rivet/platform/windows/src/row_class.rs b/rivet/platform/windows/src/row_class.rs index 6a0112a..c696e40 100644 --- a/rivet/platform/windows/src/row_class.rs +++ b/rivet/platform/windows/src/row_class.rs @@ -366,13 +366,170 @@ pub fn class_tables(pe: &PeFile, name: &str) -> BTreeSet { found } -/// The class a public table symbol names, as `??_7EdgeBrowserFrameViewWin@@6BLayerDelegate@ui@@@` -/// names `EdgeBrowserFrameViewWin`. The class name its metadata holds has no namespace. -pub fn class_of_table_symbol(symbol: &str) -> Option<&str> { - let rest = symbol.strip_prefix("??_7")?; - let name = rest.split('@').next()?; - (!name.is_empty() && name.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')) - .then_some(name) +/// How many levels of callees below the code that fills the metadata are read for its name. +const CALLEE_DEPTH: usize = 2; +/// How many names may be tried for one table before it counts as too unclear to name. +const NAMES_MOST: usize = 16; +/// How long a class name may be. +const NAME_MOST: usize = 120; + +/// The zero-terminated text at `rva` when it reads as a C++ class name without its namespace. +fn identifier_at(pe: &PeFile, rva: u32) -> Option { + let bytes = [NAME_MOST + 1, 64, 32, 16, 8] + .into_iter() + .find_map(|length| pe.read(rva, length))?; + let end = bytes.iter().position(|byte| *byte == 0)?; + let name = &bytes[..end]; + let first = *name.first()?; + (name.len() >= 2 + && (first.is_ascii_alphabetic() || first == b'_') + && name + .iter() + .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')) + .then(|| String::from_utf8_lossy(name).into_owned()) +} + +/// What a function's body loads with a RIP-relative `lea` outside the code, and the functions it +/// calls or jumps to directly. +fn body_of(pe: &PeFile, ranges: &BTreeMap, start: u32) -> (Vec, Vec) { + let end = ranges.get(&start).copied().unwrap_or(start); + let length = end.saturating_sub(start).min(BODY_MOST) as usize; + let Some(bytes) = pe.read(start, length) else { + return (vec![], vec![]); + }; + let (mut loads, mut callees) = (Vec::new(), Vec::new()); + let mut at = 0; + while at < bytes.len() { + let Some(instruction) = x64::decode_body(&bytes[at..]) else { + break; + }; + if instruction.length == 0 || at + instruction.length > bytes.len() { + break; + } + let raw = &bytes[at..at + instruction.length]; + let rva = start + at as u32; + if let Some(found) = (raw.len() == 7).then(|| rip_use(raw, rva)).flatten() { + if !found.word && !pe.is_code(found.target) { + loads.push(found.target); + } + } + if raw.len() == 5 && matches!(raw[0], 0xE8 | 0xE9) { + let rel = i32::from_le_bytes(raw[1..5].try_into().expect("five bytes")); + if let Ok(target) = u32::try_from(i64::from(rva) + 5 + i64::from(rel)) { + if ranges.contains_key(&target) { + callees.push(target); + } + } + } + at += instruction.length; + } + (loads, callees) +} + +/// The metadata statics a class table's objects reach: each constructor that writes the table at +/// the start of an object also writes other tables into it, and the second slot of the +/// `ui::metadata::MetaDataProvider` table among them returns the class's static, as `getters` reads. +fn statics_of_table(pe: &PeFile, ranges: &BTreeMap, table: u32) -> BTreeSet<(u32, bool)> { + let writers: BTreeSet = rip_uses(pe, &BTreeSet::from([table])) + .iter() + .filter(|each| !each.word) + .filter_map(|each| enclosing(ranges, each.at)) + .collect(); + let mut found = BTreeSet::new(); + for writer in writers { + let stores = stores_in(pe, writer, ranges[&writer]); + for first in stores + .iter() + .filter(|store| store.table == table && store.offset == 0) + { + for other in stores.iter().filter(|store| { + store.base == first.base && store.offset != 0 && store.table != table + }) { + let Some(getter) = pe.pointer_rva(other.table + 8).filter(|at| pe.is_code(*at)) + else { + continue; + }; + if let Some(each) = load_target(pe, getter).filter(|(at, _)| !pe.is_code(*at)) { + found.insert(each); + } + } + } + } + found +} + +/// The names the code that fills a metadata static loads, nearest first: the texts that the +/// functions whose result is the static, and their callees, load. Only those that read as a class +/// name are kept. +fn names_of_static( + pe: &PeFile, + ranges: &BTreeMap, + found: (u32, bool), +) -> Vec> { + let mut layer: BTreeSet = rip_uses(pe, &BTreeSet::from([found.0])) + .iter() + .filter_map(|each| enclosing(ranges, each.at)) + .filter(|function| load_target(pe, *function) == Some(found)) + .collect(); + let mut seen = layer.clone(); + let mut by_depth = Vec::new(); + for _ in 0..=CALLEE_DEPTH { + if layer.is_empty() || seen.len() > CALLERS_MOST { + break; + } + let mut names = Vec::new(); + let mut next = BTreeSet::new(); + for function in &layer { + let (loads, callees) = body_of(pe, ranges, *function); + names.extend(loads.into_iter().filter_map(|at| identifier_at(pe, at))); + next.extend(callees.into_iter().filter(|callee| !seen.contains(callee))); + } + by_depth.push(names); + seen.extend(&next); + layer = next; + } + by_depth +} + +/// The views class a class table belongs to, by the class name its `ui::metadata` holds, read back +/// from the build: the metadata static the table's objects reach, and the names the code that fills +/// it loads. A name counts only where `class_tables` gives exactly this table for it, so a name +/// that is not the class's own gives none. The nearest code that yields exactly one such name +/// names the table; none, or two, gives no name. +pub fn class_name_of_table(pe: &PeFile, table: u32) -> Option { + let ranges = pe.function_ranges(); + let mut by_depth: Vec> = Vec::new(); + for each in statics_of_table(pe, &ranges, table) { + for (depth, names) in names_of_static(pe, &ranges, each).into_iter().enumerate() { + if by_depth.len() <= depth { + by_depth.resize(depth + 1, Vec::new()); + } + by_depth[depth].extend(names); + } + } + let mut tried = BTreeSet::new(); + for names in by_depth { + let mut confirmed = BTreeSet::new(); + for name in names { + if tried.len() >= NAMES_MOST { + return None; + } + if tried.insert(name.clone()) && class_tables(pe, &name) == BTreeSet::from([table]) { + confirmed.insert(name); + } + } + match confirmed.len() { + 0 => continue, + 1 => return confirmed.into_iter().next(), + _ => return None, + } + } + None +} + +/// Whether `name` is the class name of `table` in `pe`: `class_tables` gives this table alone. +pub fn names_table(pe: &PeFile, name: &str, table: u32) -> bool { + class_tables(pe, name) == BTreeSet::from([table]) } #[cfg(test)] @@ -518,15 +675,33 @@ mod tests { } #[test] - fn nfr6_a_table_symbol_names_its_class() { + fn nfr6_a_class_name_is_read_from_the_prior_build_without_symbols() { + let bytes = class_module("EdgeBrowserFrameViewWin"); + let pe = PeFile::parse(&bytes).unwrap(); + // The table the constructor writes at the object's start is named by the text its + // metadata code loads, and the name gives that table back. assert_eq!( - class_of_table_symbol("??_7EdgeBrowserFrameViewWin@@6BLayerDelegate@ui@@@"), + class_name_of_table(&pe, 0x2400).as_deref(), Some("EdgeBrowserFrameViewWin") ); - assert_eq!( - class_of_table_symbol("??_7VerticalTabStripStateControllerImpl@tabs@@6B@"), - Some("VerticalTabStripStateControllerImpl") - ); - assert_eq!(class_of_table_symbol("?Layout@BrowserView@@UEAAXXZ"), None); + assert!(names_table(&pe, "EdgeBrowserFrameViewWin", 0x2400)); + // The provider table is written further into the object, so it names no class. + assert_eq!(class_name_of_table(&pe, 0x2200), None); + assert!(!names_table(&pe, "EdgeBrowserFrameViewWin", 0x2200)); + // A name the metadata code does not load does not name the table. + assert!(!names_table(&pe, "BrowserFrameViewWin", 0x2400)); + } + + #[test] + fn nfr6_a_class_name_is_a_plain_identifier() { + let mut code = class_module("BrowserView"); + let at = 0x400 + 0x1000 + 0x100; + assert_eq!(&code[at..at + 12], b"BrowserView\0"); + let pe = PeFile::parse(&code).unwrap(); + assert_eq!(identifier_at(&pe, 0x2100).as_deref(), Some("BrowserView")); + // A path or a qualified name is not a class name. + code[at + 7] = b':'; + let pe = PeFile::parse(&code).unwrap(); + assert_eq!(identifier_at(&pe, 0x2100), None); } } diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index c574c68..f656976 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -1,19 +1,20 @@ //! Makes the supported-build row of a new browser build from the row of a prior build. //! //! Chromium's source changes little between two builds of a milestone, but every address moves. -//! So each address of the prior row is named through the prior build's public symbols, the same -//! decorated names are looked up in the new build's symbols, and the instruction bytes that guard -//! each hook are read again from the new module. Values that are not addresses (member offsets, +//! Each address of the prior row is found again in the new module by its fingerprint, the first +//! instructions of the function without their displacements, or by a slot of a class table that +//! holds such a function. What a fingerprint does not pin down is settled by `row_resolve`, which +//! takes a place only where two independent methods agree. The instruction bytes that guard each +//! hook are then read again from the new module. Values that are not addresses (member offsets, //! table slots, object sizes) are read again from the new module where `row_recipe` has a recipe -//! for them, and a recipe that fails stops the row. The rest are carried over. They have no public -//! symbols, so a row that crosses a milestone lists each of them and is never published without a -//! person's review, and every row must still pass on the real browser. +//! for them, or from the instructions that use them. No browser's debug symbols are read: the +//! verified prior row, its fingerprints and the two modules are all the generator has. //! //! A row is plain data here, in the form the runtime writes: a `usize` is a `0x` string, and bytes -//! are bare hex. A value this code cannot explain stops the row: it goes to review rather than to -//! people's browsers, and the runtime's own prologue checks stand behind that. +//! are bare hex. A value this code cannot explain stops the row or turns its feature off: it never +//! reaches people's browsers, and the runtime's own prologue checks stand behind that. -use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use serde::Serialize; use serde_json::{json, Value}; @@ -25,22 +26,6 @@ use crate::row_resolve; const LOWEST_ADDRESS: u64 = 0x10_0000; /// The address a build records for what it does not have. const ABSENT: u64 = 0x7FFF_0000; -/// How far below an address its naming symbol may lie: a table slot or an instruction in a function. -const NEAREST_SYMBOL: u32 = 0x2000; - -/// One symbol: its address in the module and its decorated name. -pub type Symbol = (u32, String); - -/// Removes what the linker adds to a decorated name, which differs from build to build. -pub fn stable_name(name: &str) -> &str { - let name = name.trim_end_matches('\0'); - let name = match name.strip_prefix(".weak.") { - Some(rest) => rest.split(".default.").next().unwrap_or(rest), - None => name, - }; - name.split(".llvm.").next().unwrap_or(name) -} - /// What the generator found, for the person or job that decides what to do with the row. #[derive(Debug, Default, Serialize)] pub struct PortReport { @@ -53,10 +38,6 @@ pub struct PortReport { pub review: Vec, /// Addresses with several possible new places, settled by an independent check. pub settled: Vec, - /// Addresses inside a symbol rather than at its start, moved by the same distance. - pub interior: Vec, - /// Addresses found through private symbols, since no public one covers them. - pub private: Vec, pub bytes_changed: Vec, pub slots_moved: Vec, /// Values that are not addresses, read again from the new module by their recipes. @@ -65,8 +46,6 @@ pub struct PortReport { pub carried: Vec, /// Optional parts the new build could not supply. The runtime does without them. pub left_out: Vec, - /// The new build had no symbols, so every address was looked for by the prior row's fingerprints. - pub made_without_pdb: bool, /// Addresses a fingerprint found in exactly one place of the new build. pub fingerprinted: Vec, /// Values that are Rivet's settings rather than facts about the build, kept from the prior row. @@ -140,56 +119,6 @@ pub fn addresses_of(row: &Value) -> BTreeSet { found } -/// Names each address: all the names of the nearest symbol at or below it, which are many where -/// the linker folded identical functions, and how far above that symbol it lies. -pub fn name_addresses( - targets: &BTreeSet, - sorted_symbols: &[Symbol], -) -> BTreeMap)> { - let mut named = BTreeMap::new(); - for target in targets { - let end = sorted_symbols.partition_point(|(address, _)| address <= target); - let Some((nearest, _)) = end.checked_sub(1).map(|at| &sorted_symbols[at]) else { - continue; - }; - if target - nearest > NEAREST_SYMBOL { - continue; - } - let start = sorted_symbols.partition_point(|(address, _)| address < nearest); - let names = sorted_symbols[start..end] - .iter() - .map(|(_, name)| stable_name(name).to_owned()) - .collect(); - named.insert(*target, (target - nearest, names)); - } - named -} - -/// The names to keep from the new build's symbols. -pub fn wanted_names(named: &BTreeMap)>) -> HashSet { - named - .values() - .flat_map(|(_, names)| names.iter().cloned()) - .collect() -} - -/// Each place an address may have moved to, with how many of its names say so, most votes first. -fn candidates( - names: &[String], - distance: u32, - new: &HashMap>, -) -> Vec<(u32, usize)> { - let mut votes: BTreeMap = BTreeMap::new(); - for name in names { - for address in new.get(name).map_or(&[][..], Vec::as_slice) { - *votes.entry(address + distance).or_default() += 1; - } - } - let mut votes: Vec<_> = votes.into_iter().collect(); - votes.sort_by_key(|(address, count)| (std::cmp::Reverse(*count), *address)); - votes -} - /// A function's instructions, read as far as this needs them. pub mod x64 { /// One decoded instruction: its length, where its RIP-relative displacement or relative branch @@ -622,49 +551,6 @@ fn usize_at(row: &Value, path: &str) -> Option { read_address(at_path(row, path)) } -/// Everything the new build supplies. -pub struct NewBuild<'a> { - pub version: &'a str, - pub pe: &'a PeFile<'a>, - pub symbols: &'a HashMap>, - /// Where each address with no public name went, found through private symbols. - pub private: &'a BTreeMap, -} - -/// Settles an address the names disagree on. Folded functions share names across builds, so the -/// names alone can point at a function the new build no longer folds with the wanted one. The -/// instructions that row checks for it say which of the places is meant, and a table slot that -/// must hold it says the same. -fn settle(target: u32, choices: &[(u32, usize)], build: &Value, pe: &PeFile) -> Option { - let mut remaining: Vec = choices.iter().map(|(address, _)| *address).collect(); - let mut guards = vec![]; - collect_guards(build, &mut guards); - for (address, bytes) in guards { - if address != target { - continue; - } - let wanted = x64::shape(&bytes)?; - remaining.retain(|place| { - pe.read(*place, bytes.len()) - .and_then(x64::shape) - .is_some_and(|shape| shape == wanted) - }); - } - if remaining.len() == 1 { - return Some(remaining[0]); - } - // The linker folds functions with the same code under one name, and a new build can fold them - // into two groups. Short functions read to their end show that any of the places does the same. - let code: Vec<_> = remaining - .iter() - .map(|place| whole_function(pe, *place)) - .collect(); - let first = code.first()?.as_ref()?; - code.iter() - .all(|other| other.as_ref() == Some(first)) - .then(|| remaining[0]) -} - /// The bytes of a function short enough to read to its end: its first `ret` with no branch before. pub(crate) fn whole_function(pe: &PeFile, address: u32) -> Option> { let bytes = pe.read(address, 48)?; @@ -968,53 +854,12 @@ fn read_rounded_corners(build: &mut Value, pe: &PeFile, report: &mut PortReport) build["split"]["set_rounded_corners_parity"] = write_address(start + 13); } -/// Addresses read from instructions above, which no symbol names. +/// Addresses read from instructions above, which no fingerprint finds. const READ_FROM_CODE: &[&str] = &[ "split.set_rounded_corners_changed", "split.set_rounded_corners_parity", ]; -fn read_from_code_targets(build: &Value) -> Vec { - READ_FROM_CODE - .iter() - .filter_map(|path| usize_at(build, path)) - .map(|value| value as u32) - .collect() -} - -/// The code addresses a row holds that no public symbol starts at, which need private symbols. -pub fn unnamed_code( - prior: &Value, - named: &BTreeMap)>, - pe_of_new: &PeFile, -) -> Vec { - let read = read_from_code_targets(&prior["build"]); - let mut out = vec![]; - for (target, (distance, _)) in named { - // The prior module is gone by now. Code and data keep their sections from build to build. - if *distance != 0 && !read.contains(target) && pe_of_new.is_code(*target) { - out.push(*target); - } - } - out -} - -/// Makes the new row. `prior` is `{frame, build}`, as the runtime writes it. -pub fn port_row( - prior: &Value, - named: &BTreeMap)>, - new: &NewBuild, -) -> (Value, PortReport) { - let (row, mut report) = begin_row(prior, new.version, true); - let mut moved: BTreeMap = BTreeMap::new(); - let targets = addresses_of(&row); - report.addresses = targets.len(); - port_by_name(prior, &row, named, new, &targets, &mut moved, &mut report); - let (mut row, mut report) = finish_row(row, &moved, new.pe, report); - settle_carried(&mut row, &mut report); - (row, report) -} - /// Settles each value no recipe or instruction read from the new build. A value the runtime finds /// by reflection is left out of the row. A value the runtime does not read in this row is written /// as zero. A value of a feature the runtime can do without turns @@ -1112,10 +957,6 @@ fn settle_carried(row: &mut Value, report: &mut PortReport) { /// row; without it they are read from the new build later, each with its own review line. fn begin_row(prior: &Value, version: &str, carries: bool) -> (Value, PortReport) { let mut row = prior.clone(); - if let Some(object) = row.as_object_mut() { - // The mark tells how the prior row was made, not this one. - object.remove(WITHOUT_PDB); - } let prior_version = prior["frame"]["version"] .as_str() .unwrap_or_default() @@ -1218,73 +1059,6 @@ fn command_targets(prior: &Value, version: &str) -> BTreeMap { } } -/// Finds each address of a row through the public names of both builds. -fn port_by_name( - prior: &Value, - row: &Value, - named: &BTreeMap)>, - new: &NewBuild, - targets: &BTreeSet, - moved: &mut BTreeMap, - report: &mut PortReport, -) { - for target in targets { - let Some((distance, names)) = named.get(target) else { - continue; - }; - // No public name covers this function: the distance from the nearest one means nothing, - // since another build lays those functions out differently. - if *distance != 0 - && new.pe.is_code(*target) - && !read_from_code_targets(&prior["build"]).contains(target) - { - match new.private.get(target) { - Some(place) => { - moved.insert(*target, *place); - report.private.push(format!("{target:#x} -> {place:#x}")); - } - None => report.review.push(format!( - "{target:#x} lies in a function with no name in both builds" - )), - } - continue; - } - let choices = candidates(names, *distance, new.symbols); - let place = match choices.as_slice() { - [] => None, - [(only, _)] => Some(*only), - many => { - let settled = settle(*target, many, &row["build"], new.pe); - let place = settled - .or_else(|| by_slot(*target, many, &row["build"], new.pe, named, new.symbols)); - match place { - Some(place) => report - .settled - .push(format!("{target:#x} -> {place:#x} of {many:x?}")), - None => { - // Most folded names still fold together, so the largest group is the likely - // place, and a person looks at it. - report.review.push(format!( - "{target:#x} has several places: {many:x?}, first of {:?}", - &names[..names.len().min(3)] - )); - } - } - place.or(Some(many[0].0)) - } - }; - if let Some(place) = place { - if *distance != 0 { - report.interior.push(format!( - "{target:#x} = {}+{distance:#x} -> {place:#x}", - names[0] - )); - } - moved.insert(*target, place); - } - } -} - /// Writes the new places into a row and reads every guard and table slot back from the new module. fn finish_row( mut row: Value, @@ -1499,7 +1273,7 @@ pub(crate) fn find_table(pe: &PeFile, slot: u32, function: u32) -> Vec { } /// Makes the row of a build that has no row from the fingerprints of a verified row of the same -/// milestone, without symbols. Each address must match exactly one place, no two addresses may +/// milestone, from the new module alone. Each address must match exactly one place, no two addresses may /// share one, and every function start and table slot is then checked again in the new module the /// way a ported row is. Any doubt is an error with its reasons, and then the runtime changes /// nothing in the browser. @@ -1514,10 +1288,13 @@ pub fn find_row(prior: &Value, version: &str, pe: &PeFile) -> Result (Value, PortReport) { let (mut row, mut report) = begin_row(prior, version, prior_pe.is_none()); - report.made_without_pdb = true; let prior_starts = prior_pe.map(PeFile::function_starts).unwrap_or_default(); let targets = fingerprint_targets(prior); report.addresses = targets.len(); @@ -1691,8 +1467,8 @@ pub fn find_candidate( .iter() .map(|(target, (_, want))| (*target, want.clone())) .collect(); - // The tables the prior build's public symbols name after a class are the tables of - // views classes the slot shift compares. + // The tables a class name was confirmed for in the prior build are the tables of views + // classes the slot shift compares. let views: BTreeSet = classes.keys().copied().collect(); let resolution = row_resolve::resolve(prior_pe, pe, &moved, &asked, &table_targets, &views); @@ -1726,7 +1502,9 @@ pub fn find_candidate( if let Some(object) = row.as_object_mut() { // They describe the prior build, so they would mislead in this row. object.remove("fingerprints"); + object.remove(CLASSES); } + record_classes(prior, &mut row, classes, &moved); if let Some(prior_pe) = prior_pe { read_carried(prior, &mut row, &moved, &followed, prior_pe, pe, &mut report); } @@ -1914,170 +1692,82 @@ fn read_carried( } } -/// The key of a row made without its build's symbols. It holds what the row job needs to make the -/// row again from the symbols once they are published, and to compare the two. The runtime reads -/// only `frame` and `build`, so the mark changes nothing in a browser. -pub const WITHOUT_PDB: &str = "made_without_pdb"; +/// The key of a row that names the views class of each of its class tables, by the path of the +/// value that holds the table, as `{"build.layout.frame_vtable": "BrowserFrameViewWin"}`. The +/// runtime reads only `frame` and `build`, so the names change nothing in a browser. +pub const CLASSES: &str = "classes"; -/// Marks a row made from fingerprints with the symbol key of its module, the prior row it was made -/// from, and how the row job fetches the build again. -pub fn mark_without_pdb( - row: &mut Value, - pdb_key: &str, - prior_version: &str, - channel: &str, - download: &str, -) { - row[WITHOUT_PDB] = json!({ - "pdb_key": pdb_key, - "prior_version": prior_version, - "channel": channel, - "download": download, - }); -} - -/// Where a row made from fingerprints differs from the row the build's own symbols give. A value -/// the fingerprint row left out is not a difference, since the runtime does without it. -pub fn differences_from_pdb_row(found: &Value, from_pdb: &Value) -> Vec { - fn walk(path: &str, found: &Value, pdb: &Value, out: &mut Vec) { - match (found, pdb) { - (Value::Null, _) => {} - (Value::Object(left), Value::Object(right)) => { - for (key, value) in left { - let other = right.get(key).unwrap_or(&Value::Null); - walk(&format!("{path}.{key}"), value, other, out); - } - } - (Value::Array(left), Value::Array(right)) if left.len() == right.len() => { - for (index, (a, b)) in left.iter().zip(right).enumerate() { - walk(&format!("{path}[{index}]"), a, b, out); - } - } - _ if found != pdb => { - out.push(format!( - "{path}: {found} from fingerprints, {pdb} from the PDB" - )); - } - _ => {} +/// The path of every address a row holds, the frame entry's included, as `build.layout.frame_vtable` +/// or `frame.frame_view_vtable`. +fn address_paths(row: &Value) -> Vec<(String, u32)> { + let mut out = Vec::new(); + let mut note = |path: &str, value: &mut Value| { + if READ_FROM_CODE.iter().any(|field| path.ends_with(field)) { + return; } - } - let mut out = vec![]; - for part in ["frame", "build"] { - walk(part, &found[part], &from_pdb[part], &mut out); - } - out -} - -/// Compares the marked row of `browser` `version` in `table` with the row made from the build's -/// symbols. When they agree the mark is removed, since the symbols now vouch for the row. The -/// differences are returned, and the table is left as it was when there are any. -pub fn check_against_pdb( - table: &mut Value, - browser: &str, - version: &str, - from_pdb: &Value, -) -> Result, String> { - let row = table["rows"] - .as_array_mut() - .ok_or("the table has no rows")? - .iter_mut() - .find(|row| row["frame"]["browser"] == browser && row["frame"]["version"] == version) - .ok_or_else(|| format!("the table has no row for {browser} {version}"))?; - if row.get(WITHOUT_PDB).is_none() { - return Err(format!( - "the row of {browser} {version} was not made without its PDB" - )); - } - let differences = differences_from_pdb_row(row, from_pdb); - if differences.is_empty() { - if let Some(object) = row.as_object_mut() { - object.remove(WITHOUT_PDB); + if let Some(address) = read_address(value).filter(|value| is_address(*value)) { + out.push((path.to_owned(), address as u32)); } - } - Ok(differences) + }; + let mut build = row["build"].clone(); + walk_addresses("build", &mut build, &mut note); + let mut frame = frame_addresses(&row["frame"]); + walk_addresses("frame", &mut frame, &mut note); + out } -/// The views class each class table of the prior row is named after by the prior build's public -/// symbols, for the tables found again by their class name. A table whose symbols name two classes -/// is left out. -pub fn class_names(named: &BTreeMap)>) -> BTreeMap { +/// The views class of each class table of the prior row, from the build alone. A name the prior +/// row records for the table is taken when it gives exactly that table in the prior module, and +/// a table with no such name is named by the class name its metadata holds, read back from the +/// prior module by `row_class`. Either way the name is the one the class's `BEGIN_METADATA` gives +/// in Chromium's source, and a table no name gives alone has none. +pub fn prior_classes(prior: &Value, prior_pe: &PeFile) -> BTreeMap { + let recorded = prior[CLASSES].as_object(); let mut out = BTreeMap::new(); - for (target, (distance, names)) in named { - if *distance != 0 { + let mut tried = BTreeSet::new(); + for (path, address) in address_paths(prior) { + if prior_pe.is_code(address) || out.contains_key(&address) { continue; } - let classes: BTreeSet<&str> = names - .iter() - .filter_map(|name| crate::row_class::class_of_table_symbol(stable_name(name))) - .collect(); - if let [only] = classes.into_iter().collect::>()[..] { - out.insert(*target, only.to_owned()); - } - } - out -} - -/// Adds to each review line that starts with a prior address the public name that address lies -/// in, from the prior build's symbols, so a person sees which function was not found. -pub fn name_review_lines(review: &mut [String], named: &BTreeMap)>) { - for line in review { - let Some(digits) = line.strip_prefix("0x") else { - continue; - }; - let end = digits - .find(|c: char| !c.is_ascii_hexdigit()) - .unwrap_or(digits.len()); - let Ok(address) = u32::from_str_radix(&digits[..end], 16) else { - continue; - }; - if let Some((distance, names)) = named.get(&address) { - if let Some(name) = names.first() { - line.push_str(&format!(" ({name}+{distance:#x} in the prior build)")); + let name = recorded + .and_then(|names| names.get(&path)) + .and_then(Value::as_str) + .filter(|name| crate::row_class::names_table(prior_pe, name, address)) + .map(str::to_owned); + let name = match name { + Some(name) => Some(name), + None if tried.insert(address) => { + crate::row_class::class_name_of_table(prior_pe, address) } + None => None, + }; + if let Some(name) = name { + out.insert(address, name); } } + out } -/// A folded function that fills a known table slot is the one in that slot of the new table. -fn by_slot( - target: u32, - choices: &[(u32, usize)], - build: &Value, - pe: &PeFile, - named: &BTreeMap)>, - symbols: &HashMap>, -) -> Option { - for (vtable_path, slot_path, function_path) in VTABLE_SLOTS { - if usize_at(build, function_path) != Some(u64::from(target)) { - continue; - } - let vtable = usize_at(build, vtable_path)? as u32; - let slot = usize_at(build, slot_path)? as u32; - let (distance, names) = named.get(&vtable)?; - let [(new_vtable, _)] = candidates(names, *distance, symbols)[..] else { - continue; - }; - let held = pe.pointer_rva(new_vtable + slot * 8)?; - if choices.iter().any(|(place, _)| *place == held) { - return Some(held); +/// Writes into the new row the class name of each class table it placed, by the path of each value +/// that holds the table. +fn record_classes( + prior: &Value, + row: &mut Value, + classes: &BTreeMap, + moved: &BTreeMap, +) { + let mut names = serde_json::Map::new(); + for (path, address) in address_paths(prior) { + if let Some(name) = classes + .get(&address) + .filter(|_| moved.contains_key(&address)) + { + names.insert(path, Value::String(name.clone())); } } - // The classes of hidden buttons keep the function of one known slot. - let slot = usize_at(build, "toolbar.theme_slot")? as u32; - for pair in build["toolbar"]["hidden"].as_array()? { - if read_address(&pair[1]) != Some(u64::from(target)) { - continue; - } - let (distance, names) = named.get(&(read_address(&pair[0])? as u32))?; - let [(new_vtable, _)] = candidates(names, *distance, symbols)[..] else { - continue; - }; - let held = pe.pointer_rva(new_vtable + slot * 8)?; - if choices.iter().any(|(place, _)| *place == held) { - return Some(held); - } + if !names.is_empty() { + row[CLASSES] = Value::Object(names); } - None } /// The frame entry keeps plain numbers. The walk over a row reads `0x` strings. @@ -2148,59 +1838,136 @@ fn check_frame_slot(frame: &mut Value, pe: &PeFile, report: &mut PortReport) { } } -/// The start of the public name of `views::View::ConvertPointToScreen(const View*, gfx::Point*)`: -/// a static function returning nothing. The other overload returns the point and is named `SA?AV`. -pub const SCREEN_ORIGIN_NAME: &str = "?ConvertPointToScreen@View@views@@SAX"; +/// Leaves `screen_origin`, `[address, first bytes]` of `views::View::ConvertPointToScreen`, out of a +/// row whose prior row had none. A prior row that had it was found again with every other address. +/// The runtime then keeps placing bubbles from the window's monitor, so the row is not stopped. +pub fn leave_out_screen_origin(row: &mut Value, report: &mut PortReport) { + if row["build"]["screen_origin"].is_array() { + return; + } + row["build"]["screen_origin"] = Value::Null; + report + .left_out + .push("build.screen_origin: the prior row has none".to_owned()); +} -/// How many bytes of that function's start the runtime compares before it ever calls it. -const SCREEN_ORIGIN_BYTES: usize = 12; +/// The group a value of a row is scored in: its feature, or the window, whose parts cannot be off. +const WINDOW: &str = "window"; + +/// How one feature of a row made without debug symbols compares with the verified row of the same +/// build, value by value. +#[derive(Debug, Default, Serialize, PartialEq, Eq)] +pub struct FeatureScore { + /// Values the made row holds exactly as the verified row does. + pub equal: usize, + /// Values the made row holds differently, with both. Any is a wrong value. + pub different: Vec, + /// The made row turns the feature off, so none of its values is used. + pub off: bool, + /// Values the made row does not hold or does not use: the runtime finds them by reflection, + /// does not read them in this build, or the prior row did not have them. + pub not_held: Vec, +} -/// Whether a public name is the one `screen_origin` is found by. -pub fn is_screen_origin_name(name: &str) -> bool { - stable_name(name).starts_with(SCREEN_ORIGIN_NAME) +/// The score of a made row against its answer key: each feature's comparison, and the review lines +/// that stop the row. +#[derive(Debug, Default, Serialize)] +pub struct RowScore { + pub browser: String, + pub version: String, + pub prior_version: String, + pub features: BTreeMap, + pub review: Vec, } -/// The first whole instructions of a function, at least `SCREEN_ORIGIN_BYTES` long. -fn function_start(pe: &PeFile, address: u32) -> Option> { - if !pe.is_code(address) { - return None; +impl RowScore { + /// How many values were found but differ from the verified row. Must be zero. + pub fn wrong(&self) -> usize { + self.features + .values() + .map(|score| score.different.len()) + .sum() } - let window = pe.read(address, 32)?; - let (ends, _) = x64::boundaries(window, SCREEN_ORIGIN_BYTES); - let end = *ends.iter().find(|end| **end >= SCREEN_ORIGIN_BYTES)?; - Some(window[..end].to_vec()) } -/// Adds `screen_origin`, `[address, first bytes]` of `views::View::ConvertPointToScreen`, to a row -/// whose prior row had none, by the function's public name in the new build. A prior row that had -/// it was ported with every other address. A build with no single place for the name goes without -/// it, and the runtime keeps placing bubbles from the window's monitor, so the row is not stopped. -pub fn seed_screen_origin(row: &mut Value, places: &[u32], pe: &PeFile, report: &mut PortReport) { - if row["build"]["screen_origin"].is_array() { - return; +/// Every value a row part holds that is not a list or object, by its path. +fn leaves(path: &str, value: &Value, out: &mut BTreeMap) { + match value { + Value::Object(object) => { + for (key, item) in object { + let next = if path.is_empty() { + key.clone() + } else { + format!("{path}.{key}") + }; + leaves(&next, item, out); + } + } + Value::Array(items) if !items.is_empty() => { + for (index, item) in items.iter().enumerate() { + leaves(&format!("{path}[{index}]"), item, out); + } + } + _ => { + out.insert(path.to_owned(), value.clone()); + } } - let mut places = places.to_vec(); - places.sort_unstable(); - places.dedup(); - let found = match places.as_slice() { - [only] => function_start(pe, *only).map(|bytes| (*only, bytes)), - _ => None, +} + +/// Compares a row made from a prior row with the row people verified for the same build. A value of +/// a feature the made row turns off is not compared, since the runtime does not use it. A value the +/// made row leaves out, or writes as zero because this build does not read it, is listed as not +/// held. Every other value must be equal, and one that differs is listed with both values. +pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScore { + let off: BTreeSet<&str> = made[crate::row_features::SWITCHED_OFF] + .as_array() + .map_or(&[][..], Vec::as_slice) + .iter() + .filter_map(|entry| entry["feature"].as_str()) + .collect(); + let unused: BTreeSet<&str> = report + .unused + .iter() + .chain(&report.reflected) + .filter_map(|line| line.split(": ").next()) + .collect(); + let mut score = RowScore { + browser: report.browser.clone(), + version: report.version.clone(), + prior_version: report.prior_version.clone(), + review: report.review.clone(), + ..RowScore::default() }; - match found { - Some((address, bytes)) => { - row["build"]["screen_origin"] = - json!([write_address(u64::from(address)), hex_text(&bytes)]); - report.derived.push(format!( - "build.screen_origin: {SCREEN_ORIGIN_NAME} at {address:#x}" - )); - } - None => { - row["build"]["screen_origin"] = Value::Null; - report.left_out.push(format!( - "build.screen_origin: no single readable function named {SCREEN_ORIGIN_NAME}: {places:x?}" - )); + for part in ["frame", "build"] { + let (mut want, mut have) = (BTreeMap::new(), BTreeMap::new()); + leaves("", &verified[part], &mut want); + leaves("", &made[part], &mut have); + for (path, value) in want { + let feature = match part { + "build" => { + crate::row_features::feature_of(&path).map_or(WINDOW, |feature| feature.name) + } + _ => WINDOW, + }; + let entry = score.features.entry(feature.to_owned()).or_default(); + if off.contains(feature) { + entry.off = true; + continue; + } + let shown = format!("{part}.{path}"); + match have.get(&path) { + Some(found) if *found == value => entry.equal += 1, + None | Some(Value::Null) => entry.not_held.push(shown), + Some(_) if unused.iter().any(|unused| path.starts_with(unused)) => { + entry.not_held.push(shown) + } + Some(found) => entry + .different + .push(format!("{shown}: made {found}, verified {value}")), + } } } + score } /// The review items for the parts of the prior row that only a person writes today. A row made @@ -2276,58 +2043,33 @@ mod tests { }) } - fn symbols_old() -> Vec { - [ - (0x200000, "vt"), - (0x200100, "bounds"), - (0x200200, "hwnd"), - (0x200300, "paint"), - ] - .map(|(address, name)| (address, name.to_owned())) - .to_vec() - } - - fn places(rows: &[(&str, &[u32])]) -> HashMap> { - rows.iter() - .map(|(name, list)| ((*name).to_owned(), list.to_vec())) - .collect() - } - fn pointer(rva: u32) -> [u8; 8] { (IMAGE_BASE + u64::from(rva)).to_le_bytes() } + /// Places the prior row's addresses where `moved` says, as the fingerprints and `row_resolve` + /// would, and settles the rest of the row the way every new row is settled. fn port( prior: &Value, - new: &[(&str, &[u32])], + moved: &[(u32, u32)], code: &[(u32, &[u8])], version: &str, ) -> (Value, PortReport) { - let mut targets = addresses_of(&prior["build"]); - for key in ["frame_view_vtable", "client_view_bounds", "hwnd_for_view"] { - targets.insert(prior["frame"][key].as_u64().unwrap() as u32); - } - let named = name_addresses(&targets, &symbols_old()); let bytes = module(code); let pe = PeFile::parse(&bytes).unwrap(); - let symbols = places(new); - port_row( - prior, - &named, - &NewBuild { - version, - pe: &pe, - symbols: &symbols, - private: &BTreeMap::new(), - }, - ) - } - - const NEW_SYMBOLS: &[(&str, &[u32])] = &[ - ("vt", &[0x101000]), - ("bounds", &[0x101100]), - ("hwnd", &[0x101200]), - ("paint", &[0x101300]), + let (row, mut report) = begin_row(prior, version, true); + report.addresses = addresses_of(&row["build"]).len(); + let moved: BTreeMap = moved.iter().copied().collect(); + let (mut row, mut report) = finish_row(row, &moved, &pe, report); + settle_carried(&mut row, &mut report); + (row, report) + } + + const NEW_PLACES: &[(u32, u32)] = &[ + (0x200000, 0x101000), + (0x200100, 0x101100), + (0x200200, 0x101200), + (0x200300, 0x101300), ]; fn new_code() -> Vec<(u32, Vec)> { @@ -2345,47 +2087,9 @@ mod tests { } #[test] - fn nfr3_screen_origin_is_found_by_its_public_name_in_the_new_build() { - // push rsi; push rdi; sub rsp, 0x28; mov rsi, rdx; mov rdi, rcx; call. - let start = hex("56574883ec284889d64889cfe800000000").unwrap(); - let bytes = module(&[(0x101400, start.as_slice())]); - let pe = PeFile::parse(&bytes).unwrap(); - let mut row = prior(); - let mut report = PortReport::default(); - seed_screen_origin(&mut row, &[0x101400, 0x101400], &pe, &mut report); - assert_eq!( - row["build"]["screen_origin"], - json!(["0x101400", "56574883ec284889d64889cf"]) - ); - assert!(report.review.is_empty() && report.left_out.is_empty()); - // A row that already has it keeps the place the port gave it. - seed_screen_origin(&mut row, &[0x101500], &pe, &mut report); - assert_eq!(row["build"]["screen_origin"][0], "0x101400"); - // No name, or two places for it, leaves the part out without stopping the row. - for places in [&[][..], &[0x101400, 0x101500][..]] { - let mut row = prior(); - let mut report = PortReport::default(); - seed_screen_origin(&mut row, places, &pe, &mut report); - assert!(row["build"]["screen_origin"].is_null()); - assert_eq!(report.left_out.len(), 1); - assert!(report.review.is_empty()); - } - // Only the in-place overload, which returns nothing, is the one. - assert!(is_screen_origin_name( - "?ConvertPointToScreen@View@views@@SAXPEBV12@PEAVPoint@gfx@@@Z" - )); - assert!(!is_screen_origin_name( - "?ConvertPointToScreen@View@views@@SA?AVPoint@gfx@@PEBV12@AEBV34@@Z" - )); - assert!(!is_screen_origin_name( - "?ConvertRectToScreen@View@views@@SAXPEBV12@PEAVRect@gfx@@@Z" - )); - } - - #[test] - fn nfr3_a_new_row_takes_addresses_by_name_and_bytes_from_the_new_module() { + fn nfr3_a_new_row_takes_the_found_places_and_bytes_from_the_new_module() { let code = new_code(); - let (row, report) = port(&prior(), NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); + let (row, report) = port(&prior(), NEW_PLACES, &code_refs(&code), "1.0.0.2"); assert_eq!(report.review, Vec::::new()); assert_eq!(row["build"]["version"], json!([1, 0, 0, 2])); assert_eq!(row["frame"]["version"], "1.0.0.2"); @@ -2402,14 +2106,14 @@ mod tests { } #[test] - fn nfr3_a_name_the_new_build_lacks_stops_the_row() { + fn nfr3_an_address_with_no_new_place_stops_the_row() { let code = new_code(); - let symbols: Vec<_> = NEW_SYMBOLS + let places: Vec<_> = NEW_PLACES .iter() - .filter(|(name, _)| *name != "paint") + .filter(|(prior, _)| *prior != 0x200300) .copied() .collect(); - let (_, report) = port(&prior(), &symbols, &code_refs(&code), "1.0.0.2"); + let (_, report) = port(&prior(), &places, &code_refs(&code), "1.0.0.2"); assert!( report .review @@ -2428,7 +2132,7 @@ mod tests { // A wrong prior value shows that the new row does not copy it. prior["build"]["toolbar"]["dev"] = json!({"inspect": 1, "console": 2, "colours": []}); let code = new_code(); - let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "158.0.8127.36"); + let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "158.0.8127.36"); assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 40023); assert_eq!(row["build"]["toolbar"]["dev"]["console"], 40005); assert!( @@ -2444,11 +2148,11 @@ mod tests { .expect("the other values still cross the milestone"); assert!(!milestone.contains("toolbar.dev.console"), "{milestone}"); // A milestone whose header was not read offers no command rather than the prior one. - let (row, _) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "199.0.1.1"); + let (row, _) = port(&prior, NEW_PLACES, &code_refs(&code), "199.0.1.1"); assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 0); // A row that never offered the developer bar keeps offering none. prior["build"]["toolbar"]["dev"] = json!({"inspect": 0, "console": 0, "colours": []}); - let (row, _) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "158.0.8127.36"); + let (row, _) = port(&prior, NEW_PLACES, &code_refs(&code), "158.0.8127.36"); assert_eq!(row["build"]["toolbar"]["dev"]["console"], 0); } @@ -2473,7 +2177,7 @@ mod tests { #[test] fn nfr6_a_feature_with_an_unread_value_is_off_for_that_build() { let code = new_code(); - let (row, report) = port(&prior_with_features(), NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + let (row, report) = port(&prior_with_features(), NEW_PLACES, &code_refs(&code), "2.0.0.1"); // Nothing holds the rest of the row back. assert_eq!(report.review, Vec::::new()); assert!(report.carried.is_empty(), "{:?}", report.carried); @@ -2508,7 +2212,7 @@ mod tests { json!({"host_view": "0x38", "page_area": "0x0", "contents_container": "0xd8"}); prior["build"]["toolbar"]["get_widget_slot"] = json!("0xa"); let code = new_code(); - let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "2.0.0.1"); assert_eq!(report.review, Vec::::new()); assert!(report.carried.is_empty(), "{:?}", report.carried); assert_eq!(report.reflected.len(), 5, "{:?}", report.reflected); @@ -2528,7 +2232,7 @@ mod tests { let mut prior = prior_with_features(); prior["build"]["layout"] = json!({"view_bounds_offset": "0x1c8"}); let code = new_code(); - let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "2.0.0.1"); assert_eq!(report.carried, ["layout.view_bounds_offset"]); assert!( report.review.iter().any(|line| line.contains("milestone") @@ -2543,7 +2247,7 @@ mod tests { #[test] fn nfr6_a_row_within_its_milestone_turns_nothing_off() { let code = new_code(); - let (row, report) = port(&prior_with_features(), NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); + let (row, report) = port(&prior_with_features(), NEW_PLACES, &code_refs(&code), "1.0.0.2"); assert_eq!(report.review, Vec::::new()); assert!(report.switched_off.is_empty()); assert_eq!(row["build"]["split"]["supported"], true); @@ -2553,7 +2257,7 @@ mod tests { #[test] fn nfr3_a_row_that_crosses_a_milestone_stops_for_review() { let code = new_code(); - let (_, report) = port(&prior(), NEW_SYMBOLS, &code_refs(&code), "2.0.0.1"); + let (_, report) = port(&prior(), NEW_PLACES, &code_refs(&code), "2.0.0.1"); assert!( report.review.iter().any(|line| line.contains("milestone")), "{:?}", @@ -2567,7 +2271,7 @@ mod tests { .into_iter() .filter(|(rva, _)| *rva != 0x101008) .collect(); - let (_, report) = port(&prior(), NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); + let (_, report) = port(&prior(), NEW_PLACES, &code_refs(&code), "1.0.0.2"); assert!( report .review @@ -2578,55 +2282,6 @@ mod tests { ); } - #[test] - fn nfr3_folded_names_that_stay_apart_are_settled_by_the_guard_or_stop_the_row() { - let mut code = new_code(); - code.push((0x101400, hex("565755534883ec584889ce48").unwrap())); - let two: &[u32] = &[0x101300, 0x101400]; - let symbols: Vec<_> = NEW_SYMBOLS - .iter() - .map(|(name, list)| { - if *name == "paint" { - (*name, two) - } else { - (*name, *list) - } - }) - .collect(); - let (row, report) = port(&prior(), &symbols, &code_refs(&code), "1.0.0.2"); - assert_eq!(row["build"]["toolbar"]["paint"], "0x101300"); - assert_eq!(report.settled.len(), 1); - assert!(report.review.is_empty(), "{:?}", report.review); - // Two places with the same start cannot be told apart. - let mut same = new_code(); - same.push((0x101400, hex("415741564155415456575553").unwrap())); - let (_, report) = port(&prior(), &symbols, &code_refs(&same), "1.0.0.2"); - assert!( - report - .review - .iter() - .any(|line| line.contains("several places")), - "{:?}", - report.review - ); - } - - #[test] - fn nfr3_a_function_with_no_public_name_is_not_moved_by_distance() { - let mut prior = prior(); - prior["build"]["toolbar"]["inside"] = json!("0x200340"); - let code = new_code(); - let (_, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); - assert!( - report - .review - .iter() - .any(|line| line.contains("no name in both")), - "{:?}", - report.review - ); - } - #[test] fn nfr3_a_guard_a_hook_copies_stops_on_an_instruction_in_the_new_build() { let mut prior = prior(); @@ -2634,7 +2289,7 @@ mod tests { prior["build"]["toolbar"]["paint_prologue"] = json!("41574156565755534881ecb8000000"); let mut code = new_code(); code[2].1 = hex("4156565755534881eca00000004889ce0000").unwrap(); - let (row, report) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); + let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "1.0.0.2"); assert_eq!( row["build"]["toolbar"]["paint_prologue"], "4156565755534881eca0000000" @@ -2642,39 +2297,12 @@ mod tests { assert!(report.review.is_empty(), "{:?}", report.review); } - #[test] - fn nfr3_stable_name_drops_what_the_linker_adds() { - assert_eq!(stable_name("??1GURL@@QEAA@XZ\0"), "??1GURL@@QEAA@XZ"); - assert_eq!(stable_name("?F@@YAXXZ.llvm.123456"), "?F@@YAXXZ"); - assert_eq!( - stable_name(".weak.??_7BrowserView@@6B@.default.?RejectPromise@@"), - "??_7BrowserView@@6B@" - ); - } - #[test] fn nfr3_addresses_are_told_from_offsets_and_the_absent_marker() { let row = json!({"a": "0x10", "b": "0xfffff", "c": "0x100000", "d": ["0x7fff0000", "0x4fb01f0"], "e": 1234567, "f": "0xabcd_not"}); assert_eq!(addresses_of(&row), BTreeSet::from([0x100000, 0x4fb01f0])); } - #[test] - fn nfr3_an_address_inside_a_table_is_named_by_the_table_below_it() { - let symbols: Vec = vec![ - (0x1000, "other".into()), - (0x2000, "??_7Table@@6B@".into()), - (0x2000, "alias".into()), - (0x9000, "far".into()), - ]; - let named = name_addresses(&BTreeSet::from([0x2000, 0x2250, 0x8000]), &symbols); - assert_eq!( - named[&0x2000], - (0, vec!["??_7Table@@6B@".to_owned(), "alias".to_owned()]) - ); - assert_eq!(named[&0x2250].0, 0x250); - assert!(!named.contains_key(&0x8000)); - } - #[test] fn nfr3_x64_lengths_of_real_function_starts() { // Chrome 156.0.8078.74 chip text: the frame setup ends at byte 13. @@ -3075,10 +2703,9 @@ mod tests { } #[test] - fn nfr6_a_build_without_symbols_gets_a_row_from_the_prior_builds_fingerprints() { + fn nfr6_a_new_build_gets_a_row_from_the_prior_rows_fingerprints_alone() { let (row, report) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); assert!(report.review.is_empty(), "{:?}", report.review); - assert!(report.made_without_pdb); assert_eq!(report.fingerprinted.len(), 4, "{:?}", report.fingerprinted); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); assert_eq!(row["frame"]["frame_view_vtable"], 0x103000); @@ -3183,72 +2810,101 @@ mod tests { } #[test] - fn nfr6_a_row_made_without_its_pdb_is_checked_against_the_pdb_row() { - let (mut row, _) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); - mark_without_pdb(&mut row, "ABC1", "1.0.0.2", "stable", ""); - assert_eq!(row[WITHOUT_PDB]["prior_version"], "1.0.0.2"); - let mut from_pdb = row.clone(); - from_pdb.as_object_mut().unwrap().remove(WITHOUT_PDB); - // A part the fingerprint row left out is no difference. - row["build"]["screen_origin"] = Value::Null; - from_pdb["build"]["screen_origin"] = json!(["0x103400", "5657"]); - let table = json!({"rows": [row]}); - let mut agreed = table.clone(); - assert_eq!( - check_against_pdb(&mut agreed, "B", "1.0.0.3", &from_pdb).unwrap(), - Vec::::new() - ); - assert!(agreed["rows"][0].get(WITHOUT_PDB).is_none()); - // A different address is a difference, and the row keeps its mark. - from_pdb["build"]["toolbar"]["paint"] = json!("0x103310"); - let mut differs = table.clone(); - let differences = check_against_pdb(&mut differs, "B", "1.0.0.3", &from_pdb).unwrap(); - assert_eq!(differences.len(), 1, "{differences:?}"); - assert!( - differences[0].starts_with("build.toolbar.paint:"), - "{differences:?}" - ); - assert_eq!(differs, table); - // A row made from symbols has nothing to check. - let mut plain = json!({"rows": [from_pdb.clone()]}); - assert!(check_against_pdb(&mut plain, "B", "1.0.0.3", &from_pdb).is_err()); + fn nfr3_an_address_that_is_neither_code_nor_a_table_gets_no_fingerprints() { + let bytes = module(&code_refs(&shifted_code(0, 0x10))); + let pe = PeFile::parse(&bytes).unwrap(); + let mut row = verified_row(); + // Inside the code section's range but past what the file holds. + row["build"]["toolbar"]["state"] = json!("0x1f0000"); + let error = add_fingerprints(&mut row, &pe).unwrap_err(); + assert!(error.contains("0x1f0000"), "{error}"); + assert!(row.get("fingerprints").is_none()); } #[test] - fn nfr6_a_row_made_from_a_marked_prior_does_not_inherit_the_mark() { - let mut prior = prior(); - mark_without_pdb(&mut prior, "ABC1", "1.0.0.0", "stable", ""); - let code = new_code(); - let (row, _) = port(&prior, NEW_SYMBOLS, &code_refs(&code), "1.0.0.2"); - assert!(row.get(WITHOUT_PDB).is_none()); + fn nfr3_a_prior_row_without_screen_origin_gives_a_row_without_it() { + let mut row = prior(); + let mut report = PortReport::default(); + leave_out_screen_origin(&mut row, &mut report); + assert!(row["build"]["screen_origin"].is_null()); + assert_eq!(report.left_out.len(), 1); + assert!(report.review.is_empty()); + // A row that has it keeps the place it was found at. + row["build"]["screen_origin"] = json!(["0x101400", "5657"]); + leave_out_screen_origin(&mut row, &mut report); + assert_eq!(row["build"]["screen_origin"][0], "0x101400"); } #[test] - fn nfr6_a_review_line_names_the_prior_function_it_is_about() { - let named = BTreeMap::from([(0x101300, (0x10, vec!["?Paint@V@@".to_owned()]))]); - let mut review = vec![ - "0x101300 matches no place".to_owned(), - "0x101400: no fingerprint".to_owned(), - "the milestone changed".to_owned(), - ]; - name_review_lines(&mut review, &named); + fn nfr6_a_new_row_records_the_class_names_of_the_tables_it_placed() { + let mut prior = verified_row(); + // A name the prior row recorded is not carried: only names confirmed now are written. + prior[CLASSES] = json!({"build.toolbar.stale": "Stale"}); + let classes = BTreeMap::from([(0x101000, "BrowserFrameViewWin".to_owned())]); + let bytes = module(&code_refs(&shifted_code(0x2000, 0x44))); + let pe = PeFile::parse(&bytes).unwrap(); + let (row, report) = + find_candidate(&prior, &prints_of_prior(), None, &classes, "1.0.0.3", &pe); + assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!( - review[0], - "0x101300 matches no place (?Paint@V@@+0x10 in the prior build)" + row[CLASSES], + json!({"frame.frame_view_vtable": "BrowserFrameViewWin"}) ); - assert_eq!(review[1], "0x101400: no fingerprint"); - assert_eq!(review[2], "the milestone changed"); + // With no confirmed name the row records none. + let (row, _) = find_candidate( + &prior, + &prints_of_prior(), + None, + &BTreeMap::new(), + "1.0.0.3", + &pe, + ); + assert!(row.get(CLASSES).is_none()); } #[test] - fn nfr3_an_address_that_is_neither_code_nor_a_table_gets_no_fingerprints() { - let bytes = module(&code_refs(&shifted_code(0, 0x10))); - let pe = PeFile::parse(&bytes).unwrap(); - let mut row = verified_row(); - // Inside the code section's range but past what the file holds. - row["build"]["toolbar"]["state"] = json!("0x1f0000"); - let error = add_fingerprints(&mut row, &pe).unwrap_err(); - assert!(error.contains("0x1f0000"), "{error}"); - assert!(row.get("fingerprints").is_none()); + fn nfr6_every_address_of_a_row_is_known_by_its_path() { + let paths = address_paths(&verified_row()); + assert!(paths.contains(&("frame.frame_view_vtable".to_owned(), 0x101000))); + assert!(paths.contains(&("build.toolbar.paint".to_owned(), 0x101300))); + assert!(paths.contains(&("build.tabs.signatures[0][0]".to_owned(), 0x101300))); + // Offsets and the absent marker are not addresses. + assert!(!paths.iter().any(|(path, _)| path.ends_with("view_layer"))); + assert!(!paths.iter().any(|(path, _)| path.ends_with("missing"))); + } + + #[test] + fn nfr6_a_made_row_is_scored_value_by_value_against_the_verified_row() { + let (made, report) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); + let mut verified = made.clone(); + let score = score_row(&made, &report, &verified); + assert_eq!(score.wrong(), 0); + assert!(score.features[WINDOW].equal > 0); + // A value found at another place than the verified one is wrong. + verified["build"]["toolbar"]["paint"] = json!("0x103310"); + let score = score_row(&made, &report, &verified); + assert_eq!(score.wrong(), 1, "{:?}", score.features); + let wrong: Vec<&String> = score.features.values().flat_map(|f| &f.different).collect(); + assert!( + wrong[0].starts_with("build.toolbar.paint: made"), + "{wrong:?}" + ); + // A value the made row does not hold is not wrong. + let mut made_less = made.clone(); + made_less["build"]["toolbar"] + .as_object_mut() + .unwrap() + .remove("paint"); + let score = score_row(&made_less, &report, &verified); + assert_eq!(score.wrong(), 0); + // A feature the made row turns off is not compared at all. + let mut off = made.clone(); + off[crate::row_features::SWITCHED_OFF] = json!([{"feature": "split view", "values": []}]); + let mut split = verified.clone(); + split["build"]["split"] = json!({"supported": true, "outline_member": "0x40"}); + off["build"]["split"] = json!({"supported": false, "outline_member": "0x0"}); + let score = score_row(&off, &report, &split); + assert!(score.features["split view"].off); + assert!(score.features["split view"].different.is_empty()); } } diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index a65f945..ee91f92 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -1,7 +1,7 @@ //! Reads the values of a row that are not addresses from the new build itself. //! -//! A row holds member offsets, table slots and object sizes as well as addresses. They have no -//! public symbols, and a new milestone moves them without notice: Chromium 157 moved many view +//! A row holds member offsets, table slots and object sizes as well as addresses. No name in the +//! module tells them, and a new milestone moves them without notice: Chromium 157 moved many view //! members by 8 bytes and every frame view slot above one removed virtual by one. A port that //! copies them gives a row that looks complete and is wrong. So each such value has recipes that //! read it from the new build's own instructions and tables. A value is taken only when every diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index 6679072..dd9d19a 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -1,5 +1,5 @@ -//! Finds, in a build whose symbols are not published, the functions and class tables that the -//! prior row's fingerprints do not pin down to one place. +//! Finds, in a new build, the functions and class tables that the prior row's fingerprints do not +//! pin down to one place. //! //! Each such address is looked for by several independent methods, and a place is taken only when //! two different methods name the same place and no method names another. The methods read the @@ -849,7 +849,7 @@ pub enum Kind { pub struct Wanted { pub kind: Kind, pub candidates: Option>, - /// For a class table, the views class the prior build's public symbol names it after. + /// For a class table, the views class whose name its metadata holds in the prior build. pub class: Option, /// For a function a browser command runs first, the command's public id. pub command: Option, diff --git a/rivet/platform/windows/src/row_watch.rs b/rivet/platform/windows/src/row_watch.rs index 842f084..86e7c19 100644 --- a/rivet/platform/windows/src/row_watch.rs +++ b/rivet/platform/windows/src/row_watch.rs @@ -161,7 +161,7 @@ pub fn brave_candidates(releases: &Value) -> Vec { /// What still needs a row, most urgent first: what people have now, then what stable is about to /// serve, then beta, which brings the next milestone weeks ahead and gives a person time to review -/// what symbols cannot show. A version older than every row and not served is history, not news. +/// what the generator cannot read. A version older than every row and not served is history, not news. pub fn pending(candidates: Vec, known: &BTreeSet<(String, String)>) -> Vec { let mut newest_known: BTreeMap<&str, Vec> = BTreeMap::new(); for (browser, version) in known { diff --git a/rivet/runtime/windows/rows/table.json b/rivet/runtime/windows/rows/table.json index 41d56c3..90ba91d 100644 --- a/rivet/runtime/windows/rows/table.json +++ b/rivet/runtime/windows/rows/table.json @@ -2604,17 +2604,5 @@ } ], "schema": 1, - "sequence": 0, - "symbols": { - "Brave 156.1.98.63": "5723B770F8DCB2794C4C44205044422E1", - "Brave 157.1.99.55": "22DC58117C04ED6E4C4C44205044422E1", - "Google Chrome 156.0.8078.74": "713E6CA96EBDD5814C4C44205044422E1", - "Google Chrome 156.0.8078.80": "B2C7C3B72F30D3ED4C4C44205044422E1", - "Google Chrome 156.0.8078.81": "4A4A604319CF7D794C4C44205044422E1", - "Google Chrome 156.0.8078.82": "A28166C00E1AB5384C4C44205044422E1", - "Google Chrome 157.0.8103.38": "B445A620A73B6EA94C4C44205044422E1", - "Google Chrome 157.0.8103.39": "037147ED9738B0F84C4C44205044422E1", - "Microsoft Edge 156.0.4314.50": "F44CB0836ADF26834C4C44205044422E1", - "Microsoft Edge 156.0.4314.58": "03775A411C2857584C4C44205044422E1" - } + "sequence": 0 } diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index 1f70e64..3b4e8cd 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -1501,36 +1501,6 @@ fn fr12_edge_58_and_whale_57_record_the_page_view_that_moves_below_the_bar() { } } -#[cfg(windows)] -#[test] -fn nfr6_newest_row_of_each_ported_browser_has_its_symbol_key() { - // The row job ports a new build from the newest row of its browser, read through that row's - // public symbols. A newest row without its symbol key stops every later row of the browser. - let table: serde_json::Value = - serde_json::from_str(CHECKED_IN).expect("the checked-in table is JSON"); - let mut rows = crate::compiled_rows(); - rows.extend(table["rows"].as_array().cloned().unwrap_or_default()); - let version_of = |row: &serde_json::Value| -> Vec { - row["build"]["version"] - .as_array() - .map(|parts| parts.iter().filter_map(serde_json::Value::as_u64).collect()) - .unwrap_or_default() - }; - for browser in ["Google Chrome", "Microsoft Edge", "Brave"] { - let newest = rows - .iter() - .filter(|row| row["build"]["browser"] == browser && !row["frame"].is_null()) - .max_by_key(|row| version_of(row)) - .unwrap_or_else(|| panic!("{browser} has a row")); - let version: Vec = version_of(newest).iter().map(u64::to_string).collect(); - let key = format!("{browser} {}", version.join(".")); - assert!( - table["symbols"][key.as_str()].is_string(), - "{key} has no symbol key in rows/table.json" - ); - } -} - #[cfg(windows)] #[test] fn nfr6_recipes_read_every_row_value_they_cover_again_from_its_own_module() { diff --git a/scripts/check.sh b/scripts/check.sh index 34c08c3..0f97327 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -15,6 +15,7 @@ tests=( scripts/tests/installer.test.sh scripts/tests/windows-features.test.sh scripts/tests/paths.test.sh + scripts/tests/no-pdb.test.sh scripts/tests/layers.test.sh scripts/tests/test-desktop.test.sh scripts/tests/test-window-placement.test.sh diff --git a/scripts/tests/browser-rows.test.sh b/scripts/tests/browser-rows.test.sh index 2e38aa8..111771d 100755 --- a/scripts/tests/browser-rows.test.sh +++ b/scripts/tests/browser-rows.test.sh @@ -25,10 +25,10 @@ expect "proves a row on the real browser" "windows-row-proof.ps1" expect "does not publish a row that needs review" "steps.made.outputs.for_review == 'false'" expect "publishes a signed table" "table-sign" expect "signs with a secret" "secrets.RIVET_TABLE_SIGNING_KEY" -expect "makes a row from fingerprints when the new PDB is missing" "chrome-builds.exe find" -expect "tells a missing PDB from a failed download" "catch [System.IO.FileNotFoundException]" -expect "compares a row made without its PDB once the PDB appears" "chrome-builds.exe pdb-check" -expect "reports a row that differs from its PDB" "Row differs from its PDB" +expect "makes each row from the prior row and the prior build's module" 'chrome-builds.exe find "$temp/prior.json" $env:PRIOR_MODULE' +expect "fingerprints a new row from its own module" "chrome-builds.exe fingerprint" +expect "scores the generator against verified rows" "scripts/tests/row-score.ps1" +expect "a score run makes no row" "github.event.inputs.score == ''" expect "a trial run publishes nothing" "needs.row.result != 'skipped' && !inputs.trial" expect "a trial run proposes nothing" "steps.made.outputs.for_review == 'true' && !inputs.trial" @@ -36,7 +36,7 @@ if [[ -e "$repo_root/.github/workflows/chrome-support.yml" ]]; then echo "chrome-support.yml covers Chrome only and is replaced by browser-rows.yml" >&2 failed=1 fi -for script in fetch-browser fetch-symbols; do +for script in fetch-browser; do if [[ ! -f "$repo_root/.github/scripts/rows/$script.ps1" ]]; then echo "the job needs .github/scripts/rows/$script.ps1" >&2 failed=1 diff --git a/scripts/tests/no-pdb.test.sh b/scripts/tests/no-pdb.test.sh new file mode 100755 index 0000000..2124383 --- /dev/null +++ b/scripts/tests/no-pdb.test.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Fails if code, scripts or workflows download or read a browser's debug symbols. Rivet and its row +# generator make every row from the verified prior row, its fingerprints and the two builds' +# modules: a maker can ship a build long before its symbols appear, or never publish them, so +# nothing may wait on them. The rows already verified with symbols stay as the starting point. +set -uo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" + +# Searches the tracked code, scripts and workflows. A search that cannot run fails, so a broken +# search never passes as a clean one. +search() { + local found status + found="$(git grep -inIE -e "$1" -- rivet scripts .github ':!scripts/tests/no-pdb.test.sh')" + status=$? + if (( status > 1 )); then + echo "error: git grep could not search for $1" >&2 + return 2 + fi + printf '%s' "$found" +} + +# A symbol server, the variable that names one, or the path a PDB is asked for by. +servers='symsrv|msdl\.microsoft\.com|brave-symbols|symbols\.mozilla|/download/symbols|_NT_SYMBOL_PATH|srv\*|\.pdb/|\.dll\.pdb' +found="$(search "$servers")" || exit 2 +if [[ -n "$found" ]]; then + echo "error: no code, script or workflow may name a symbol server:" >&2 + echo "$found" >&2 + exit 1 +fi +echo "ok no code, script or workflow names a symbol server" + +# DbgHelp and DIA read PDBs, a CodeView record names the PDB of a module, and the `pdb` crate parses +# one. Any of them, or a file named after a PDB, is code that reads symbols. +readers='dbghelp|SymInitialize|SymLoadModule|SymEnumSymbols|SymFromName|SymFromAddr|SymSetOptions|msdia|IDiaDataSource|RSDS|CodeView|pdb_key|pdb-key|(^|[^a-z0-9_])pdb([^a-z0-9_]|$)|fetch-symbols' +found="$(search "$readers")" || exit 2 +if [[ -n "$found" ]]; then + echo "error: no code, script or workflow may read a PDB:" >&2 + echo "$found" >&2 + exit 1 +fi +echo "ok no code, script or workflow reads a PDB" diff --git a/scripts/tests/row-port.ps1 b/scripts/tests/row-port.ps1 deleted file mode 100644 index d074f1c..0000000 --- a/scripts/tests/row-port.ps1 +++ /dev/null @@ -1,62 +0,0 @@ -param( - [Parameter(Mandatory = $true)][string]$Rows, - [Parameter(Mandatory = $true)][string]$Generator, - [Parameter(Mandatory = $true)][string]$Symbols -) - -$ErrorActionPreference = 'Stop' -# Proves the row generator on builds people already verified: a row made from the prior build must -# hold the same addresses as the row that was checked by hand. Fields the prior row did not have -# yet are named, since a generator cannot add a feature. Needs the PDBs and an installed browser, so -# a machine without them skips the pair it lacks. -$work = Join-Path ([IO.Path]::GetTempPath()) "rivet-row-port-$PID" -New-Item -ItemType Directory -Force $work | Out-Null - -function Flatten($value, $path, $out) { - if ($value -is [System.Management.Automation.PSCustomObject]) { - foreach ($item in $value.PSObject.Properties) { Flatten $item.Value "$path.$($item.Name)" $out } - } elseif ($value -is [System.Collections.IEnumerable] -and $value -isnot [string]) { - $index = 0 - foreach ($item in $value) { Flatten $item "$path[$index]" $out; $index++ } - } else { - $out[$path] = $value - } -} - -$failed = $false -foreach ($pair in @( - @{ Browser = 'Google Chrome'; Prior = '156.0.8078.48'; New = '156.0.8078.74'; Pdbs = 'chrome-symbols'; Module = 'C:\Program Files\Google\Chrome\Application\156.0.8078.74\chrome.dll' }, - @{ Browser = 'Brave'; Prior = '156.1.98.62'; New = '156.1.98.63'; Pdbs = 'brave-symbols'; Module = 'C:\Program Files\BraveSoftware\Brave-Browser\Application\156.1.98.63\chrome.dll' } -)) { - $old = Join-Path $Symbols "$($pair.Pdbs)\$($pair.Prior)\chrome.dll.pdb" - $new = Join-Path $Symbols "$($pair.Pdbs)\$($pair.New)\chrome.dll.pdb" - if (-not ((Test-Path $old) -and (Test-Path $new) -and (Test-Path $pair.Module))) { - "skip $($pair.Browser) $($pair.New): no symbols or module here" - continue - } - $priorRow = Join-Path $work "prior.json" - $made = Join-Path $work "made.json" - $report = Join-Path $work "report.json" - & $Rows row $pair.Browser $pair.Prior | Set-Content -Encoding utf8 $priorRow - $truth = & $Rows row $pair.Browser $pair.New | ConvertFrom-Json - & $Generator port $priorRow $old $new $pair.Module $pair.New $made $report - $review = (Get-Content -Raw $report | ConvertFrom-Json).review - if ($review.Count -gt 0) { "$($pair.Browser): for review: $review"; $failed = $true } - $a = @{}; $b = @{} - Flatten (Get-Content -Raw $made | ConvertFrom-Json) '' $a - Flatten $truth '' $b - $count = 0 - foreach ($path in $b.Keys) { - if ("$($b[$path])" -notmatch '^0x') { continue } - $count++ - if ($a[$path] -ne $b[$path]) { - if ($a[$path] -eq '0x7fff0000' -or $null -eq $a[$path]) { "$($pair.Browser): $path was added by hand after the prior row"; continue } - "$($pair.Browser): $path made $($a[$path]), verified $($b[$path])" - $failed = $true - } - } - "$($pair.Browser) $($pair.Prior) -> $($pair.New): compared $count address values" -} -Remove-Item -Recurse -Force $work -if ($failed) { throw 'NFR-3: A generated row differs from the row people verified.' } -'NFR-3: Generated rows match the verified rows.' diff --git a/scripts/tests/row-score.ps1 b/scripts/tests/row-score.ps1 new file mode 100644 index 0000000..1e1cd81 --- /dev/null +++ b/scripts/tests/row-score.ps1 @@ -0,0 +1,98 @@ +param( + # rivet-rows.exe, which prints the rows Rivet knows. + [Parameter(Mandatory = $true)][string]$Rows, + # chrome-builds.exe, the row generator. + [Parameter(Mandatory = $true)][string]$Generator, + # The checked-in table, whose rows count as verified like those built into rivet-rows. + [Parameter(Mandatory = $true)][string]$Table, + # Where the modules, rows and scores go. Removed and made again. + [Parameter(Mandatory = $true)][string]$Work, + # `browser@prior>new` pairs. Empty means the list below. + [string[]]$Pairs = @(), + # Fetches each build with .github/scripts/rows/fetch-browser.ps1. Without it, each module is + # taken from `$Modules\\\`. + [switch]$Fetch, + [string]$Modules = '' +) + +$ErrorActionPreference = 'Stop' +# Scores the row generator against answer keys: builds whose rows people verified, made from +# public symbols before Rivet stopped reading them. Each new row is made without symbols from the +# verified row of an older build, the way the row job makes rows, and compared value by value with +# the verified row of the new build. Per feature it reports values found and equal, values found +# but different, and features the made row turns off because their values were not found. +# +# A value found but different is a wrong value, which would reach people's browsers, so any fails +# this script. A feature turned off is not a failure: the runtime keeps it off. A pair whose builds +# cannot be fetched is reported and skipped, and a run that scores no pair fails, since it measured +# nothing. Nothing is published or proposed. +# +# A build newer than every verified row, such as Chrome 158 while the newest verified row is 157, +# has no answer key and cannot be scored here. +if (-not $Pairs -or $Pairs.Count -eq 0) { + $Pairs = @( + 'Google Chrome@156.0.8078.82>157.0.8103.38', + 'Google Chrome@156.0.8078.82>157.0.8103.39', + 'Google Chrome@156.0.8078.74>156.0.8078.80', + 'Microsoft Edge@156.0.4314.50>156.0.4314.58', + 'Brave@156.1.98.63>157.1.99.55' + ) +} + +if (Test-Path $Work) { Remove-Item -Recurse -Force $Work } +New-Item -ItemType Directory -Force $Work | Out-Null + +function Find-BuildModule($browser, $version) { + $dll = if ($browser -eq 'Microsoft Edge') { 'msedge.dll' } else { 'chrome.dll' } + if (-not $Fetch) { + $path = Join-Path $Modules "$browser\$version\$dll" + if (-not (Test-Path $path)) { throw "no module at $path" } + return $path + } + $out = Join-Path $Work ("browser-" + ($browser -replace ' ', '-') + "-$version") + $found = Join-Path $Work ("browser-" + ($browser -replace ' ', '-') + "-$version.txt") + if (-not (Test-Path $found)) { + & "$PSScriptRoot/../../.github/scripts/rows/fetch-browser.ps1" -Browser $browser -Version $version -Out $out -Output $found | Out-Host + } + (Get-Content $found | Where-Object { $_ -like 'module=*' } | Select-Object -First 1) -replace '^module=', '' +} + +function Get-VerifiedRow($browser, $version, $file) { + & $Rows prior $browser $version --table $Table | Set-Content -Encoding utf8 $file + if ($LASTEXITCODE -ne 0) { throw "rivet-rows has no row for $browser at or below $version" } + $row = Get-Content -Raw $file | ConvertFrom-Json + if ($row.frame.version -ne $version) { throw "$browser $version has no verified row; the nearest is $($row.frame.version)" } +} + +$scored = 0 +$wrong = 0 +$failed = @() +foreach ($pair in $Pairs) { + $browser, $versions = $pair -split '@', 2 + $prior, $new = $versions -split '>', 2 + $slug = ($browser -replace ' ', '-') + "-$prior-to-$new" + $priorRow = Join-Path $Work "$slug-prior.json" + $verified = Join-Path $Work "$slug-verified.json" + $score = Join-Path $Work "$slug-score.json" + try { + Get-VerifiedRow $browser $prior $priorRow + Get-VerifiedRow $browser $new $verified + $priorModule = Find-BuildModule $browser $prior + $module = Find-BuildModule $browser $new + } catch { + "skip ${browser} $prior -> ${new}: $_" + continue + } + & $Generator score $priorRow $priorModule $module $verified $score + switch ($LASTEXITCODE) { + 0 { $scored++ } + 5 { $scored++; $wrong++ } + default { $failed += "$browser $prior -> $new (chrome-builds exited with $LASTEXITCODE)" } + } +} + +"scored $scored of $($Pairs.Count) pairs; $wrong with a wrong value" +if ($failed.Count -gt 0) { throw "NFR-6: the generator failed on: $($failed -join '; ')" } +if ($wrong -gt 0) { throw 'NFR-6: a row made without symbols holds a value that differs from its verified row.' } +if ($scored -eq 0) { throw 'NFR-6: no pair could be scored, so nothing was measured.' } +'NFR-6: every value the generator found equals the verified row.' From d1a737caffaa39ffb23beda82e2adb5c1debb3d3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:40:05 +0000 Subject: [PATCH 10/29] Publish: develop 2a9fcd7 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_port.rs | 37 -------------------------- scripts/tests/no-pdb.test.sh | 4 ++- 2 files changed, 3 insertions(+), 38 deletions(-) diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index f656976..77306fa 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -568,43 +568,6 @@ pub(crate) fn whole_function(pe: &PeFile, address: u32) -> Option> { None } -/// Every `(address, bytes)` guard of a row. -fn collect_guards(value: &Value, guards: &mut Vec<(u32, Vec)>) { - match value { - Value::Object(object) => { - for (key, item) in object { - if let Some(bytes) = item.as_str().filter(|_| is_byte_field(key)).and_then(hex) { - let base = byte_field_address(key) - .map(|(base, _)| base.to_owned()) - .unwrap_or_else(|| { - key.trim_end_matches("_prologue") - .trim_end_matches("_bytes") - .to_owned() - }); - if let Some(address) = object - .get(&base) - .and_then(read_address) - .filter(|value| is_address(*value)) - { - guards.push((address as u32, bytes)); - } - } - collect_guards(item, guards); - } - } - Value::Array(items) => { - if let [address, Value::String(bytes)] = items.as_slice() { - if let (Some(address), Some(bytes)) = (read_address(address), hex(bytes)) { - guards.push((address as u32, bytes)); - return; - } - } - items.iter().for_each(|item| collect_guards(item, guards)); - } - _ => {} - } -} - fn is_byte_field(key: &str) -> bool { key.ends_with("_prologue") || key.ends_with("_bytes") || byte_field_address(key).is_some() } diff --git a/scripts/tests/no-pdb.test.sh b/scripts/tests/no-pdb.test.sh index 2124383..090b618 100755 --- a/scripts/tests/no-pdb.test.sh +++ b/scripts/tests/no-pdb.test.sh @@ -18,7 +18,9 @@ search() { echo "error: git grep could not search for $1" >&2 return 2 fi - printf '%s' "$found" + # The script that runs this test names it, and the name is not a reader. + printf '%s' "$found" | grep -v 'no-pdb\.test\.sh' + return 0 } # A symbol server, the variable that names one, or the path a PDB is asked for by. From 9ee4b67ec4329d6a067d53ff8226beae87985faf Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:19:46 +0000 Subject: [PATCH 11/29] Publish: develop e46e9a2 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .github/scripts/rows/fetch-browser.ps1 | 21 ++++- rivet/platform/windows/src/chrome_build.rs | 3 + rivet/platform/windows/src/row_class.rs | 91 +++++++++++++++------- 3 files changed, 86 insertions(+), 29 deletions(-) diff --git a/.github/scripts/rows/fetch-browser.ps1 b/.github/scripts/rows/fetch-browser.ps1 index 61ec9c9..ca6767d 100644 --- a/.github/scripts/rows/fetch-browser.ps1 +++ b/.github/scripts/rows/fetch-browser.ps1 @@ -60,6 +60,14 @@ function Resolve-Edge { $url = switch ($Browser) { 'Google Chrome' { Resolve-Chrome } 'Microsoft Edge' { Resolve-Edge } + 'Brave' { + # Brave's feed lists only new builds, but every release keeps its installer on GitHub under + # the tag of the version without its Chromium milestone, so an earlier build is found too. + if ($Download) { $Download } else { + $tag = 'v' + (($Version -split '\.', 2)[1]) + "https://github.com/brave/brave-browser/releases/download/$tag/BraveBrowserStandaloneSilentSetup.exe" + } + } default { if (-not $Download) { throw "The feed names no installer for $Browser $Version yet." } $Download @@ -106,7 +114,18 @@ if ($Browser -eq 'Brave') { } throw "Brave's installer exited with 0, but no place holds brave.exe and $Version\chrome.dll after 10 minutes. Under BraveSoftware: $(@($seen) -join '; ')" } - $unpacked = $installed + # The files are copied out and Brave is removed again, so a second build, such as the one + # before it, can be installed on the same runner. + $unpacked = Join-Path $Out 'files' + New-Item -ItemType Directory -Force $unpacked | Out-Null + Copy-Item $installed $unpacked -Recurse -Force + $remover = Join-Path $installed "$Version\Installer\setup.exe" + $level = if ($installed -like "$env:LOCALAPPDATA*") { @() } else { @('--system-level') } + if (Test-Path $remover) { + Start-Process $remover -ArgumentList (@('--uninstall', '--force-uninstall') + $level) -Wait | Out-Null + } + Remove-Item (Split-Path $installed -Parent) -Recurse -Force -ErrorAction SilentlyContinue + if (Test-Path $installed) { throw "Brave $Version could not be removed from $installed after its files were copied" } } else { 7z x $package "-o$unpacked" -y | Out-Null if ($LASTEXITCODE -ne 0) { throw "7-Zip could not unpack $url" } diff --git a/rivet/platform/windows/src/chrome_build.rs b/rivet/platform/windows/src/chrome_build.rs index 5805740..158eb82 100644 --- a/rivet/platform/windows/src/chrome_build.rs +++ b/rivet/platform/windows/src/chrome_build.rs @@ -67,6 +67,8 @@ pub struct PeFile<'a> { sections: Vec<(u32, u32, u32)>, code_sections: Vec<(u32, u32)>, exception_directory: (u32, u32), + /// What `row_class` reads from the whole code once, kept for its later questions. + pub(crate) code_index: std::cell::OnceCell, } fn u16_at(bytes: &[u8], offset: usize) -> Option { @@ -136,6 +138,7 @@ impl<'a> PeFile<'a> { sections, code_sections, exception_directory, + code_index: std::cell::OnceCell::new(), }) } diff --git a/rivet/platform/windows/src/row_class.rs b/rivet/platform/windows/src/row_class.rs index c696e40..93b215b 100644 --- a/rivet/platform/windows/src/row_class.rs +++ b/rivet/platform/windows/src/row_class.rs @@ -100,43 +100,78 @@ fn rip_use(bytes: &[u8], rva: u32) -> Option { }) } -/// Every RIP-relative `lea` or `mov` in the code whose target is one of `targets`. -fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { - let mut found = Vec::new(); - for (base, bytes, is_code) in pe.sections() { - if !is_code { - continue; - } - for at in 0..bytes.len().saturating_sub(7) { - if let Some(found_use) = rip_use(&bytes[at..at + 7], base + at as u32) { - if targets.contains(&found_use.target) { - found.push(found_use); +/// Every RIP-relative `lea` and `mov` and every direct `call` and `jmp` of a module's code, sorted +/// by what they point at. The code of a browser is hundreds of megabytes and each class name asks +/// about it many times, so it is read once and each question is a search in the sorted lists. +#[derive(Debug, Default)] +pub struct CodeIndex { + uses: Vec, + /// (target, site, whether it is a jump). + branches: Vec<(u32, u32, bool)>, +} + +impl CodeIndex { + fn of<'p>(pe: &'p PeFile<'_>) -> &'p CodeIndex { + pe.code_index.get_or_init(|| { + let mut index = CodeIndex::default(); + for (base, bytes, is_code) in pe.sections() { + if !is_code { + continue; + } + for at in 0..bytes.len() { + let rva = base + at as u32; + if let Some(found) = bytes.get(at..at + 7).and_then(|raw| rip_use(raw, rva)) { + index.uses.push(found); + } + if matches!(bytes[at], 0xE8 | 0xE9) { + if let Some(raw) = bytes.get(at + 1..at + 5) { + let rel = i32::from_le_bytes(raw.try_into().expect("four bytes")); + let target = i64::from(rva) + 5 + i64::from(rel); + // Only a branch into code can be one into a function. + if let Some(target) = + u32::try_from(target).ok().filter(|target| pe.is_code(*target)) + { + index.branches.push((target, rva, bytes[at] == 0xE9)); + } + } + } } } - } + index.uses.sort_unstable_by_key(|each| (each.target, each.at)); + index.branches.sort_unstable(); + index + }) + } +} + +/// Every RIP-relative `lea` or `mov` in the code whose target is one of `targets`, in the order +/// of where they are. +fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { + let index = CodeIndex::of(pe); + let mut found = Vec::new(); + for target in targets { + let from = index.uses.partition_point(|each| each.target < *target); + found.extend(index.uses[from..].iter().take_while(|each| each.target == *target).copied()); } + found.sort_unstable_by_key(|each: &RipUse| each.at); found } -/// Every direct `call` or `jmp` into one of `targets`, as (site, whether it is a jump). +/// Every direct `call` or `jmp` into one of `targets`, as (site, whether it is a jump), in the +/// order of where they are. fn branches_into(pe: &PeFile, targets: &BTreeSet) -> Vec<(u32, bool)> { + let index = CodeIndex::of(pe); let mut found = Vec::new(); - for (base, bytes, is_code) in pe.sections() { - if !is_code { - continue; - } - for at in 0..bytes.len().saturating_sub(5) { - if !matches!(bytes[at], 0xE8 | 0xE9) { - continue; - } - let rel = i32::from_le_bytes(bytes[at + 1..at + 5].try_into().expect("in range")); - let site = base + at as u32; - let target = i64::from(site) + 5 + i64::from(rel); - if u32::try_from(target).is_ok_and(|target| targets.contains(&target)) { - found.push((site, bytes[at] == 0xE9)); - } - } + for target in targets { + let from = index.branches.partition_point(|each| each.0 < *target); + found.extend( + index.branches[from..] + .iter() + .take_while(|each| each.0 == *target) + .map(|each| (each.1, each.2)), + ); } + found.sort_unstable(); found } From bd644213571afa3daa1d1e79d0b0957e14e25d25 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:30:52 +0000 Subject: [PATCH 12/29] Publish: develop aaca078 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_class.rs | 144 ++++++++++++++++++------ 1 file changed, 111 insertions(+), 33 deletions(-) diff --git a/rivet/platform/windows/src/row_class.rs b/rivet/platform/windows/src/row_class.rs index 93b215b..25209eb 100644 --- a/rivet/platform/windows/src/row_class.rs +++ b/rivet/platform/windows/src/row_class.rs @@ -48,8 +48,15 @@ pub fn load_target(pe: &PeFile, at: u32) -> Option<(u32, bool)> { code_at = u32::try_from(i64::from(code_at) + skip as i64 + 5 + i64::from(rel)).ok()?; } let code = pe.read(code_at, 128)?; - let at = (0..code.len() - 7).find(|&i| { - code[i] == 0x48 && matches!(code[i + 1], 0x8D | 0x8B) && code[i + 2] == 0x05 + // A function with a guarded stack frame first loads the stack cookie and mixes it with the + // stack pointer (`xor rax, rsp`). That load is not the function's result. + let at = (0..code.len() - 10).find(|&i| { + // Any 64-bit register: a function with a stack frame keeps its result in one it saved + // and moves it to `rax` at the end. + code[i] & 0xFB == 0x48 + && matches!(code[i + 1], 0x8D | 0x8B) + && code[i + 2] & 0xC7 == 0x05 + && code[i + 7..i + 10] != [0x48, 0x31, 0xE0] })?; let rel = i32::from_le_bytes(code[at + 3..at + 7].try_into().ok()?); let target = u32::try_from(i64::from(code_at) + at as i64 + 7 + i64::from(rel)).ok()?; @@ -218,7 +225,7 @@ fn getters(pe: &PeFile, ranges: &BTreeMap, found: (u32, bool)) -> BTre let loads = rip_uses(pe, &BTreeSet::from([found.0])); let mut getters: BTreeSet = loads .iter() - .filter(|each| each.register == 0 && each.word == found.1) + .filter(|each| each.word == found.1) .filter_map(|each| enclosing(ranges, each.at)) .filter(|function| load_target(pe, *function) == Some(found)) .collect(); @@ -359,8 +366,38 @@ fn stores_in(pe: &PeFile, start: u32, end: u32) -> Vec { stores } -/// The table each constructor that writes `provider` writes at the start of the same object. -fn first_tables(pe: &PeFile, ranges: &BTreeMap, provider: u32) -> BTreeSet { +/// The tables a constructor leaves in the object it writes `around` into, in the order of where +/// they go. A constructor of a derived class writes over the tables of its bases, so the last +/// store at each place counts. +fn object_tables(stores: &[Store], around: &Store) -> Vec<(i64, u32)> { + let mut last: BTreeMap = BTreeMap::new(); + for store in stores.iter().filter(|store| store.base == around.base) { + last.insert(store.offset, store.table); + } + // Without the table at the object's start the places cannot be counted. + if !last.contains_key(&0) { + return Vec::new(); + } + last.into_iter().collect() +} + +/// A class name and which of its object's tables is meant: `BrowserView` is the table at the start +/// of the object, `BrowserView#6` the seventh in the order of where they go. A class with several +/// bases has a table for each, and the order of the bases is the class's own declaration. +fn name_and_order(name: &str) -> (&str, usize) { + match name.split_once('#') { + Some((bare, order)) => (bare, order.parse().unwrap_or(usize::MAX)), + None => (name, 0), + } +} + +/// The table each constructor that writes `provider` leaves at place `order` of the same object. +fn tables_beside( + pe: &PeFile, + ranges: &BTreeMap, + provider: u32, + order: usize, +) -> BTreeSet { let writers: BTreeSet = rip_uses(pe, &BTreeSet::from([provider])) .iter() .filter(|each| !each.word) @@ -370,32 +407,33 @@ fn first_tables(pe: &PeFile, ranges: &BTreeMap, provider: u32) -> BTre for writer in writers { let stores = stores_in(pe, writer, ranges[&writer]); for written in stores.iter().filter(|store| store.table == provider) { - let first = stores - .iter() - .filter(|store| { - store.base == written.base && store.offset == 0 && store.table != provider - }) - .min_by_key(|store| store.index.abs_diff(written.index)); - if let Some(first) = first { - found.insert(first.table); + let tables = object_tables(&stores, written); + // The provider's own table must be what the constructor leaves at its place. + if !tables.iter().any(|(at, table)| *at == written.offset && *table == provider) { + continue; + } + if let Some((_, table)) = tables.get(order) { + found.insert(*table); } } } found } -/// The class tables of the views class `name` in `pe`, each the table at the start of its -/// objects. More than one means the name does not tell one class table, and the caller takes none. +/// The class tables of the views class `name` in `pe`, each the table at the place the name gives +/// in its objects. More than one means the name does not tell one class table, and the caller +/// takes none. pub fn class_tables(pe: &PeFile, name: &str) -> BTreeSet { + let (bare, order) = name_and_order(name); let ranges = pe.function_ranges(); let mut found = BTreeSet::new(); - for each in statics_of(pe, &ranges, name) { + for each in statics_of(pe, &ranges, bare) { let getters = getters(pe, &ranges, each); - if getters.is_empty() { + if getters.is_empty() || getters.len() > CALLERS_MOST { continue; } for provider in tables_holding(pe, &getters) { - found.extend(first_tables(pe, &ranges, provider)); + found.extend(tables_beside(pe, &ranges, provider, order)); } } found @@ -461,27 +499,32 @@ fn body_of(pe: &PeFile, ranges: &BTreeMap, start: u32) -> (Vec, V (loads, callees) } -/// The metadata statics a class table's objects reach: each constructor that writes the table at -/// the start of an object also writes other tables into it, and the second slot of the -/// `ui::metadata::MetaDataProvider` table among them returns the class's static, as `getters` reads. -fn statics_of_table(pe: &PeFile, ranges: &BTreeMap, table: u32) -> BTreeSet<(u32, bool)> { +/// The metadata statics a class table's objects reach, and the table's place among the object's +/// tables: each constructor that writes the table into an object also writes other tables into it, +/// and the second slot of the `ui::metadata::MetaDataProvider` table among them returns the class's +/// static, as `getters` reads. Constructors that put the table at different places give no place. +fn statics_of_table( + pe: &PeFile, + ranges: &BTreeMap, + table: u32, +) -> (BTreeSet<(u32, bool)>, Option) { let writers: BTreeSet = rip_uses(pe, &BTreeSet::from([table])) .iter() .filter(|each| !each.word) .filter_map(|each| enclosing(ranges, each.at)) .collect(); let mut found = BTreeSet::new(); + let mut orders = BTreeSet::new(); for writer in writers { let stores = stores_in(pe, writer, ranges[&writer]); - for first in stores - .iter() - .filter(|store| store.table == table && store.offset == 0) - { - for other in stores.iter().filter(|store| { - store.base == first.base && store.offset != 0 && store.table != table - }) { - let Some(getter) = pe.pointer_rva(other.table + 8).filter(|at| pe.is_code(*at)) - else { + for written in stores.iter().filter(|store| store.table == table) { + let tables = object_tables(&stores, written); + let Some(order) = tables.iter().position(|(_, each)| *each == table) else { + continue; + }; + orders.insert(order); + for (_, other) in tables.iter().filter(|(_, other)| *other != table) { + let Some(getter) = pe.pointer_rva(other + 8).filter(|at| pe.is_code(*at)) else { continue; }; if let Some(each) = load_target(pe, getter).filter(|(at, _)| !pe.is_code(*at)) { @@ -490,7 +533,8 @@ fn statics_of_table(pe: &PeFile, ranges: &BTreeMap, table: u32) -> BTr } } } - found + let order = (orders.len() == 1).then(|| orders.into_iter().next()).flatten(); + (found, order) } /// The names the code that fills a metadata static loads, nearest first: the texts that the @@ -534,7 +578,13 @@ fn names_of_static( pub fn class_name_of_table(pe: &PeFile, table: u32) -> Option { let ranges = pe.function_ranges(); let mut by_depth: Vec> = Vec::new(); - for each in statics_of_table(pe, &ranges, table) { + let (statics, order) = statics_of_table(pe, &ranges, table); + let order = order?; + let placed = |name: &str| match order { + 0 => name.to_owned(), + order => format!("{name}#{order}"), + }; + for each in statics { for (depth, names) in names_of_static(pe, &ranges, each).into_iter().enumerate() { if by_depth.len() <= depth { by_depth.resize(depth + 1, Vec::new()); @@ -549,6 +599,7 @@ pub fn class_name_of_table(pe: &PeFile, table: u32) -> Option { if tried.len() >= NAMES_MOST { return None; } + let name = placed(&name); if tried.insert(name.clone()) && class_tables(pe, &name) == BTreeSet::from([table]) { confirmed.insert(name); } @@ -739,4 +790,31 @@ mod tests { let pe = PeFile::parse(&code).unwrap(); assert_eq!(identifier_at(&pe, 0x2100), None); } + #[test] + fn nfr6_a_table_past_the_start_of_its_object_is_named_with_its_place() { + // A class with several bases has a table for each. The row's table of `BrowserView` is the + // seventh in Edge 156, and a name without the place would give the first. + assert_eq!(name_and_order("BrowserView#6"), ("BrowserView", 6)); + assert_eq!(name_and_order("BrowserView"), ("BrowserView", 0)); + let store = |table, offset| Store { index: 0, table, base: 6, offset }; + let stores = [store(0x10, 0), store(0x20, 8), store(0x30, 0x1f8), store(0x11, 0)]; + // A derived constructor's later store at a place replaces the base's. + assert_eq!(object_tables(&stores, &stores[1]), [(0, 0x11), (8, 0x20), (0x1f8, 0x30)]); + // An object whose first table is not seen gives no places. + assert!(object_tables(&stores[1..3], &stores[1]).is_empty()); + } + + #[test] + fn nfr6_the_stack_cookie_is_not_a_functions_result() { + // sub rsp; mov rax, [rip+cookie]; xor rax, rsp; mov [rsp+0x28], rax; mov rsi, [rip+static] + let mut code = vec![0x48, 0x83, 0xEC, 0x30]; + code.extend([0x48, 0x8B, 0x05, 0x00, 0x10, 0x00, 0x00, 0x48, 0x31, 0xE0]); + code.extend([0x48, 0x89, 0x44, 0x24, 0x28]); + code.extend([0x48, 0x8B, 0x35, 0x00, 0x20, 0x00, 0x00]); + code.resize(160, 0xCC); + let bytes = module(&[(0x1000, code)], &[(0x1000, 0x10a0)]); + let pe = PeFile::parse(&bytes).unwrap(); + assert_eq!(load_target(&pe, 0x1000), Some((0x1000 + 26 + 0x2000, true))); + } + } From 48999e2823a49b0df2cebf121a300d50f02d27e2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:37:00 +0000 Subject: [PATCH 13/29] Publish: develop b297ec3 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 28 +++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index dd9d19a..25ee0a1 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -1029,6 +1029,10 @@ pub fn resolve( Kind::Function => { if let Some(place) = followed.get(target) { answers.push((Method::CallsInto, place)); + // The call is a fact of the caller's code and the fingerprint one of the + // bytes at the place, so a place both give has two kinds of evidence. + let given = BTreeSet::from([place]); + answers.extend(fingerprint_agrees(&given, want.candidates.as_deref())); } let calls = &expected[&target]; let candidates: Vec = match &want.candidates { @@ -1467,6 +1471,10 @@ pub(crate) mod tests { } fn run(new_bytes: &[u8], known_table: bool) -> Resolution { + run_with(new_bytes, known_table, Some(NEW_TARGETS.to_vec())) + } + + fn run_with(new_bytes: &[u8], known_table: bool, candidates: Option>) -> Resolution { let old_bytes = old_module(); let old = PeFile::parse(&old_bytes).unwrap(); let new = PeFile::parse(new_bytes).unwrap(); @@ -1478,7 +1486,7 @@ pub(crate) mod tests { OLD_TARGET, Wanted { kind: Kind::Function, - candidates: Some(NEW_TARGETS.to_vec()), + candidates, class: None, command: None, loose: Vec::new(), @@ -1540,10 +1548,26 @@ pub(crate) mod tests { #[test] fn nfr6_one_method_alone_does_not_place_a_function() { - let resolution = run(&new_module(NEW_TARGETS[0]), false); + // The fingerprint matched no place, so the paired call site stands alone. + let resolution = run_with(&new_module(NEW_TARGETS[0]), false, None); assert!(resolution.places.is_empty()); let reason = &resolution.reasons[&OLD_TARGET]; assert!(reason.starts_with("only calls into it found it"), "{reason}"); + // A place outside the fingerprint's places gets no agreement from it either. + let resolution = run_with(&new_module(NEW_TARGETS[0]), false, Some(vec![NEW_TARGETS[1]])); + assert!(resolution.places.is_empty(), "{:?}", resolution.settled); + } + + #[test] + fn nfr6_a_paired_call_site_and_the_fingerprint_place_a_function_together() { + // Edge 156 has functions whose bytes match in two or three places. The call a known + // function makes is a fact of the caller, the bytes one of the place, and they agree. + let resolution = run(&new_module(NEW_TARGETS[0]), false); + assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); + assert_eq!( + resolution.settled, + ["0x101100 -> 0x103100 by calls into it and its fingerprint"] + ); } const VIEW_TARGET: u32 = 0x105000; From 51b1e208a6e0575e1afe18dbf7f0861724e30286 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:43:51 +0000 Subject: [PATCH 14/29] Publish: develop 692efb2 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 81 +++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index 25ee0a1..c50d3e9 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -56,6 +56,8 @@ const FOLLOW_LIMIT: usize = 4000; /// How many slots of a class table are read at most. const TABLE_SLOTS: u32 = 512; /// How many slots of a class table are compared to tell one table from another. +/// How many slots a table must share with a known one before the sharing tells anything. +const SIBLING_LEAST: u32 = 8; const TABLE_SEEN: u32 = 0x80; /// How many slots on each side of a slot are compared to line two tables up. const ALIGN_REACH: u32 = 6; @@ -648,6 +650,29 @@ fn by_slots( passing } +/// How many of a table's first slots hold the very function another table of the same build holds +/// in that slot. Classes that share a base share the base's functions they do not replace. +fn shared_slots(pe: &PeFile, table: u32, other: u32) -> u32 { + (0..TABLE_SEEN) + .map_while(|slot| { + let slot = i64::from(slot); + Some((entry(pe, table, slot)?, entry(pe, other, slot)?)) + }) + .filter(|(left, right)| left == right) + .count() as u32 +} + +/// Whether `candidate` stands to a table known in both builds as `target` did in the prior build: +/// it shares about as many inherited slots with it. What a class takes from its bases is a fact of +/// the tables apart from the class's name, so it checks the table a name gives. +fn by_sibling(old: &Side, new: &Side, pairs: &[(u32, u32)], target: u32, candidate: u32) -> bool { + pairs.iter().filter(|(from, _)| *from != target).any(|(from, to)| { + let before = shared_slots(old.pe, target, *from); + let after = shared_slots(new.pe, candidate, *to); + before >= SIBLING_LEAST && after * 10 >= before * 8 && after * 8 <= before * 10 + }) +} + /// Tables of the new build that hold, near the same slot, a function the old table holds and /// whose place is known. fn table_candidates(old: &Side, new: &Side, known: &BTreeMap, target: u32) -> Vec { @@ -772,6 +797,7 @@ pub enum Method { SlotShift, Command, KnownCaller, + Sibling, } impl fmt::Display for Method { @@ -788,6 +814,7 @@ impl fmt::Display for Method { Method::SlotShift => "its slot shift", Method::Command => "its command id", Method::KnownCaller => "a known caller", + Method::Sibling => "the slots it shares with a known table", }) } } @@ -1104,6 +1131,9 @@ pub fn resolve( let mut slots = by_slots(&old, &new, &known, target, &candidates); if let Some(place) = by_class.get(&target).copied() { answers.push((Method::ClassName, place)); + if by_sibling(&old, &new, &table_pairs, target, place) { + answers.push((Method::Sibling, place)); + } let given = BTreeSet::from([place]); answers.extend(fingerprint_agrees(&given, want.candidates.as_deref())); // Several tables holding the same slots is no answer of their own; the @@ -1117,6 +1147,28 @@ pub fn resolve( } } } + // A function may start with a jump over a few bytes to its body, and the exception + // table then lists the body as a start of its own. A method that names the body means + // the function another method names by its real start. + let starts: Vec = answers.iter().map(|(_, place)| *place).collect(); + for (_, place) in &mut answers { + let start = starts.iter().copied().find(|start| { + *start < *place + && *place - *start <= 16 + && new.pe.read(*start, 5).is_some_and(|head| { + head[0] == 0xE9 + && i64::from(*start) + + 5 + + i64::from(i32::from_le_bytes( + head[1..5].try_into().expect("four bytes"), + )) + == i64::from(*place) + }) + }); + if let Some(start) = start { + *place = start; + } + } match decide(&answers, want.candidates.as_deref()) { Ok((place, methods)) => { known.insert(target, place); @@ -1734,4 +1786,33 @@ pub(crate) mod tests { assert_eq!(methods.len(), 2); assert_eq!(decide(&[], None).unwrap_err(), "no method found it"); } + #[test] + fn nfr6_a_table_a_class_name_gives_is_checked_by_the_slots_it_shares_with_a_known_table() { + // Two classes of one base hold the base's functions in the same slots. Edge 157's caption + // button table was named by its class, and what it shares with the frame's table checks it. + let functions: Vec = (0..12u32).map(|n| 0x101400 + 0x10 * n).collect(); + let mut parts: Vec<(u32, Vec)> = + functions.iter().enumerate().map(|(n, at)| (*at, small(n as u8))).collect(); + let mut own = functions.clone(); + own[10] = 0x101600; + own[11] = 0x101610; + parts.push((0x101600, small(40))); + parts.push((0x101610, small(41))); + // A table of other functions throughout shares nothing. + let other: Vec = (0..12u32).map(|n| 0x101700 + 0x10 * n).collect(); + parts.extend(other.iter().enumerate().map(|(n, at)| (*at, small(50 + n as u8)))); + parts.push((0x200100, table(&functions))); + parts.push((0x200300, table(&own))); + parts.push((0x200500, table(&other))); + let bytes = module(&parts, &[]); + let pe = PeFile::parse(&bytes).unwrap(); + assert_eq!(shared_slots(&pe, 0x200300, 0x200100), 10); + let (old, new) = (Side::new(&pe), Side::new(&pe)); + let pairs = [(0x200100, 0x200100)]; + assert!(by_sibling(&old, &new, &pairs, 0x200300, 0x200300)); + assert!(!by_sibling(&old, &new, &pairs, 0x200300, 0x200500)); + // The known table itself is no check of its own place. + assert!(!by_sibling(&old, &new, &pairs, 0x200100, 0x200100)); + } + } From 1a20f5611fd3cd458c3542e9a86c0538a5e50efa Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:31:42 +0000 Subject: [PATCH 15/29] Publish: develop 7aaed30 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 28 ++--------------------- 1 file changed, 2 insertions(+), 26 deletions(-) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index c50d3e9..72b3d26 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -1056,10 +1056,6 @@ pub fn resolve( Kind::Function => { if let Some(place) = followed.get(target) { answers.push((Method::CallsInto, place)); - // The call is a fact of the caller's code and the fingerprint one of the - // bytes at the place, so a place both give has two kinds of evidence. - let given = BTreeSet::from([place]); - answers.extend(fingerprint_agrees(&given, want.candidates.as_deref())); } let calls = &expected[&target]; let candidates: Vec = match &want.candidates { @@ -1523,10 +1519,6 @@ pub(crate) mod tests { } fn run(new_bytes: &[u8], known_table: bool) -> Resolution { - run_with(new_bytes, known_table, Some(NEW_TARGETS.to_vec())) - } - - fn run_with(new_bytes: &[u8], known_table: bool, candidates: Option>) -> Resolution { let old_bytes = old_module(); let old = PeFile::parse(&old_bytes).unwrap(); let new = PeFile::parse(new_bytes).unwrap(); @@ -1538,7 +1530,7 @@ pub(crate) mod tests { OLD_TARGET, Wanted { kind: Kind::Function, - candidates, + candidates: Some(NEW_TARGETS.to_vec()), class: None, command: None, loose: Vec::new(), @@ -1600,26 +1592,10 @@ pub(crate) mod tests { #[test] fn nfr6_one_method_alone_does_not_place_a_function() { - // The fingerprint matched no place, so the paired call site stands alone. - let resolution = run_with(&new_module(NEW_TARGETS[0]), false, None); + let resolution = run(&new_module(NEW_TARGETS[0]), false); assert!(resolution.places.is_empty()); let reason = &resolution.reasons[&OLD_TARGET]; assert!(reason.starts_with("only calls into it found it"), "{reason}"); - // A place outside the fingerprint's places gets no agreement from it either. - let resolution = run_with(&new_module(NEW_TARGETS[0]), false, Some(vec![NEW_TARGETS[1]])); - assert!(resolution.places.is_empty(), "{:?}", resolution.settled); - } - - #[test] - fn nfr6_a_paired_call_site_and_the_fingerprint_place_a_function_together() { - // Edge 156 has functions whose bytes match in two or three places. The call a known - // function makes is a fact of the caller, the bytes one of the place, and they agree. - let resolution = run(&new_module(NEW_TARGETS[0]), false); - assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); - assert_eq!( - resolution.settled, - ["0x101100 -> 0x103100 by calls into it and its fingerprint"] - ); } const VIEW_TARGET: u32 = 0x105000; From 0bacb1359a3e507cd99ddf618d0c1e266bfdc8ce Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:47:48 +0000 Subject: [PATCH 16/29] Publish: develop b70bd7f to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .../platform/windows/src/bin/chrome-builds.rs | 3 +- rivet/platform/windows/src/row_class.rs | 62 ++++-- rivet/platform/windows/src/row_features.rs | 24 ++- rivet/platform/windows/src/row_port.rs | 179 ++++++++++++++---- rivet/platform/windows/src/row_recipe.rs | 6 +- rivet/platform/windows/src/row_resolve.rs | 101 +++++++--- .../windows/src/browsers/chromium/commands.rs | 10 +- .../windows/src/browsers/chromium/split.rs | 5 +- rivet/runtime/windows/src/builds/tests.rs | 6 +- .../windows/src/chromium/live_tables.rs | 18 +- .../windows/src/chromium/window_views.rs | 36 +++- .../windows/src/features/app_window.rs | 20 +- .../windows/src/features/frame_layout.rs | 8 +- .../windows/src/features/side_panel.rs | 5 +- 14 files changed, 361 insertions(+), 122 deletions(-) diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index d70f005..0eda8f4 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -212,9 +212,10 @@ fn score( for (feature, each) in &score.features { let state = if each.off { "off" } else { "on" }; println!( - " {feature}: {state}, {} equal, {} different, {} not held", + " {feature}: {state}, {} equal, {} wrong, {} not found, {} not held", each.equal, each.different.len(), + each.not_found.len(), each.not_held.len() ); for line in &each.different { diff --git a/rivet/platform/windows/src/row_class.rs b/rivet/platform/windows/src/row_class.rs index 25209eb..0817a3a 100644 --- a/rivet/platform/windows/src/row_class.rs +++ b/rivet/platform/windows/src/row_class.rs @@ -135,8 +135,9 @@ impl CodeIndex { let rel = i32::from_le_bytes(raw.try_into().expect("four bytes")); let target = i64::from(rva) + 5 + i64::from(rel); // Only a branch into code can be one into a function. - if let Some(target) = - u32::try_from(target).ok().filter(|target| pe.is_code(*target)) + if let Some(target) = u32::try_from(target) + .ok() + .filter(|target| pe.is_code(*target)) { index.branches.push((target, rva, bytes[at] == 0xE9)); } @@ -144,7 +145,9 @@ impl CodeIndex { } } } - index.uses.sort_unstable_by_key(|each| (each.target, each.at)); + index + .uses + .sort_unstable_by_key(|each| (each.target, each.at)); index.branches.sort_unstable(); index }) @@ -158,7 +161,12 @@ fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { let mut found = Vec::new(); for target in targets { let from = index.uses.partition_point(|each| each.target < *target); - found.extend(index.uses[from..].iter().take_while(|each| each.target == *target).copied()); + found.extend( + index.uses[from..] + .iter() + .take_while(|each| each.target == *target) + .copied(), + ); } found.sort_unstable_by_key(|each: &RipUse| each.at); found @@ -409,7 +417,10 @@ fn tables_beside( for written in stores.iter().filter(|store| store.table == provider) { let tables = object_tables(&stores, written); // The provider's own table must be what the constructor leaves at its place. - if !tables.iter().any(|(at, table)| *at == written.offset && *table == provider) { + if !tables + .iter() + .any(|(at, table)| *at == written.offset && *table == provider) + { continue; } if let Some((_, table)) = tables.get(order) { @@ -533,7 +544,9 @@ fn statics_of_table( } } } - let order = (orders.len() == 1).then(|| orders.into_iter().next()).flatten(); + let order = (orders.len() == 1) + .then(|| orders.into_iter().next()) + .flatten(); (found, order) } @@ -639,7 +652,10 @@ mod tests { bytes[directory..directory + 4].copy_from_slice(&0x2f00u32.to_le_bytes()); bytes[directory + 4..directory + 8] .copy_from_slice(&(12 * ranges.len() as u32).to_le_bytes()); - for (index, flags) in [0x6000_0020u32, 0x4000_0040, 0xC000_0040].iter().enumerate() { + for (index, flags) in [0x6000_0020u32, 0x4000_0040, 0xC000_0040] + .iter() + .enumerate() + { let header = optional + 240 + 40 * index; let rva = 0x1000 * (index as u32 + 1); bytes[header + 8..header + 12].copy_from_slice(&0x1000u32.to_le_bytes()); @@ -715,7 +731,12 @@ mod tests { (0x2200, provider), (0x2400, class), ], - &[(0x1100, 0x1120), (0x1300, 0x1301), (0x1310, 0x1311), (0x1400, 0x1420)], + &[ + (0x1100, 0x1120), + (0x1300, 0x1301), + (0x1310, 0x1311), + (0x1400, 0x1420), + ], ) } @@ -725,7 +746,10 @@ mod tests { let pe = PeFile::parse(&bytes).unwrap(); // The getter reads the static the way the runtime reads it. assert_eq!(load_target(&pe, 0x1200), Some((0x3000, true))); - assert_eq!(class_tables(&pe, "EdgeBrowserFrameViewWin"), BTreeSet::from([0x2400])); + assert_eq!( + class_tables(&pe, "EdgeBrowserFrameViewWin"), + BTreeSet::from([0x2400]) + ); // A name the build does not hold, or holds only as part of a longer one, gives nothing. assert!(class_tables(&pe, "BrowserFrameViewWin").is_empty()); assert!(class_tables(&pe, "WindowsCaptionButton").is_empty()); @@ -796,10 +820,23 @@ mod tests { // seventh in Edge 156, and a name without the place would give the first. assert_eq!(name_and_order("BrowserView#6"), ("BrowserView", 6)); assert_eq!(name_and_order("BrowserView"), ("BrowserView", 0)); - let store = |table, offset| Store { index: 0, table, base: 6, offset }; - let stores = [store(0x10, 0), store(0x20, 8), store(0x30, 0x1f8), store(0x11, 0)]; + let store = |table, offset| Store { + index: 0, + table, + base: 6, + offset, + }; + let stores = [ + store(0x10, 0), + store(0x20, 8), + store(0x30, 0x1f8), + store(0x11, 0), + ]; // A derived constructor's later store at a place replaces the base's. - assert_eq!(object_tables(&stores, &stores[1]), [(0, 0x11), (8, 0x20), (0x1f8, 0x30)]); + assert_eq!( + object_tables(&stores, &stores[1]), + [(0, 0x11), (8, 0x20), (0x1f8, 0x30)] + ); // An object whose first table is not seen gives no places. assert!(object_tables(&stores[1..3], &stores[1]).is_empty()); } @@ -816,5 +853,4 @@ mod tests { let pe = PeFile::parse(&bytes).unwrap(); assert_eq!(load_target(&pe, 0x1000), Some((0x1000 + 26 + 0x2000, true))); } - } diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs index 266fa47..e9a1acf 100644 --- a/rivet/platform/windows/src/row_features.rs +++ b/rivet/platform/windows/src/row_features.rs @@ -293,12 +293,12 @@ fn at<'a>(build: &'a Value, path: &str) -> Option<&'a Value> { } fn at_mut<'a>(build: &'a mut Value, path: &str) -> Option<&'a mut Value> { - path.split('.').try_fold(build, |value, key| value.get_mut(key)) + path.split('.') + .try_fold(build, |value, key| value.get_mut(key)) } fn is_recorded(value: &Value) -> bool { - crate::row_recipe::number(value) - .is_some_and(|value| (0x10_0000..0x7FFF_0000).contains(&value)) + crate::row_recipe::number(value).is_some_and(|value| (0x10_0000..0x7FFF_0000).contains(&value)) } /// Why the runtime does not read a value in this row, or `None` when it does. @@ -426,9 +426,18 @@ mod tests { #[test] fn nfr6_every_row_value_of_a_feature_has_one_switch() { assert_eq!(feature_of("split.view_size").unwrap().name, "split view"); - assert_eq!(feature_of("toolbar.dev.colours[3][0]").unwrap().name, "developer colours"); - assert_eq!(feature_of("layout.frame_ids[1]").unwrap().name, "frame colour"); - assert_eq!(feature_of("omnibox.match_size").unwrap().name, "address suggestions"); + assert_eq!( + feature_of("toolbar.dev.colours[3][0]").unwrap().name, + "developer colours" + ); + assert_eq!( + feature_of("layout.frame_ids[1]").unwrap().name, + "frame colour" + ); + assert_eq!( + feature_of("omnibox.match_size").unwrap().name, + "address suggestions" + ); // The frame and the page area layout have no switch: the window cannot do without them. for core in ["layout.view_bounds_offset", "side_panel.toolbar"] { assert!(feature_of(core).is_none(), "{core}"); @@ -475,7 +484,8 @@ mod tests { #[test] fn nfr6_a_switched_off_feature_excuses_only_its_own_checks() { - let row = json!({"switched_off": [{"feature": "split view"}, {"feature": "developer colours"}]}); + let row = + json!({"switched_off": [{"feature": "split view"}, {"feature": "developer colours"}]}); let excused = excused_checks(&row); assert_eq!(excuses(&excused, "split-grid-4"), Some("split view")); assert_eq!(excuses(&excused, "split"), Some("split view")); diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 77306fa..01b1b99 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -856,9 +856,9 @@ fn settle_carried(row: &mut Value, report: &mut PortReport) { if row_features::is_reflected(&path) { row_features::leave_out(&mut row["build"], &path); report.unread.remove(&path); - report - .reflected - .push(format!("{path}: left out, the runtime finds it by reflection")); + report.reflected.push(format!( + "{path}: left out, the runtime finds it by reflection" + )); } else if let Some(why) = row_features::unused(&row["build"], &path) { row_features::clear(&mut row["build"], &path, Clear::Zero); report.unused.push(format!("{path}: {why}")); @@ -1077,9 +1077,9 @@ fn finish_row( format!("could not be read from the new build: {failure}"), ); } else { - report - .review - .push(format!("a value could not be read from the new build: {failure}")); + report.review.push(format!( + "a value could not be read from the new build: {failure}" + )); } } (row, report) @@ -1285,8 +1285,8 @@ pub fn find_candidate( // that read the prior build next to the new one. let mut wanted: BTreeMap = BTreeMap::new(); let commands = command_targets(prior, version); - let want = |target: u32, kind: row_resolve::Kind, candidates: Option>| { - row_resolve::Wanted { + let want = + |target: u32, kind: row_resolve::Kind, candidates: Option>| row_resolve::Wanted { kind, candidates, class: (kind == row_resolve::Kind::Table) @@ -1296,8 +1296,7 @@ pub fn find_candidate( .then(|| commands.get(&target).copied()) .flatten(), loose: Vec::new(), - } - }; + }; for target in &targets { match stored.get(&format!("{target:#x}")) { Some(Value::String(text)) => match hex(text).filter(|shape| shape.len() >= ANCHOR) { @@ -1382,7 +1381,10 @@ pub fn find_candidate( } many => { let line = format!("{target:#x} matches {} places", many.len()); - wanted.insert(*target, (line, want(*target, function, Some(many.to_vec())))); + wanted.insert( + *target, + (line, want(*target, function, Some(many.to_vec()))), + ); } } } @@ -1469,7 +1471,15 @@ pub fn find_candidate( } record_classes(prior, &mut row, classes, &moved); if let Some(prior_pe) = prior_pe { - read_carried(prior, &mut row, &moved, &followed, prior_pe, pe, &mut report); + read_carried( + prior, + &mut row, + &moved, + &followed, + prior_pe, + pe, + &mut report, + ); } settle_carried(&mut row, &mut report); (row, report) @@ -1530,7 +1540,11 @@ fn release_unplaced( None => { let why = row_features::unused(&row["build"], path).unwrap_or_default(); // A list holds no single address, so a value in one becomes zero. - let how = if path.contains('[') { Clear::Zero } else { Clear::Absent }; + let how = if path.contains('[') { + Clear::Zero + } else { + Clear::Absent + }; row_features::clear(&mut row["build"], path, how); report.unused.push(format!("{path}: {why}")); } @@ -1634,7 +1648,10 @@ fn read_carried( report.derived.push(if value == reading.prior { format!("{}: {value:#x}, {how}", reading.path) } else { - format!("{}: {:#x} -> {value:#x}, {how}", reading.path, reading.prior) + format!( + "{}: {:#x} -> {value:#x}, {how}", + reading.path, reading.prior + ) }); } Err(reason) => { @@ -1825,6 +1842,9 @@ pub struct FeatureScore { pub equal: usize, /// Values the made row holds differently, with both. Any is a wrong value. pub different: Vec, + /// Values no method placed in the new build, so the made row still shows the prior build's and + /// a review line stops the row. Not a wrong value: the row is not published. + pub not_found: Vec, /// The made row turns the feature off, so none of its values is used. pub off: bool, /// Values the made row does not hold or does not use: the runtime finds them by reflection, @@ -1880,7 +1900,8 @@ fn leaves(path: &str, value: &Value, out: &mut BTreeMap) { /// Compares a row made from a prior row with the row people verified for the same build. A value of /// a feature the made row turns off is not compared, since the runtime does not use it. A value the /// made row leaves out, or writes as zero because this build does not read it, is listed as not -/// held. Every other value must be equal, and one that differs is listed with both values. +/// held. A value a review line reports as having no new place is listed as not found. Every other +/// value must be equal, and one that differs is listed with both values. pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScore { let off: BTreeSet<&str> = made[crate::row_features::SWITCHED_OFF] .as_array() @@ -1894,6 +1915,16 @@ pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScor .chain(&report.reflected) .filter_map(|line| line.split(": ").next()) .collect(); + let unplaced: BTreeSet = report + .review + .iter() + .filter_map(|line| line.strip_prefix("no new place for .")) + .filter_map(|rest| rest.split(' ').next()) + .map(|path| match path.starts_with("frame.") { + true => path.to_owned(), + false => format!("build.{path}"), + }) + .collect(); let mut score = RowScore { browser: report.browser.clone(), version: report.version.clone(), @@ -1924,6 +1955,7 @@ pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScor Some(_) if unused.iter().any(|unused| path.starts_with(unused)) => { entry.not_held.push(shown) } + Some(_) if unplaced.contains(&shown) => entry.not_found.push(shown), Some(found) => entry .different .push(format!("{shown}: made {found}, verified {value}")), @@ -2099,8 +2131,11 @@ mod tests { assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 40023); assert_eq!(row["build"]["toolbar"]["dev"]["console"], 40005); assert!( - !report.carried.iter().any(|path| path.starts_with("toolbar.dev.inspect") - || path.starts_with("toolbar.dev.console")), + !report + .carried + .iter() + .any(|path| path.starts_with("toolbar.dev.inspect") + || path.starts_with("toolbar.dev.console")), "{:?}", report.carried ); @@ -2140,7 +2175,12 @@ mod tests { #[test] fn nfr6_a_feature_with_an_unread_value_is_off_for_that_build() { let code = new_code(); - let (row, report) = port(&prior_with_features(), NEW_PLACES, &code_refs(&code), "2.0.0.1"); + let (row, report) = port( + &prior_with_features(), + NEW_PLACES, + &code_refs(&code), + "2.0.0.1", + ); // Nothing holds the rest of the row back. assert_eq!(report.review, Vec::::new()); assert!(report.carried.is_empty(), "{:?}", report.carried); @@ -2156,7 +2196,10 @@ mod tests { .iter() .map(|entry| entry["feature"].as_str().unwrap()) .collect(); - assert_eq!(off, ["address suggestions", "developer colours", "split view"]); + assert_eq!( + off, + ["address suggestions", "developer colours", "split view"] + ); assert_eq!(report.switched_off.len(), 3, "{:?}", report.switched_off); // A value this build does not use is written as zero, and no feature goes off for it. assert_eq!(build["tabs"]["tab_collection"], "0x0"); @@ -2210,7 +2253,12 @@ mod tests { #[test] fn nfr6_a_row_within_its_milestone_turns_nothing_off() { let code = new_code(); - let (row, report) = port(&prior_with_features(), NEW_PLACES, &code_refs(&code), "1.0.0.2"); + let (row, report) = port( + &prior_with_features(), + NEW_PLACES, + &code_refs(&code), + "1.0.0.2", + ); assert_eq!(report.review, Vec::::new()); assert!(report.switched_off.is_empty()); assert_eq!(row["build"]["split"]["supported"], true); @@ -2503,7 +2551,14 @@ mod tests { ) -> (Value, PortReport) { let bytes = module(&code_refs(code)); let pe = PeFile::parse(&bytes).unwrap(); - find_candidate(&verified_row(), prints, None, &BTreeMap::new(), version, &pe) + find_candidate( + &verified_row(), + prints, + None, + &BTreeMap::new(), + version, + &pe, + ) } /// `module` with an exception table at 0x10f000 that lists `starts`. @@ -2561,14 +2616,23 @@ mod tests { let bytes = with_ranges(&new, &ranges(0x2000, new[3].1.len())); let pe = PeFile::parse(&bytes).unwrap(); let classes = BTreeMap::new(); - find_candidate(&verified_row(), &prints, Some(&prior_pe), &classes, "1.0.0.3", &pe) + find_candidate( + &verified_row(), + &prints, + Some(&prior_pe), + &classes, + "1.0.0.3", + &pe, + ) } #[test] fn nfr6_a_carried_value_is_read_from_the_instructions_that_use_it() { // mov rax, [rcx + 0x20]; mov rdx, [rcx + 0x20], and the new build moved the member to 0x28. - let (row, report) = - read_view_layer("488b8120000000488b9120000000", "488b8128000000488b9128000000"); + let (row, report) = read_view_layer( + "488b8120000000488b9120000000", + "488b8128000000488b9128000000", + ); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["view_layer"], "0x28"); assert!(report.carried.is_empty(), "{:?}", report.carried); @@ -2600,8 +2664,10 @@ mod tests { "{:?}", report.review ); - let (_, report) = - read_view_layer("488b8120000000488b9120000000", "488b8128000000488b9130000000"); + let (_, report) = read_view_layer( + "488b8120000000488b9120000000", + "488b8128000000488b9130000000", + ); assert!( report .review @@ -2633,8 +2699,14 @@ mod tests { let (prints, _) = fingerprints_of(&verified, &prior_pe); let bytes = with_starts(&code, &[0x103100, 0x103200, 0x103300]); let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = - find_candidate(&verified, &prints, Some(&prior_pe), &no_classes(), "1.0.0.3", &pe); + let (row, report) = find_candidate( + &verified, + &prints, + Some(&prior_pe), + &no_classes(), + "1.0.0.3", + &pe, + ); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); // A part moved out of another function starts where it may, and a whole function does not. @@ -2645,21 +2717,30 @@ mod tests { )); let bytes = with_starts(&split, &[0x103100, 0x103200, 0x103300, 0x105308]); let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = - find_candidate(&verified, &prints, Some(&prior_pe), &no_classes(), "1.0.0.3", &pe); + let (row, report) = find_candidate( + &verified, + &prints, + Some(&prior_pe), + &no_classes(), + "1.0.0.3", + &pe, + ); assert!(report.review.is_empty(), "{:?}", report.review); assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); // Bytes that match only inside another function are no place at all. let bytes = with_starts(&code, &[0x103100, 0x103200]); let pe = PeFile::parse(&bytes).unwrap(); - let (_, report) = - find_candidate(&verified, &prints, Some(&prior_pe), &no_classes(), "1.0.0.3", &pe); + let (_, report) = find_candidate( + &verified, + &prints, + Some(&prior_pe), + &no_classes(), + "1.0.0.3", + &pe, + ); assert!( - report - .review - .iter() - .any(|line| line - .starts_with("0x101300 matches no function start, of 2 places; not settled:")), + report.review.iter().any(|line| line + .starts_with("0x101300 matches no function start, of 2 places; not settled:")), "{:?}", report.review ); @@ -2746,7 +2827,10 @@ mod tests { assert_eq!(build["split"]["supported"], false); assert_eq!(build["split"]["remove_split"], "0x0"); assert_eq!(build["split"]["signatures"][0][0], "0x0"); - assert_eq!(row[crate::row_features::SWITCHED_OFF][0]["feature"], "split view"); + assert_eq!( + row[crate::row_features::SWITCHED_OFF][0]["feature"], + "split view" + ); assert!( report.switched_off[0] .starts_with("split view is off: split.remove_split has no place"), @@ -2764,11 +2848,17 @@ mod tests { let prints = prints_of_prior(); let (row, report) = find_candidate(&prior, &prints, None, &no_classes(), "1.0.0.3", &pe); assert!( - report.review.iter().any(|line| line == "0x101400: no fingerprint"), + report + .review + .iter() + .any(|line| line == "0x101400: no fingerprint"), "{:?}", report.review ); - assert!(report.unplaced.iter().all(|line| !line.contains("0x101400"))); + assert!(report + .unplaced + .iter() + .all(|line| !line.contains("0x101400"))); assert_eq!(row["build"]["split"]["supported"], true); } @@ -2852,6 +2942,15 @@ mod tests { wrong[0].starts_with("build.toolbar.paint: made"), "{wrong:?}" ); + // A value a review line reports as unplaced is not found, not wrong. + let (_, mut stopped) = + candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); + stopped + .review + .push("no new place for .toolbar.paint 0x101300".into()); + let score = score_row(&made, &stopped, &verified); + assert_eq!(score.wrong(), 0, "{:?}", score.features); + assert_eq!(score.features[WINDOW].not_found, ["build.toolbar.paint"]); // A value the made row does not hold is not wrong. let mut made_less = made.clone(); made_less["build"]["toolbar"] diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index ee91f92..48829b6 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -421,7 +421,11 @@ pub fn derive_row(build: &mut Value, pe: &PeFile) -> Derived { /// takes them the same way, so they are written from the value they follow and never carried. pub const FOLLOWS: &[(&str, &str, i64)] = &[ ("app_window.view_parent", "layout.view_bounds_offset", -0x30), - ("app_window.view_children", "layout.view_bounds_offset", -0x28), + ( + "app_window.view_children", + "layout.view_bounds_offset", + -0x28, + ), ]; /// Writes each value of `FOLLOWS` the row has from the value it follows. diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index 72b3d26..fa2bd23 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -205,7 +205,11 @@ fn read_body(pe: &PeFile, ranges: &BTreeMap, start: u32) -> Vec if instruction.length == 0 || instruction.length > rest.len() { break; } - steps.push(step(&rest[..instruction.length], &instruction, start + at as u32)); + steps.push(step( + &rest[..instruction.length], + &instruction, + start + at as u32, + )); at += instruction.length; } steps @@ -275,7 +279,10 @@ fn named_sites(steps: &[Step]) -> HashMap, Vec> { /// Pairs what the two bodies of one function point at: sites named the same way, which each body /// has the same number of, in order. -fn pair_sites(old: &HashMap, Vec>, new: &HashMap, Vec>) -> Vec<(u32, u32)> { +fn pair_sites( + old: &HashMap, Vec>, + new: &HashMap, Vec>, +) -> Vec<(u32, u32)> { let mut pairs = Vec::new(); for (key, targets) in old { if let Some(others) = new.get(key).filter(|others| others.len() == targets.len()) { @@ -423,7 +430,8 @@ fn calls_into(side: &Side, wanted: &BTreeSet) -> BTreeMap u32 { /// it shares about as many inherited slots with it. What a class takes from its bases is a fact of /// the tables apart from the class's name, so it checks the table a name gives. fn by_sibling(old: &Side, new: &Side, pairs: &[(u32, u32)], target: u32, candidate: u32) -> bool { - pairs.iter().filter(|(from, _)| *from != target).any(|(from, to)| { - let before = shared_slots(old.pe, target, *from); - let after = shared_slots(new.pe, candidate, *to); - before >= SIBLING_LEAST && after * 10 >= before * 8 && after * 8 <= before * 10 - }) + pairs + .iter() + .filter(|(from, _)| *from != target) + .any(|(from, to)| { + let before = shared_slots(old.pe, target, *from); + let after = shared_slots(new.pe, candidate, *to); + before >= SIBLING_LEAST && after * 10 >= before * 8 && after * 8 <= before * 10 + }) } /// Tables of the new build that hold, near the same slot, a function the old table holds and @@ -768,7 +779,8 @@ fn functions_using(side: &Side, texts: &BTreeSet>) -> BTreeMap, { continue; } - let distance = i32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); + let distance = + i32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); let site = base + at as u32; let Ok(target) = u32::try_from(i64::from(site) + 4 + i64::from(distance)) else { continue; @@ -1169,10 +1181,9 @@ pub fn resolve( Ok((place, methods)) => { known.insert(target, place); resolution.places.insert(target, place); - resolution.settled.push(format!( - "{target:#x} -> {place:#x} by {}", - names(&methods) - )); + resolution + .settled + .push(format!("{target:#x} -> {place:#x} by {}", names(&methods))); resolution.reasons.remove(&target); pending.remove(&target); found_any = true; @@ -1245,7 +1256,8 @@ fn use_of(step: &Step, wanted: i64, slot: bool) -> Option { return None; } if slot { - return (step.indirect && step.displacement == Some(wanted)).then_some(Operand::Displacement); + return (step.indirect && step.displacement == Some(wanted)) + .then_some(Operand::Displacement); } if step.displacement == Some(wanted) { Some(Operand::Displacement) @@ -1270,9 +1282,13 @@ fn read_value( if prior == 0 { return Err("zero is used too widely in code to be told apart".to_owned()); } - let wanted = if slot { prior.checked_mul(8) } else { Some(prior) } - .and_then(|value| i64::try_from(value).ok()) - .ok_or_else(|| format!("{prior:#x} is too large to be an operand"))?; + let wanted = if slot { + prior.checked_mul(8) + } else { + Some(prior) + } + .and_then(|value| i64::try_from(value).ok()) + .ok_or_else(|| format!("{prior:#x} is too large to be an operand"))?; let mut found: Vec<(u64, u32)> = Vec::new(); let mut uses = 0; for (from, to) in pairs { @@ -1286,7 +1302,10 @@ fn read_value( }; uses += 1; let key = &old_keys[index]; - let rank = old_keys[..index].iter().filter(|other| *other == key).count(); + let rank = old_keys[..index] + .iter() + .filter(|other| *other == key) + .count(); let count = old_keys.iter().filter(|other| *other == key).count(); let theirs: Vec = new_keys .iter() @@ -1367,7 +1386,11 @@ pub fn read_values( for (path, prior) in values { let section = path.split('.').next().unwrap_or_default(); let name = path.rsplit('.').next().unwrap_or_default(); - let slot = name.split('[').next().unwrap_or_default().ends_with("_slot"); + let slot = name + .split('[') + .next() + .unwrap_or_default() + .ends_with("_slot"); let pairs = pairs_of.get(section).map_or(&[][..], Vec::as_slice); readings.push(Reading { path: path.clone(), @@ -1573,7 +1596,10 @@ pub(crate) mod tests { let alone = decide(&answers[..1], None).unwrap_err(); assert!(alone.starts_with("only its class name found it"), "{alone}"); // A place that is not one of the fingerprint's places gets no agreement from it. - assert_eq!(fingerprint_agrees(&BTreeSet::from([0x11b5_3000]), Some(candidates)), None); + assert_eq!( + fingerprint_agrees(&BTreeSet::from([0x11b5_3000]), Some(candidates)), + None + ); // A table slot that gives two places gives the fingerprint nothing to agree with. let both: BTreeSet = candidates.iter().copied().collect(); assert_eq!(fingerprint_agrees(&both, Some(candidates)), None); @@ -1595,7 +1621,10 @@ pub(crate) mod tests { let resolution = run(&new_module(NEW_TARGETS[0]), false); assert!(resolution.places.is_empty()); let reason = &resolution.reasons[&OLD_TARGET]; - assert!(reason.starts_with("only calls into it found it"), "{reason}"); + assert!( + reason.starts_with("only calls into it found it"), + "{reason}" + ); } const VIEW_TARGET: u32 = 0x105000; @@ -1682,12 +1711,18 @@ pub(crate) mod tests { let alone = run_views([true, true], &[VIEW_TABLE]); assert!(alone.places.is_empty()); let reason = &alone.reasons[&VIEW_TARGET]; - assert!(reason.starts_with("only its table slot found it"), "{reason}"); + assert!( + reason.starts_with("only its table slot found it"), + "{reason}" + ); // A second table that lines the slot up another way confirms nothing. let apart = run_views([true, false], &[VIEW_TABLE, OTHER_VIEW_TABLE]); assert!(apart.places.is_empty()); let reason = &apart.reasons[&VIEW_TARGET]; - assert!(reason.starts_with("only its table slot found it"), "{reason}"); + assert!( + reason.starts_with("only its table slot found it"), + "{reason}" + ); } /// push rbx; mov ebx, 5; xor eax, eax; call `first`; [call `second`;] nop; pop rbx; ret: a @@ -1756,7 +1791,10 @@ pub(crate) mod tests { fn nfr6_a_place_outside_the_fingerprint_matches_is_refused() { let answers = [(Method::CallsInto, 0x103300), (Method::TableSlot, 0x103300)]; let refused = decide(&answers, Some(&NEW_TARGETS[..])).unwrap_err(); - assert!(refused.contains("not one of its fingerprint's places"), "{refused}"); + assert!( + refused.contains("not one of its fingerprint's places"), + "{refused}" + ); let (place, methods) = decide(&answers, None).unwrap(); assert_eq!(place, 0x103300); assert_eq!(methods.len(), 2); @@ -1767,8 +1805,11 @@ pub(crate) mod tests { // Two classes of one base hold the base's functions in the same slots. Edge 157's caption // button table was named by its class, and what it shares with the frame's table checks it. let functions: Vec = (0..12u32).map(|n| 0x101400 + 0x10 * n).collect(); - let mut parts: Vec<(u32, Vec)> = - functions.iter().enumerate().map(|(n, at)| (*at, small(n as u8))).collect(); + let mut parts: Vec<(u32, Vec)> = functions + .iter() + .enumerate() + .map(|(n, at)| (*at, small(n as u8))) + .collect(); let mut own = functions.clone(); own[10] = 0x101600; own[11] = 0x101610; @@ -1776,7 +1817,12 @@ pub(crate) mod tests { parts.push((0x101610, small(41))); // A table of other functions throughout shares nothing. let other: Vec = (0..12u32).map(|n| 0x101700 + 0x10 * n).collect(); - parts.extend(other.iter().enumerate().map(|(n, at)| (*at, small(50 + n as u8)))); + parts.extend( + other + .iter() + .enumerate() + .map(|(n, at)| (*at, small(50 + n as u8))), + ); parts.push((0x200100, table(&functions))); parts.push((0x200300, table(&own))); parts.push((0x200500, table(&other))); @@ -1790,5 +1836,4 @@ pub(crate) mod tests { // The known table itself is no check of its own place. assert!(!by_sibling(&old, &new, &pairs, 0x200100, 0x200100)); } - } diff --git a/rivet/runtime/windows/src/browsers/chromium/commands.rs b/rivet/runtime/windows/src/browsers/chromium/commands.rs index 99f2283..6fe2511 100644 --- a/rivet/runtime/windows/src/browsers/chromium/commands.rs +++ b/rivet/runtime/windows/src/browsers/chromium/commands.rs @@ -168,8 +168,14 @@ mod tests { #[test] fn nfr6_a_command_id_is_not_a_row_value() { // The developer commands follow the build's Chromium milestone, whatever its row holds. - assert_eq!(dev_tools("Google Chrome", [159, 0, 8154, 6]), (40023, 40005)); - assert_eq!(dev_tools("Microsoft Edge", [157, 0, 4341, 46]), (40023, 40005)); + assert_eq!( + dev_tools("Google Chrome", [159, 0, 8154, 6]), + (40023, 40005) + ); + assert_eq!( + dev_tools("Microsoft Edge", [157, 0, 4341, 46]), + (40023, 40005) + ); // A milestone whose header was not read offers no command. assert_eq!(dev_tools("Google Chrome", [149, 0, 1, 1]), (0, 0)); assert_eq!(dev_tools("Samsung Internet", [30, 0, 4, 29]), (0, 0)); diff --git a/rivet/runtime/windows/src/browsers/chromium/split.rs b/rivet/runtime/windows/src/browsers/chromium/split.rs index 7efa102..41c042f 100644 --- a/rivet/runtime/windows/src/browsers/chromium/split.rs +++ b/rivet/runtime/windows/src/browsers/chromium/split.rs @@ -81,10 +81,7 @@ pub(crate) fn needs(build: &Build) -> Needs { /// the Sidebar left, and the toolbar follows the active page. pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { let row = &crate::builds::get().side_panel; - if let (Some(toolbar), Some(contents)) = ( - area.bounds(row.toolbar), - area.contents(), - ) { + if let (Some(toolbar), Some(contents)) = (area.bounds(row.toolbar), area.contents()) { if area.rail == 0 && active_is_split(area.window) { if let Some(page) = area.page() { fill_area(&mut *contents, &*page); diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index 3b4e8cd..cf73bee 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -1071,7 +1071,11 @@ fn nfr3_chromium_157_rows_record_the_members_that_moved() { assert_eq!(build.tabs.browser_in_view, 0x558, "{name}"); assert_eq!(build.side_panel.browser_offset, 0x558, "{name}"); assert_eq!(build.layout.view_bounds_offset, 0x1C8, "{name}"); - assert_eq!(build.layout.frame_browser_window_offset, Some(0x338), "{name}"); + assert_eq!( + build.layout.frame_browser_window_offset, + Some(0x338), + "{name}" + ); assert_eq!(build.layout.caption_container_offset, 0x3C0, "{name}"); assert_eq!( (build.layout.top_inset_slot, build.layout.caption_paint_slot), diff --git a/rivet/runtime/windows/src/chromium/live_tables.rs b/rivet/runtime/windows/src/chromium/live_tables.rs index e81be26..afd90ac 100644 --- a/rivet/runtime/windows/src/chromium/live_tables.rs +++ b/rivet/runtime/windows/src/chromium/live_tables.rs @@ -91,7 +91,9 @@ pub(crate) fn frame_view( browser_view: usize, parent: usize, ) -> Option { - let holder = memory.word(browser_view + parent).filter(|holder| *holder != 0)?; + let holder = memory + .word(browser_view + parent) + .filter(|holder| *holder != 0)?; let frames: Vec = children(memory, holder, parent + 8) .into_iter() .filter(|child| *child != browser_view) @@ -240,7 +242,8 @@ mod tests { self.words.insert(child + PARENT, parent); } self.words.insert(parent + PARENT + 8, list); - self.words.insert(parent + PARENT + 16, list + children.len() * 8); + self.words + .insert(parent + PARENT + 16, list + children.len() * 8); } } @@ -271,7 +274,11 @@ mod tests { tree.view(NON_CLIENT, BASE + 0x100_1000, "NonClientView"); tree.view(BROWSER, BASE + 0x100_2000, BROWSER_VIEW); tree.view(FRAME, BASE + 0x100_3000, frame_name); - tree.view(CONTAINER, BASE + 0x100_4000, "WindowsCaptionButtonContainer"); + tree.view( + CONTAINER, + BASE + 0x100_4000, + "WindowsCaptionButtonContainer", + ); for (button, table) in BUTTONS.iter().zip(button_tables) { tree.view(*button, table, CAPTION_BUTTON); } @@ -309,7 +316,10 @@ mod tests { assert_eq!((tables.frame, tables.caption), (None, None)); // The walk starts only from a view named as the browser view. let tree = window("BrowserFrameViewWin", [BASE + 0x100_5000; 3]); - assert_eq!(tables_of(&tree, FRAME, PARENT, &is_table), Tables::default()); + assert_eq!( + tables_of(&tree, FRAME, PARENT, &is_table), + Tables::default() + ); } #[test] diff --git a/rivet/runtime/windows/src/chromium/window_views.rs b/rivet/runtime/windows/src/chromium/window_views.rs index d9b511d..50c3c42 100644 --- a/rivet/runtime/windows/src/chromium/window_views.rs +++ b/rivet/runtime/windows/src/chromium/window_views.rs @@ -140,13 +140,17 @@ fn is_listing_parent(memory: &M, view: usize, parent: usize) -> bool } fn children(memory: &M, view: usize, field: usize) -> Vec { - let (Some(begin), Some(end)) = (memory.word(view + field), memory.word(view + field + 8)) else { + let (Some(begin), Some(end)) = (memory.word(view + field), memory.word(view + field + 8)) + else { return Vec::new(); }; if begin == 0 || end < begin || (end - begin) % 8 != 0 || (end - begin) / 8 > 256 { return Vec::new(); } - (begin..end).step_by(8).filter_map(|at| memory.word(at)).collect() + (begin..end) + .step_by(8) + .filter_map(|at| memory.word(at)) + .collect() } /// The root of the view tree `view` is in: the view whose parent is null. @@ -339,7 +343,12 @@ impl Slot { } fn known(&self, row: Option) -> Option { - match self.value.lock().unwrap_or_else(|error| error.into_inner()).0 { + match self + .value + .lock() + .unwrap_or_else(|error| error.into_inner()) + .0 + { Settled::Known(known) => known, Settled::Unknown => row, } @@ -373,10 +382,14 @@ pub(crate) unsafe fn host_field(layout: usize) -> Option { }; let host = HOST.get(recorded(row.host_view), || fields().map(|found| found.host)); PAGE_AREA.get(recorded(row.page_area), || { - fields().map(|found| found.page_area).filter(|fields| !fields.is_empty()) + fields() + .map(|found| found.page_area) + .filter(|fields| !fields.is_empty()) }); CONTENTS.get(recorded(row.contents_container), || { - fields().map(|found| found.contents).filter(|fields| !fields.is_empty()) + fields() + .map(|found| found.contents) + .filter(|fields| !fields.is_empty()) }); host } @@ -402,9 +415,7 @@ pub(crate) unsafe fn frame_browser_view(frame: usize, host: Option) -> Op let field = FRAME.get(row, || { live().and_then(|live| frame_fields(live, frame, host, parent_field())) })?; - live()? - .word(frame + field) - .filter(|view| *view != 0) + live()?.word(frame + field).filter(|view| *view != 0) } /// Starts the view walk of `reflect` from `window`'s own `HWNDMessageHandler`, once per process, on @@ -478,7 +489,9 @@ pub(crate) unsafe fn read_tables( .is_some_and(|slot| slot >= ranges.text.0 && slot < ranges.text.1) }; let tables = live_tables::note(live, browser_view, found.parent, image.base, &is_table); - crate::trace::trace(&format!("window views: class tables from live views {tables:x?}")); + crate::trace::trace(&format!( + "window views: class tables from live views {tables:x?}" + )); tables } @@ -678,7 +691,10 @@ mod tests { frame_fields(&memory, FRAME, None, Some(PARENT)), Some(vec![0x340, 0x348]) ); - assert_eq!(frame_fields(&memory, FRAME, Some(OTHER), Some(PARENT)), None); + assert_eq!( + frame_fields(&memory, FRAME, Some(OTHER), Some(PARENT)), + None + ); assert_eq!(frame_fields(&memory, FRAME, None, None), None); } diff --git a/rivet/runtime/windows/src/features/app_window.rs b/rivet/runtime/windows/src/features/app_window.rs index 3682695..3aca8d6 100644 --- a/rivet/runtime/windows/src/features/app_window.rs +++ b/rivet/runtime/windows/src/features/app_window.rs @@ -31,7 +31,10 @@ pub(crate) fn view_fields(build: &crate::builds::Build) -> Option<(usize, usize) use crate::chromium::view::View; let by_bounds = View::parent_offset(build.layout.view_bounds_offset) .map(|parent| (parent, View::children_offset(parent))); - agreed_view_fields(crate::chromium::window_views::walked_view_fields(), by_bounds) + agreed_view_fields( + crate::chromium::window_views::walked_view_fields(), + by_bounds, + ) } /// The view fields from the walk and from the bounds offset. Both must agree when both are known. @@ -738,10 +741,19 @@ mod tests { Some((0x198, 0x1A0)) ); // A walk that disagrees with the bounds offset leaves the fields unknown. - assert_eq!(agreed_view_fields(Some((0x190, 0x198)), Some((0x198, 0x1A0))), None); + assert_eq!( + agreed_view_fields(Some((0x190, 0x198)), Some((0x198, 0x1A0))), + None + ); // Either alone stands until the other is known. - assert_eq!(agreed_view_fields(Some((0x190, 0x198)), None), Some((0x190, 0x198))); - assert_eq!(agreed_view_fields(None, Some((0x198, 0x1A0))), Some((0x198, 0x1A0))); + assert_eq!( + agreed_view_fields(Some((0x190, 0x198)), None), + Some((0x190, 0x198)) + ); + assert_eq!( + agreed_view_fields(None, Some((0x198, 0x1A0))), + Some((0x198, 0x1A0)) + ); assert_eq!(agreed_view_fields(None, None), None); } diff --git a/rivet/runtime/windows/src/features/frame_layout.rs b/rivet/runtime/windows/src/features/frame_layout.rs index 310d70a..cda859d 100644 --- a/rivet/runtime/windows/src/features/frame_layout.rs +++ b/rivet/runtime/windows/src/features/frame_layout.rs @@ -150,7 +150,10 @@ fn corner_table() -> usize { /// The browser view's class table, settled with the live browser view's as `frame_table` is. fn browser_view_table() -> usize { use crate::chromium::live_tables; - live_tables::table(bv().browser_view_view_vtable, live_tables::found().browser_view) + live_tables::table( + bv().browser_view_view_vtable, + live_tables::found().browser_view, + ) } fn recorded_image() -> Result { @@ -926,8 +929,7 @@ unsafe fn clip_panel(frame: *mut c_void) { return; }; let base = image.base; - let Some(index) = - (0..0x100).find(|index| *browser.add(*index) == base + browser_view_table()) + let Some(index) = (0..0x100).find(|index| *browser.add(*index) == base + browser_view_table()) else { return; }; diff --git a/rivet/runtime/windows/src/features/side_panel.rs b/rivet/runtime/windows/src/features/side_panel.rs index 0e6e622..d7e79bf 100644 --- a/rivet/runtime/windows/src/features/side_panel.rs +++ b/rivet/runtime/windows/src/features/side_panel.rs @@ -909,10 +909,7 @@ pub(crate) unsafe fn on_page_area(area: &mut PageArea) { let animation = area.bounds(bv().side_panel_animation); let outline = area.bounds(bv().contents_outline); let panel_view = area.field(bv().side_panel); - let page = area - .page() - .map(|bounds| *bounds) - .unwrap_or([0; 4]); + let page = area.page().map(|bounds| *bounds).unwrap_or([0; 4]); // The page starts where the browser's vertical tab list ends. let left = area .bounds(bv().vertical_tabs) From 0c050e7776c498134a6f8fe36ce919bef5decf2d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:57:33 +0000 Subject: [PATCH 17/29] Publish: develop 9b3c24d to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- .../platform/windows/src/bin/chrome-builds.rs | 8 ++- rivet/platform/windows/src/row_port.rs | 59 ++++++++++++++++--- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index 0eda8f4..18cc22b 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -199,7 +199,7 @@ fn score( .ok_or("the verified row has no frame version")? .to_owned(); let (row, report) = make(&prior, prior_module, module, &version)?; - let score = row_port::score_row(&row, &report, &verified); + let score = row_port::score_row(&row, &report, &verified, &prior); std::fs::write( out, serde_json::to_string_pretty(&score).map_err(|error| error.to_string())? + "\n", @@ -212,15 +212,19 @@ fn score( for (feature, each) in &score.features { let state = if each.off { "off" } else { "on" }; println!( - " {feature}: {state}, {} equal, {} wrong, {} not found, {} not held", + " {feature}: {state}, {} equal, {} wrong, {} carried, {} not found, {} not held", each.equal, each.different.len(), + each.carried.len(), each.not_found.len(), each.not_held.len() ); for line in &each.different { println!(" wrong: {line}"); } + for line in &each.carried { + println!(" carried: {line}"); + } } if !score.review.is_empty() { println!( diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 01b1b99..000e315 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -1845,6 +1845,9 @@ pub struct FeatureScore { /// Values no method placed in the new build, so the made row still shows the prior build's and /// a review line stops the row. Not a wrong value: the row is not published. pub not_found: Vec, + /// Values the made row holds exactly as the prior row did although the verified row differs: + /// nothing read them again. Wrong only in a row no review line stops. + pub carried: Vec, /// The made row turns the feature off, so none of its values is used. pub off: bool, /// Values the made row does not hold or does not use: the runtime finds them by reflection, @@ -1864,15 +1867,27 @@ pub struct RowScore { } impl RowScore { - /// How many values were found but differ from the verified row. Must be zero. + /// How many values were found but differ from the verified row, with the values carried from + /// the prior build when no review line stops the row. Must be zero. pub fn wrong(&self) -> usize { self.features .values() - .map(|score| score.different.len()) + .map(|score| match self.review.is_empty() { + true => score.different.len() + score.carried.len(), + false => score.different.len(), + }) .sum() } } +/// The address a value was read at: the function of a prologue, or the first item of a pair. +fn read_at(path: &str) -> Option { + if let Some(function) = path.strip_suffix("_prologue") { + return Some(function.to_owned()); + } + path.strip_suffix("[1]").map(|pair| format!("{pair}[0]")) +} + /// Every value a row part holds that is not a list or object, by its path. fn leaves(path: &str, value: &Value, out: &mut BTreeMap) { match value { @@ -1902,7 +1917,7 @@ fn leaves(path: &str, value: &Value, out: &mut BTreeMap) { /// made row leaves out, or writes as zero because this build does not read it, is listed as not /// held. A value a review line reports as having no new place is listed as not found. Every other /// value must be equal, and one that differs is listed with both values. -pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScore { +pub fn score_row(made: &Value, report: &PortReport, verified: &Value, prior: &Value) -> RowScore { let off: BTreeSet<&str> = made[crate::row_features::SWITCHED_OFF] .as_array() .map_or(&[][..], Vec::as_slice) @@ -1933,8 +1948,9 @@ pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScor ..RowScore::default() }; for part in ["frame", "build"] { - let (mut want, mut have) = (BTreeMap::new(), BTreeMap::new()); + let (mut want, mut have, mut before) = (BTreeMap::new(), BTreeMap::new(), BTreeMap::new()); leaves("", &verified[part], &mut want); + leaves("", &prior[part], &mut before); leaves("", &made[part], &mut have); for (path, value) in want { let feature = match part { @@ -1956,6 +1972,15 @@ pub fn score_row(made: &Value, report: &PortReport, verified: &Value) -> RowScor entry.not_held.push(shown) } Some(_) if unplaced.contains(&shown) => entry.not_found.push(shown), + // Bytes read at an address with no new place say nothing about the new build. + Some(_) if read_at(&shown).is_some_and(|at| unplaced.contains(&at)) => { + entry.not_found.push(shown) + } + // A part the generator could not confirm is declined, which is not a wrong value. + Some(Value::Bool(false)) => entry.not_found.push(shown), + Some(found) if before.get(&path) == Some(found) => entry + .carried + .push(format!("{shown}: carried {found}, verified {value}")), Some(found) => entry .different .push(format!("{shown}: made {found}, verified {value}")), @@ -2930,12 +2955,12 @@ mod tests { fn nfr6_a_made_row_is_scored_value_by_value_against_the_verified_row() { let (made, report) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); let mut verified = made.clone(); - let score = score_row(&made, &report, &verified); + let score = score_row(&made, &report, &verified, &json!({})); assert_eq!(score.wrong(), 0); assert!(score.features[WINDOW].equal > 0); // A value found at another place than the verified one is wrong. verified["build"]["toolbar"]["paint"] = json!("0x103310"); - let score = score_row(&made, &report, &verified); + let score = score_row(&made, &report, &verified, &json!({})); assert_eq!(score.wrong(), 1, "{:?}", score.features); let wrong: Vec<&String> = score.features.values().flat_map(|f| &f.different).collect(); assert!( @@ -2948,16 +2973,32 @@ mod tests { stopped .review .push("no new place for .toolbar.paint 0x101300".into()); - let score = score_row(&made, &stopped, &verified); + let score = score_row(&made, &stopped, &verified, &json!({})); assert_eq!(score.wrong(), 0, "{:?}", score.features); assert_eq!(score.features[WINDOW].not_found, ["build.toolbar.paint"]); + // Bytes read at that address are not found either. + let mut bytes = verified.clone(); + bytes["build"]["toolbar"]["paint_prologue"] = json!("4883ec28"); + let mut read = made.clone(); + read["build"]["toolbar"]["paint_prologue"] = json!("cccccccc"); + let score = score_row(&read, &stopped, &bytes, &json!({})); + assert_eq!(score.wrong(), 0, "{:?}", score.features); + // A value kept from the prior row is wrong only when nothing stops the row. + let mut kept = verified.clone(); + kept["build"]["toolbar"]["paint"] = made["build"]["toolbar"]["paint"].clone(); + kept["build"]["toolbar"]["slot"] = json!(7); + let mut carried = made.clone(); + carried["build"]["toolbar"]["slot"] = json!(8); + let before = json!({"build": {"toolbar": {"slot": 8}}}); + assert_eq!(score_row(&carried, &report, &kept, &before).wrong(), 1); + assert_eq!(score_row(&carried, &stopped, &kept, &before).wrong(), 0); // A value the made row does not hold is not wrong. let mut made_less = made.clone(); made_less["build"]["toolbar"] .as_object_mut() .unwrap() .remove("paint"); - let score = score_row(&made_less, &report, &verified); + let score = score_row(&made_less, &report, &verified, &json!({})); assert_eq!(score.wrong(), 0); // A feature the made row turns off is not compared at all. let mut off = made.clone(); @@ -2965,7 +3006,7 @@ mod tests { let mut split = verified.clone(); split["build"]["split"] = json!({"supported": true, "outline_member": "0x40"}); off["build"]["split"] = json!({"supported": false, "outline_member": "0x0"}); - let score = score_row(&off, &report, &split); + let score = score_row(&off, &report, &split, &json!({})); assert!(score.features["split view"].off); assert!(score.features["split view"].different.is_empty()); } From 2caab408d01e62ca49c3584951e14ac95a81452f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:24:05 +0000 Subject: [PATCH 18/29] Publish: develop 62d918d to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 114 ++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index fa2bd23..986a9a4 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -795,6 +795,68 @@ fn functions_using(side: &Side, texts: &BTreeSet>) -> BTreeMap, users } +/// How many functions on one side of a function are compared by their lengths. +const NEIGHBOURS: usize = 8; + +/// The function starts of a build in order, with every run of `NEIGHBOURS` lengths between them +/// and where it begins. +pub struct Lengths { + starts: Vec, + runs: HashMap, Vec>, +} + +impl Lengths { + pub fn new(starts: &BTreeSet) -> Self { + let starts: Vec = starts.iter().copied().collect(); + let gaps: Vec = starts.windows(2).map(|pair| pair[1] - pair[0]).collect(); + let mut runs: HashMap, Vec> = HashMap::new(); + for (index, run) in gaps.windows(NEIGHBOURS).enumerate() { + let places = runs.entry(run.to_vec()).or_default(); + // A run seen more than twice is no better than one seen twice: it names no place. + if places.len() < 2 { + places.push(index); + } + } + Self { starts, runs } + } + + /// The lengths of the `NEIGHBOURS` functions from the one at `index`. + fn run(&self, index: usize) -> Option> { + let part = self.starts.get(index..=index + NEIGHBOURS)?; + Some(part.windows(2).map(|pair| pair[1] - pair[0]).collect()) + } +} + +/// The place of a function by the functions the linker put beside it. The linker keeps the +/// functions of one source file together and in order, so the lengths of the functions after a +/// function, and of those before it, form a run that a build holds once. A run of the prior build +/// that the new build also holds exactly once gives the place. Both sides must not disagree, and a +/// run of equal lengths, as a row of small stubs has, says nothing. +fn by_neighbours(old: &Lengths, new: &Lengths, target: u32) -> Option { + let index = old.starts.binary_search(&target).ok()?; + let place = |run: Option>, back: usize| -> Option> { + let run = run?; + if run.iter().collect::>().len() < NEIGHBOURS / 2 { + return None; + } + match new.runs.get(&run).map(Vec::as_slice) { + Some([only]) => Some(new.starts.get(only + back).copied()), + Some(_) => Some(None), + None => None, + } + }; + let after = place(old.run(index), 0); + let before = place( + index.checked_sub(NEIGHBOURS).and_then(|from| old.run(from)), + NEIGHBOURS, + ); + match (after.flatten(), before.flatten()) { + (Some(one), Some(other)) => (one == other).then_some(one), + (Some(one), None) | (None, Some(one)) => Some(one), + (None, None) => None, + } +} + /// Which method gave a place. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Method { @@ -810,6 +872,7 @@ pub enum Method { Command, KnownCaller, Sibling, + Neighbours, } impl fmt::Display for Method { @@ -827,6 +890,7 @@ impl fmt::Display for Method { Method::Command => "its command id", Method::KnownCaller => "a known caller", Method::Sibling => "the slots it shares with a known table", + Method::Neighbours => "the lengths of the functions beside it", }) } } @@ -1052,6 +1116,9 @@ pub fn resolve( } } + let old_lengths = Lengths::new(&old_pe.function_starts()); + let new_lengths = Lengths::new(&new_pe.function_starts()); + let mut pending: BTreeSet = wanted.keys().copied().collect(); for _ in 0..ROUNDS { let followed = follow(&mut old, &mut new, &known); @@ -1109,6 +1176,19 @@ pub fn resolve( } } } + if let Some(place) = by_neighbours(&old_lengths, &new_lengths, target) { + // Where a function lies says nothing of its bytes, so the fingerprint + // matching at that place is a second fact. + answers.push((Method::Neighbours, place)); + let matched = want + .candidates + .as_ref() + .is_some_and(|candidates| candidates.contains(&place)) + || want.loose.contains(&place); + if matched { + answers.push((Method::Fingerprint, place)); + } + } if let Some(place) = by_command.get(&target).copied() { answers.push((Method::Command, place)); let matched = want @@ -1836,4 +1916,38 @@ pub(crate) mod tests { // The known table itself is no check of its own place. assert!(!by_sibling(&old, &new, &pairs, 0x200100, 0x200100)); } + #[test] + fn nfr6_a_function_is_placed_by_the_lengths_of_the_functions_beside_it() { + let lengths = [0x30, 0x48, 0x21, 0x90, 0x17, 0x64, 0x52, 0x3d, 0x71, 0x2a]; + let starts = |from: u32, lengths: &[u32]| -> BTreeSet { + let mut at = from; + let mut out = BTreeSet::from([at]); + for length in lengths { + at += length; + out.insert(at); + } + out + }; + let old = Lengths::new(&starts(0x1000, &lengths)); + // The new build has another function in front, so every place moved. + let mut moved = vec![0x500]; + moved.extend(lengths); + let new = Lengths::new(&starts(0x2000, &moved)); + assert_eq!(by_neighbours(&old, &new, 0x1000), Some(0x2500)); + assert_eq!(by_neighbours(&old, &new, 0x1030), Some(0x2530)); + // The last functions are placed by those before them. + let last = 0x1000 + lengths.iter().sum::(); + assert_eq!(by_neighbours(&old, &new, last), Some(last + 0x1500)); + // An address that starts no function has no neighbours. + assert_eq!(by_neighbours(&old, &new, 0x1004), None); + // A run the new build holds twice names no place. + let mut twice = moved.clone(); + twice.extend(lengths); + let new = Lengths::new(&starts(0x2000, &twice)); + assert_eq!(by_neighbours(&old, &new, 0x1000), None); + // A row of stubs of one length says nothing. + let old = Lengths::new(&starts(0x1000, &[0x10; 10])); + let new = Lengths::new(&starts(0x2000, &[0x10; 8])); + assert_eq!(by_neighbours(&old, &new, 0x1000), None); + } } From c69f2fb707351b4af7f49c61236d7f9297277ded Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:35:47 +0000 Subject: [PATCH 19/29] Publish: develop 1c7f193 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 133 +++++++++++++++++++++- 1 file changed, 127 insertions(+), 6 deletions(-) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index 986a9a4..5f53617 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -857,6 +857,56 @@ fn by_neighbours(old: &Lengths, new: &Lengths, target: u32) -> Option { } } +/// How many callers must agree on a place, how many are a crowd, and how many are read. +const VOTERS_LEAST: usize = 3; +const VOTERS_CROWD: usize = 8; +const VOTERS_MOST: usize = 400; + +/// The place of a function by the functions that call it. Each caller is placed by its own +/// neighbours, apart from every other caller, and must make as many direct calls and jumps in both +/// builds. The call that went to the function in the prior build then goes to its new place. One +/// caller is one vote, and the place stands when at least `VOTERS_LEAST` callers name it and at +/// most one in ten names another. Returns the place and its votes. +fn by_callers( + old: &mut Side, + new: &mut Side, + lengths: (&Lengths, &Lengths), + callers: &BTreeSet, + target: u32, +) -> Option<(u32, usize)> { + let mut votes: BTreeMap = BTreeMap::new(); + for caller in callers.iter().take(VOTERS_MOST) { + let Some(place) = by_neighbours(lengths.0, lengths.1, *caller) else { + continue; + }; + let before: Vec = old + .body(*caller) + .iter() + .filter_map(|step| step.call) + .collect(); + let after: Vec = new + .body(place) + .iter() + .filter_map(|step| step.call) + .collect(); + if before.len() != after.len() { + continue; + } + let named: BTreeSet = before + .iter() + .zip(&after) + .filter(|(from, _)| **from == target) + .map(|(_, to)| *to) + .collect(); + if let [only] = named.iter().copied().collect::>()[..] { + *votes.entry(only).or_default() += 1; + } + } + let all: usize = votes.values().sum(); + let (place, most) = votes.into_iter().max_by_key(|(_, count)| *count)?; + (most >= VOTERS_LEAST && (all - most) * 10 <= all).then_some((place, most)) +} + /// Which method gave a place. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Method { @@ -873,6 +923,8 @@ pub enum Method { KnownCaller, Sibling, Neighbours, + Callers, + Crowd, } impl fmt::Display for Method { @@ -891,6 +943,8 @@ impl fmt::Display for Method { Method::KnownCaller => "a known caller", Method::Sibling => "the slots it shares with a known table", Method::Neighbours => "the lengths of the functions beside it", + Method::Callers => "the same call in several placed callers", + Method::Crowd => "the number of callers that agree", }) } } @@ -1068,12 +1122,7 @@ pub fn resolve( let callers = calls_into(&new, &called); // The prior build's callers of each wanted function with fingerprint places, for the method of // a known caller. - let with_candidates: BTreeSet = wanted - .iter() - .filter(|(_, want)| want.kind == Kind::Function && want.candidates.is_some()) - .map(|(target, _)| *target) - .collect(); - let prior_callers = calls_into(&old, &with_candidates); + let prior_callers = calls_into(&old, &functions.iter().copied().collect()); // A class name gives a table from the build alone, so it is read once. let mut by_class = BTreeMap::new(); @@ -1189,6 +1238,33 @@ pub fn resolve( answers.push((Method::Fingerprint, place)); } } + let voted = from.and_then(|callers| { + let lengths = (&old_lengths, &new_lengths); + by_callers(&mut old, &mut new, lengths, callers, target) + }); + if let Some((place, votes)) = voted { + // Callers placed by their neighbours are another fact than the calls + // followed from known functions, but the same kind, so beside those they + // add only what the fingerprint and their number say. + let followed = answers.iter().any(|(method, at)| { + matches!(method, Method::CallsInto | Method::KnownCaller) + && *at == place + }); + if !followed { + answers.push((Method::Callers, place)); + } + let matched = want + .candidates + .as_ref() + .is_some_and(|candidates| candidates.contains(&place)) + || want.loose.contains(&place); + if matched { + answers.push((Method::Fingerprint, place)); + } + if votes >= VOTERS_CROWD { + answers.push((Method::Crowd, place)); + } + } if let Some(place) = by_command.get(&target).copied() { answers.push((Method::Command, place)); let matched = want @@ -1950,4 +2026,49 @@ pub(crate) mod tests { let new = Lengths::new(&starts(0x2000, &[0x10; 8])); assert_eq!(by_neighbours(&old, &new, 0x1000), None); } + #[test] + fn nfr6_a_function_is_placed_by_the_call_several_placed_callers_make() { + // Twelve functions of twelve lengths, the first `calling` of which call the target, which + // comes last. The new build has one more function in front. + let build = |shift: u32, calling: usize, target: u32| -> Vec { + let mut parts = Vec::new(); + let mut ranges = Vec::new(); + let mut at = 0x100000; + if shift > 0 { + parts.push((at, vec![0xC3])); + ranges.push((at, at + shift)); + at += shift; + } + for index in 0..12u32 { + let length = 0x10 + index * 4; + let mut body = Vec::new(); + if (index as usize) < calling { + body.extend(call(at, target)); + } + body.push(0xC3); + parts.push((at, body)); + ranges.push((at, at + length)); + at += length; + } + parts.push((target, vec![0xC3])); + ranges.push((target, target + 0x10)); + module(&parts, &ranges) + }; + let place = |calling: usize| -> Option<(u32, usize)> { + let (old_bytes, new_bytes) = + (build(0, calling, 0x100300), build(0x40, calling, 0x100380)); + let old_pe = PeFile::parse(&old_bytes).unwrap(); + let new_pe = PeFile::parse(&new_bytes).unwrap(); + let lengths = ( + &Lengths::new(&old_pe.function_starts()), + &Lengths::new(&new_pe.function_starts()), + ); + let (mut old, mut new) = (Side::new(&old_pe), Side::new(&new_pe)); + let callers = calls_into(&old, &BTreeSet::from([0x100300])); + by_callers(&mut old, &mut new, lengths, &callers[&0x100300], 0x100300) + }; + assert_eq!(place(3), Some((0x100380, 3))); + // Two callers are too few to stand. + assert_eq!(place(2), None); + } } From b7a7240cb90cc30e2caa3eba9e3cf7c5f417926c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:48:36 +0000 Subject: [PATCH 20/29] Publish: develop 630540a to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_resolve.rs | 69 +++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index 5f53617..0426b34 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -907,6 +907,21 @@ fn by_callers( (most >= VOTERS_LEAST && (all - most) * 10 <= all).then_some((place, most)) } +/// How many instructions a function must have for its shape to say which function it is. +const SHAPE_LEAST: usize = 8; + +/// Whether two functions are the same instructions from start to end, apart from the addresses, +/// member offsets and constants in them. A short function is not asked: many are alike. +fn same_shape(old: &mut Side, new: &mut Side, from: u32, to: u32) -> bool { + let (before, after) = (old.body(from), new.body(to)); + before.len() >= SHAPE_LEAST + && before.len() == after.len() + && before + .iter() + .zip(after.iter()) + .all(|(left, right)| left.skeleton == right.skeleton) +} + /// Which method gave a place. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Method { @@ -925,6 +940,7 @@ pub enum Method { Neighbours, Callers, Crowd, + Shape, } impl fmt::Display for Method { @@ -945,6 +961,7 @@ impl fmt::Display for Method { Method::Neighbours => "the lengths of the functions beside it", Method::Callers => "the same call in several placed callers", Method::Crowd => "the number of callers that agree", + Method::Shape => "the same instructions throughout", }) } } @@ -1265,6 +1282,23 @@ pub fn resolve( answers.push((Method::Crowd, place)); } } + // The shape of a body is a fact apart from where a table, a text or the + // neighbours put the function. It is not one apart from the calls: functions + // alike in shape are often called from the same places. + let apart = answers.iter().copied().find(|(method, _)| { + matches!( + method, + Method::TableSlot + | Method::SlotShift + | Method::Text + | Method::Neighbours + ) + }); + if let Some((_, place)) = apart { + if same_shape(&mut old, &mut new, target, place) { + answers.push((Method::Shape, place)); + } + } if let Some(place) = by_command.get(&target).copied() { answers.push((Method::Command, place)); let matched = want @@ -2071,4 +2105,39 @@ pub(crate) mod tests { // Two callers are too few to stand. assert_eq!(place(2), None); } + #[test] + fn nfr6_two_functions_of_the_same_instructions_have_the_same_shape() { + // Nine instructions that read a member, with another offset in the new build. + let body = |offset: u8| -> Vec { + let mut bytes = vec![0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20]; + bytes.extend([0x48, 0x8B, 0x41, offset]); + bytes.extend([ + 0x48, 0x89, 0xC6, 0x48, 0x83, 0xC4, 0x20, 0x5B, 0x5F, 0x5E, 0xC3, + ]); + bytes + }; + let old_bytes = module(&[(0x100000, body(0x18))], &[(0x100000, 0x100016)]); + let mut other = body(0x10); + other[2] = 0x55; + let new_bytes = module( + &[ + (0x100100, body(0x10)), + (0x100200, other), + (0x100300, vec![0xC3]), + ], + &[ + (0x100100, 0x100116), + (0x100200, 0x100216), + (0x100300, 0x100301), + ], + ); + let old_pe = PeFile::parse(&old_bytes).unwrap(); + let new_pe = PeFile::parse(&new_bytes).unwrap(); + let (mut old, mut new) = (Side::new(&old_pe), Side::new(&new_pe)); + assert!(same_shape(&mut old, &mut new, 0x100000, 0x100100)); + // Another register saved is another function. + assert!(!same_shape(&mut old, &mut new, 0x100000, 0x100200)); + // A short function has no shape of its own. + assert!(!same_shape(&mut new, &mut old, 0x100300, 0x100300)); + } } From e5f811f4b25f4fc9cebd4c4c471f868a6d1d0d1d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:44:45 +0000 Subject: [PATCH 21/29] Publish: develop fcdd01f to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_features.rs | 112 ++-- rivet/platform/windows/src/row_port.rs | 52 +- rivet/platform/windows/src/row_recipe.rs | 174 +----- rivet/runtime/windows/rows/table.json | 117 ---- rivet/runtime/windows/src/browser/mod.rs | 4 +- .../windows/src/browsers/chromium/layout.rs | 5 + rivet/runtime/windows/src/builds/brave.rs | 103 ---- rivet/runtime/windows/src/builds/chrome.rs | 180 +----- rivet/runtime/windows/src/builds/edge.rs | 45 +- rivet/runtime/windows/src/builds/mod.rs | 93 +--- .../windows/src/builds/omnibox_rows.rs | 7 - rivet/runtime/windows/src/builds/samsung.rs | 2 - rivet/runtime/windows/src/builds/tests.rs | 116 +--- rivet/runtime/windows/src/builds/whale.rs | 3 - rivet/runtime/windows/src/feature.rs | 27 +- .../windows/src/features/address_bar.rs | 3 +- rivet/runtime/windows/src/features/mod.rs | 1 - rivet/runtime/windows/src/features/omnibox.rs | 4 +- .../windows/src/features/vertical_tabs.rs | 522 ------------------ rivet/runtime/windows/src/frame.rs | 78 +-- rivet/runtime/windows/src/hooks/page_area.rs | 108 +++- rivet/runtime/windows/src/lib.rs | 20 - rivet/runtime/windows/src/row_data.rs | 12 +- 23 files changed, 258 insertions(+), 1530 deletions(-) delete mode 100644 rivet/runtime/windows/src/features/vertical_tabs.rs diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs index e9a1acf..099d09f 100644 --- a/rivet/platform/windows/src/row_features.rs +++ b/rivet/platform/windows/src/row_features.rs @@ -57,18 +57,6 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Zero, checks: &["split", "split-"], }, - RowFeature { - name: "vertical tabs", - paths: &[ - "vertical.update_collapse_action", - "vertical.browser_offset", - "vertical.mode_offset", - "vertical.width_offset", - ], - off: &[Off::Flag("vertical.supported")], - clear: Clear::Zero, - checks: &[], - }, RowFeature { name: "sidebar", paths: &[ @@ -126,27 +114,6 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Absent, checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], }, - RowFeature { - // The vertical tab controller's functions and class tables. Only - // `features/vertical_tabs.rs` reads them, and only once its targets are all recorded. - name: "vertical tabs", - paths: &[ - "vertical.slot", - "vertical.should_display", - "vertical.destructor", - "vertical.browser_view_for_browser", - "vertical.hwnd_for_view", - "vertical.notify_mode_changed", - "vertical.browser_view_view_vtable", - "vertical.region_preferred_size", - "vertical.region_preferred_size_slot", - "vertical.region_minimum_size", - "vertical.invalidate_layout", - ], - off: &[Off::Flag("vertical.supported")], - clear: Clear::Absent, - checks: &[], - }, RowFeature { name: "app window", paths: &["app_window."], @@ -161,6 +128,23 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Zero, checks: &["address-suggest", "security-chip"], }, + RowFeature { + // DevTools on a chosen panel and the link under the pointer. Without them DevTools opens + // as the browser opens it, and a long press on a link stays a click. + name: "page tools", + paths: &["page_tools."], + off: &[Off::Part("page_tools")], + clear: Clear::Zero, + checks: &["link-preview"], + }, + RowFeature { + // Without it a bubble keeps the place the browser gives it. + name: "bubble anchor", + paths: &["bubble_anchor"], + off: &[Off::Part("bubble_anchor")], + clear: Clear::Zero, + checks: &["permission-bubble", "password-bubble"], + }, RowFeature { // An empty list is a build without developer colours, whose page keeps the browser's own. name: "developer colours", @@ -169,14 +153,6 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Empty, checks: &["dev-row"], }, - RowFeature { - // Font functions recorded beside the developer colours. No runtime calls them. - name: "developer colours", - paths: &["toolbar.dev.font_list_new", "toolbar.dev.font_new"], - off: &[], - clear: Clear::Absent, - checks: &["dev-row"], - }, RowFeature { name: "frame colour", paths: &["layout.frame_ids", "layout.caption_ink_ids"], @@ -242,6 +218,8 @@ pub enum When { Absent(&'static str), /// A flag that is false. False(&'static str), + /// A flag that is not true: false, null or missing. + NotTrue(&'static str), } pub const UNUSED_WHEN: &[UnusedWhen] = &[ @@ -265,6 +243,15 @@ pub const UNUSED_WHEN: &[UnusedWhen] = &[ when: When::False("vertical.detour_strip"), why: "the build does not leave its tab strip out by a detour", }, + UnusedWhen { + paths: &[ + "side_panel.layout_vtable", + "side_panel.proposed_slot", + "side_panel.proposed", + ], + when: When::NotTrue("side_panel.old_layout"), + why: "a Rivet window is an app window, laid out by the app layout class, not the tabbed one", + }, ]; /// The field a value path names: `layout.frame_ids[2]` names `layout.frame_ids`. @@ -313,6 +300,7 @@ pub fn unused(build: &Value, path: &str) -> Option<&'static str> { at(build, address).is_some_and(|value| !is_recorded(value)) } When::False(flag) => at(build, flag).and_then(Value::as_bool) == Some(false), + When::NotTrue(flag) => at(build, flag).and_then(Value::as_bool) != Some(true), } }) .map(|rule| rule.why) @@ -425,7 +413,7 @@ mod tests { #[test] fn nfr6_every_row_value_of_a_feature_has_one_switch() { - assert_eq!(feature_of("split.view_size").unwrap().name, "split view"); + assert_eq!(feature_of("split.flex_layout_host").unwrap().name, "split view"); assert_eq!( feature_of("toolbar.dev.colours[3][0]").unwrap().name, "developer colours" @@ -482,6 +470,46 @@ mod tests { assert!(unused(&build, "vertical.toolbar_in_view").is_none()); } + #[test] + fn nfr6_page_tools_and_the_bubble_anchor_are_switched_off_as_parts() { + assert_eq!( + feature_of("page_tools.toggle_devtools[0]").unwrap().name, + "page tools" + ); + assert_eq!(feature_of("bubble_anchor[1]").unwrap().name, "bubble anchor"); + let mut build = json!({ + "page_tools": {"update_target_url": ["0x2f475d0", "41574156"]}, + "bubble_anchor": ["0xaa72dc0", "41574156"], + "omnibox": {"match_size": "0x1c8"}, + }); + turn_off(&mut build, "page tools"); + turn_off(&mut build, "bubble anchor"); + assert!(build["page_tools"].is_null()); + assert!(build["bubble_anchor"].is_null()); + assert_eq!(build["omnibox"]["match_size"], "0x1c8"); + let row = json!({"switched_off": [{"feature": "bubble anchor"}]}); + let excused = excused_checks(&row); + assert_eq!(excuses(&excused, "permission-bubble"), Some("bubble anchor")); + assert_eq!(excuses(&excused, "security-chip"), None); + } + + #[test] + fn nfr6_the_tabbed_layout_is_not_a_value_of_a_build_without_the_old_layout() { + let build = json!({"side_panel": {"old_layout": null, "proposed": "0x13c8310"}}); + for path in [ + "side_panel.layout_vtable", + "side_panel.proposed_slot", + "side_panel.proposed", + ] { + assert!(unused(&build, path).is_some(), "{path}"); + } + assert!(unused(&json!({"side_panel": {}}), "side_panel.proposed").is_some()); + // An old-layout build lays out every window with the class its row records. + let old = json!({"side_panel": {"old_layout": true, "proposed": "0x13c8310"}}); + assert!(unused(&old, "side_panel.proposed").is_none()); + assert!(unused(&old, "side_panel.layout_vtable").is_none()); + } + #[test] fn nfr6_a_switched_off_feature_excuses_only_its_own_checks() { let row = diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 000e315..d0519ea 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -451,7 +451,6 @@ pub mod x64 { /// A byte field with no address field of the same name, and where it was read from. fn byte_field_address(key: &str) -> Option<(&'static str, u64)> { Some(match key { - "region_minimum_prologue" => ("region_minimum_size", 0), "bounds_bytes" => ("bounds_in_screen", 0), "page_info_bytes" => ("page_info_path", 0), "hwnd_for_widget_head" => ("hwnd_for_widget", 0), @@ -466,7 +465,7 @@ const NOT_CODE: &[&str] = &["http_icon_name", "nav_icon_names"]; /// Data, rather than instructions, so its shape is not read as code. const DATA_BYTES: &[&str] = &["page_info_bytes"]; -/// The value at a path such as `toolbar.paint_slot`. +/// The value at a path such as `layout.on_paint_slot`. fn at_path<'a>(row: &'a Value, path: &str) -> &'a Value { path.split('.').fold(row, |value, key| &value[key]) } @@ -474,46 +473,11 @@ fn at_path<'a>(row: &'a Value, path: &str) -> &'a Value { /// `(vtable, slot, function)`: a function the runtime replaces in a table, and so a check the new /// module can answer on its own. A function listed twice settles a folded name. const VTABLE_SLOTS: &[(&str, &str, &str)] = &[ - ( - "toolbar.browser_widget_vtable", - "toolbar.paint_slot", - "toolbar.paint", - ), - ( - "toolbar.browser_widget_vtable", - "toolbar.layout_slot", - "toolbar.layout", - ), - ( - "toolbar.plain_widget_vtable", - "toolbar.paint_slot", - "toolbar.paint", - ), - ( - "toolbar.plain_widget_vtable", - "toolbar.layout_slot", - "toolbar.layout", - ), - ( - "toolbar.browser_delegate_vtable", - "toolbar.active_web_contents_slot", - "toolbar.active_web_contents", - ), - ( - "toolbar.web_contents_vtable", - "toolbar.web_contents_title_slot", - "toolbar.web_contents_title", - ), ( "side_panel.layout_vtable", "side_panel.proposed_slot", "side_panel.proposed", ), - ( - "toolbar.infobar_vtable", - "toolbar.infobar_layout_slot", - "toolbar.infobar_layout", - ), ( "layout.frame_vtable", "layout.on_paint_slot", @@ -535,16 +499,6 @@ const VTABLE_SLOTS: &[(&str, &str, &str)] = &[ "layout.caption_paint_slot", "layout.caption_paint", ), - ( - "location_bar.vtable", - "location_bar.slot", - "location_bar.function", - ), - ( - "location_bar.vtable", - "location_bar.preferred_slot", - "location_bar.preferred", - ), ]; fn usize_at(row: &Value, path: &str) -> Option { @@ -831,9 +785,6 @@ const READ_FROM_CODE: &[&str] = &[ /// build. fn settle_carried(row: &mut Value, report: &mut PortReport) { use crate::row_features::{self, Clear, RowFeature}; - report - .derived - .extend(crate::row_recipe::follow(&mut row["build"])); let mut off: BTreeMap<&'static str, (&'static RowFeature, Vec)> = BTreeMap::new(); for (path, reason) in std::mem::take(&mut report.off_values) { if let Some(feature) = row_features::feature_of(&path) { @@ -2834,7 +2785,6 @@ mod tests { "signatures": [["0x101400", "4883ec28"]], }); prior["build"]["vertical"] = json!({ - "supported": false, "detour_strip": false, "should_draw_tab_strip": "0x101500", "should_draw_tab_strip_prologue": "4883ec28", diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index 48829b6..642f712 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -74,53 +74,6 @@ pub const FIELDS: &[Field] = &[ constructor: "app_window.web_view_ctor", }], }, - Field { - path: "toolbar.paint_slot", - recipes: &[ - Recipe::Slot { - vtable: "toolbar.browser_widget_vtable", - function: "toolbar.paint", - }, - Recipe::Slot { - vtable: "toolbar.plain_widget_vtable", - function: "toolbar.paint", - }, - ], - }, - Field { - path: "toolbar.layout_slot", - recipes: &[ - Recipe::Slot { - vtable: "toolbar.browser_widget_vtable", - function: "toolbar.layout", - }, - Recipe::Slot { - vtable: "toolbar.plain_widget_vtable", - function: "toolbar.layout", - }, - ], - }, - Field { - path: "toolbar.active_web_contents_slot", - recipes: &[Recipe::Slot { - vtable: "toolbar.browser_delegate_vtable", - function: "toolbar.active_web_contents", - }], - }, - Field { - path: "toolbar.web_contents_title_slot", - recipes: &[Recipe::Slot { - vtable: "toolbar.web_contents_vtable", - function: "toolbar.web_contents_title", - }], - }, - Field { - path: "toolbar.infobar_layout_slot", - recipes: &[Recipe::Slot { - vtable: "toolbar.infobar_vtable", - function: "toolbar.infobar_layout", - }], - }, Field { path: "side_panel.proposed_slot", recipes: &[Recipe::Slot { @@ -163,20 +116,6 @@ pub const FIELDS: &[Field] = &[ function: "layout.caption_paint", }], }, - Field { - path: "location_bar.slot", - recipes: &[Recipe::Slot { - vtable: "location_bar.vtable", - function: "location_bar.function", - }], - }, - Field { - path: "location_bar.preferred_slot", - recipes: &[Recipe::Slot { - vtable: "location_bar.vtable", - function: "location_bar.preferred", - }], - }, ]; /// What the recipes found for one value. @@ -415,55 +354,11 @@ pub fn derive_row(build: &mut Value, pe: &PeFile) -> Derived { derived } -/// Values that follow from another value of the row by the member order of a public Chromium -/// class, as (path, the value it follows, the distance). `ui/views/view.h` declares `parent_`, -/// then `children_`, then the members up to `bounds_`, 0x30 bytes after `parent_`. The runtime -/// takes them the same way, so they are written from the value they follow and never carried. -pub const FOLLOWS: &[(&str, &str, i64)] = &[ - ("app_window.view_parent", "layout.view_bounds_offset", -0x30), - ( - "app_window.view_children", - "layout.view_bounds_offset", - -0x28, - ), -]; - -/// Writes each value of `FOLLOWS` the row has from the value it follows. -pub fn follow(build: &mut Value) -> Vec { - let mut read = Vec::new(); - for (path, from, by) in FOLLOWS { - let Some(base) = number(at_path(build, from)).filter(|base| *base >= 0x30) else { - continue; - }; - let (parent, key) = path.split_once('.').expect("a path has a parent"); - let Some(old) = number(&build[parent][key]) else { - continue; - }; - let value = (base as i64 + by) as u64; - let is_string = build[parent][key].is_string(); - build[parent][key] = if is_string { - Value::String(format!("{value:#x}")) - } else { - json!(value) - }; - read.push(if old == value { - format!("{path}: {value:#x}, from {from}") - } else { - format!("{path}: {old:#x} -> {value:#x}, from {from}") - }); - } - read -} - /// Values Rivet chooses rather than reads from a build, such as how long it waits before it opens -/// a new tab, how far its toolbar starts after the browser view's edge to leave room for Rivet's -/// toggle button, and the DIPs it adds to the top inset it reports. The row carries them for the -/// runtime, so they are kept from the prior row. -pub const SETTINGS: &[&str] = &[ - "tabs.new_tab_delay_ms", - "vertical.toolbar_leading", - "layout.top_inset_adjust", -]; +/// a new tab and how far its toolbar starts after the browser view's edge to leave room for +/// Rivet's toggle button. The row carries them for the runtime, so they are kept from the prior +/// row. +pub const SETTINGS: &[&str] = &["tabs.new_tab_delay_ms", "vertical.toolbar_leading"]; /// Lists of `[id, colour]` pairs: the id is a value of the build, and the colour is Rivet's choice. pub const ID_COLOUR_PAIRS: &[&str] = &["toolbar.dev.colours"]; @@ -540,7 +435,6 @@ pub fn without_recipe(build: &Value) -> Vec { && !FIELDS.iter().any(|field| field.path == path) && !SETTINGS.contains(&path.as_str()) && !crate::command_ids::ROW_PATHS.contains(&path.as_str()) - && !FOLLOWS.iter().any(|(follows, _, _)| follows == path) }); out } @@ -690,21 +584,32 @@ mod tests { (0x10_8100, second.as_slice()), ]); let pe = PeFile::parse(&bytes).unwrap(); - let mut build = json!({ - "toolbar": { - "browser_widget_vtable": "0x108000", "plain_widget_vtable": "0x108100", - "paint": "0x101100", "paint_slot": "0x1", + let build = json!({ + "layout": { + "frame_vtable": "0x108000", "caption_vtable": "0x108100", + "layout": "0x101100", "layout_slot": "0x1", } }); - let derived = derive_row(&mut build, &pe); - assert!( - derived - .failed - .iter() - .any(|line| line.starts_with("toolbar.paint_slot: its recipes disagree")), - "{:?}", - derived.failed - ); + // No value of a row has two recipes today, so the rule is checked on a field made here. + let field = Field { + path: "layout.layout_slot", + recipes: &[ + Recipe::Slot { + vtable: "layout.frame_vtable", + function: "layout.layout", + }, + Recipe::Slot { + vtable: "layout.caption_vtable", + function: "layout.layout", + }, + ], + }; + match derive_field(&field, &build, &pe) { + Outcome::Failed(reason) => { + assert!(reason.starts_with("its recipes disagree"), "{reason}"); + } + other => panic!("{other:?}"), + } } #[test] @@ -720,23 +625,6 @@ mod tests { ); } - #[test] - fn nfr6_a_views_parent_and_children_follow_its_bounds() { - let mut build = json!({ - "layout": {"view_bounds_offset": "0x1c0"}, - "app_window": {"view_parent": "0x198", "view_children": "0x1a0"}, - }); - assert_eq!(without_recipe(&build), vec!["layout.view_bounds_offset"]); - let read = follow(&mut build); - assert_eq!(build["app_window"]["view_parent"], "0x190"); - assert_eq!(build["app_window"]["view_children"], "0x198"); - assert_eq!(read.len(), 2, "{read:?}"); - // A row without the app window part gets none. - let mut bare = json!({"layout": {"view_bounds_offset": "0x1c8"}, "app_window": null}); - assert!(follow(&mut bare).is_empty()); - assert!(bare["app_window"].is_null()); - } - #[test] fn nfr6_rivet_settings_are_not_values_of_the_build() { let build = json!({ @@ -753,13 +641,9 @@ mod tests { ); let chosen = json!({ "vertical": {"toolbar_leading": 26, "toolbar_in_view": "0x60"}, - "layout": {"top_inset_adjust": 0}, }); assert_eq!(without_recipe(&chosen), vec!["vertical.toolbar_in_view"]); - assert_eq!( - settings(&chosen), - vec!["vertical.toolbar_leading", "layout.top_inset_adjust"] - ); + assert_eq!(settings(&chosen), vec!["vertical.toolbar_leading"]); assert_eq!( settings(&build), vec![ diff --git a/rivet/runtime/windows/rows/table.json b/rivet/runtime/windows/rows/table.json index 90ba91d..2604b42 100644 --- a/rivet/runtime/windows/rows/table.json +++ b/rivet/runtime/windows/rows/table.json @@ -28,8 +28,6 @@ "set_bounds_prologue": "4157415641554154565755534881ece8", "set_contents": "0x1148800", "set_contents_prologue": "5657534883ec304889d74889cee83e6b", - "view_children": "0x1a0", - "view_parent": "0x198", "web_view_ctor": "0xba8700", "web_view_ctor_prologue": "5657534883ec304889ce488b052fa9e3", "web_view_size": "0x528", @@ -93,7 +91,6 @@ "stack_at_top": "0xaa90920", "stack_at_top_prologue": "415741565657", "top_inset": "0x198b7f0", - "top_inset_adjust": 0, "top_inset_slot": "0x7f", "view_bounds_offset": "0x1c8" }, @@ -166,7 +163,6 @@ "input_new": "0x25380f0", "input_omit_asynchronous": "0x1b3", "input_prevent_inline": "0x1b0", - "input_size": "0x478", "match_contents": "0x2a0", "match_description": "0x2d0", "match_destination": "0x68", @@ -387,7 +383,6 @@ "supported": true, "update_border": "0x20f3330", "update_border_prologue": "41565657534883ec484889ce", - "view_size": "0x1d0", "web_contents_focused": "0xa27f190", "web_contents_focused_prologue": "56574883ec28488b8198030000" }, @@ -592,14 +587,9 @@ ] ], "console": 40005, - "font_list_new": "0x2fc4af0", - "font_list_new_prologue": "5657534883ec204889d34889ce", - "font_new": "0x2fc4e00", - "font_new_prologue": "564883ec204889ce4889d14489c2", "inspect": 40023 }, "get_color": "0x52b0790", - "get_color_bytes": "415741564154565755534883ec2089d7", "get_widget_slot": "0xb", "skip": "", "toolbar_layout": "0x1309170", @@ -612,32 +602,13 @@ 81 ], "vertical": { - "browser_offset": "0x1b8", - "browser_view_for_browser": "0x2119b0", - "browser_view_view_vtable": "0xfce91b0", - "destructor": "0x2890200", - "destructor_prologue": "56574883ec2889d74889cee8", "detour_strip": false, - "hwnd_for_view": "0x348d8a0", - "invalidate_layout": "0x44a1140", - "invalidate_layout_prologue": "415741564155415456575553", - "mode_offset": "0x1e8", - "notify_mode_changed": "0x9f8eb70", - "region_minimum_prologue": "56574883ec284889d64889cf48c70200000000", - "region_minimum_size": "0xbaa13b0", - "region_preferred_size": "0xbaa1440", - "region_preferred_size_slot": "0xfd84f40", "set_bounds_rect": "0x7fff0000", "set_bounds_rect_prologue": "00", - "should_display": "0x3481180", "should_draw_tab_strip": "0x500f570", "should_draw_tab_strip_prologue": "565753", - "slot": "0xfc1d120", - "supported": true, "toolbar_in_view": "0x0", "toolbar_leading": 0, - "update_collapse_action": "0x208f7d0", - "width_offset": "0x1cc", "window_feature": "0x7fff0000", "window_feature_callers": [ "0x0", @@ -686,8 +657,6 @@ "set_bounds_prologue": "4157415641554154565755534881ece8", "set_contents": "0x11487e0", "set_contents_prologue": "5657534883ec304889d74889cee85e6b", - "view_children": "0x1a0", - "view_parent": "0x198", "web_view_ctor": "0xba8700", "web_view_ctor_prologue": "5657534883ec304889ce488b052fa9e3", "web_view_size": "0x528", @@ -751,7 +720,6 @@ "stack_at_top": "0xaa90770", "stack_at_top_prologue": "415741565657", "top_inset": "0x198b800", - "top_inset_adjust": 0, "top_inset_slot": "0x7f", "view_bounds_offset": "0x1c8" }, @@ -824,7 +792,6 @@ "input_new": "0x2538040", "input_omit_asynchronous": "0x1b3", "input_prevent_inline": "0x1b0", - "input_size": "0x478", "match_contents": "0x2a0", "match_description": "0x2d0", "match_destination": "0x68", @@ -1041,7 +1008,6 @@ "supported": true, "update_border": "0x20f32f0", "update_border_prologue": "41565657534883ec484889ce", - "view_size": "0x1d0", "web_contents_focused": "0xa27efe0", "web_contents_focused_prologue": "56574883ec28488b8198030000" }, @@ -1246,14 +1212,9 @@ ] ], "console": 40005, - "font_list_new": "0x2fc49f0", - "font_list_new_prologue": "5657534883ec204889d34889ce", - "font_new": "0x2fc4d00", - "font_new_prologue": "564883ec204889ce4889d14489c2", "inspect": 40023 }, "get_color": "0x52b0650", - "get_color_bytes": "415741564154565755534883ec2089d7", "get_widget_slot": "0xb", "skip": "", "toolbar_layout": "0x1309160", @@ -1266,32 +1227,13 @@ 82 ], "vertical": { - "browser_offset": "0x1b8", - "browser_view_for_browser": "0x2119b0", - "browser_view_view_vtable": "0xfce91b0", - "destructor": "0x2890140", - "destructor_prologue": "56574883ec2889d74889cee8", "detour_strip": false, - "hwnd_for_view": "0x348d750", - "invalidate_layout": "0x44a0ff0", - "invalidate_layout_prologue": "415741564155415456575553", - "mode_offset": "0x1e8", - "notify_mode_changed": "0x9f8e9d0", - "region_minimum_prologue": "56574883ec284889d64889cf48c70200000000", - "region_minimum_size": "0xbaa11e0", - "region_preferred_size": "0xbaa1270", - "region_preferred_size_slot": "0xfd84f40", "set_bounds_rect": "0x7fff0000", "set_bounds_rect_prologue": "00", - "should_display": "0x3481030", "should_draw_tab_strip": "0x500f430", "should_draw_tab_strip_prologue": "565753", - "slot": "0xfc1d120", - "supported": true, "toolbar_in_view": "0x0", "toolbar_leading": 0, - "update_collapse_action": "0x208f790", - "width_offset": "0x1cc", "window_feature": "0x7fff0000", "window_feature_callers": [ "0x0", @@ -1340,8 +1282,6 @@ "set_bounds_prologue": "4157415641554154565755534881ece8", "set_contents": "0x10d60e0", "set_contents_prologue": "5657534883ec304889d74889cee85e41", - "view_children": "0x1a0", - "view_parent": "0x198", "web_view_ctor": "0x92a120", "web_view_ctor_prologue": "5657534883ec304889ce488b050f6f55", "web_view_size": "0x520", @@ -1405,7 +1345,6 @@ "stack_at_top": "0xaf47650", "stack_at_top_prologue": "415741565657", "top_inset": "0xaad20d0", - "top_inset_adjust": 0, "top_inset_slot": "0x7e", "view_bounds_offset": "0x1c8" }, @@ -1478,7 +1417,6 @@ "input_new": "0x23724c0", "input_omit_asynchronous": "0x1b3", "input_prevent_inline": "0x1b0", - "input_size": "0x478", "match_contents": "0x2a0", "match_description": "0x2d0", "match_destination": "0x68", @@ -1695,7 +1633,6 @@ "supported": true, "update_border": "0x214ae00", "update_border_prologue": "41565657534883ec484889ce", - "view_size": "0x1d0", "web_contents_focused": "0xab95530", "web_contents_focused_prologue": "56574883ec28488b8190030000" }, @@ -1900,14 +1837,9 @@ ] ], "console": 40005, - "font_list_new": "0x3239200", - "font_list_new_prologue": "5657534883ec204889d34889ce", - "font_new": "0x3239520", - "font_new_prologue": "564883ec204889ce4889d14489c2", "inspect": 40023 }, "get_color": "0x454eef0", - "get_color_bytes": "415741564154565755534883ec2089d7", "get_widget_slot": "0xb", "skip": "", "toolbar_layout": "0x1196250", @@ -1920,32 +1852,13 @@ 39 ], "vertical": { - "browser_offset": "0x1b8", - "browser_view_for_browser": "0x319000", - "browser_view_view_vtable": "0x1016e590", - "destructor": "0x2aaed80", - "destructor_prologue": "56574883ec2889d74889cee8", "detour_strip": false, - "hwnd_for_view": "0x3739530", - "invalidate_layout": "0x4587b10", - "invalidate_layout_prologue": "415741564155415456575553", - "mode_offset": "0x1e8", - "notify_mode_changed": "0xa875700", - "region_minimum_prologue": "56574883ec284889d64889cf48c70200000000", - "region_minimum_size": "0xa8d3860", - "region_preferred_size": "0xa8d38f0", - "region_preferred_size_slot": "0x10176640", "set_bounds_rect": "0x7fff0000", "set_bounds_rect_prologue": "00", - "should_display": "0x372f620", "should_draw_tab_strip": "0x54d6590", "should_draw_tab_strip_prologue": "565753", - "slot": "0x100ade20", - "supported": true, "toolbar_in_view": "0x0", "toolbar_leading": 0, - "update_collapse_action": "0x2044100", - "width_offset": "0x1cc", "window_feature": "0x7fff0000", "window_feature_callers": [ "0x0", @@ -1994,8 +1907,6 @@ "set_bounds_prologue": "4157415641554154565755534881ecb8", "set_contents": "0x2a7d730", "set_contents_prologue": "5657534883ec204889d74889ce4889d1", - "view_children": "0x1a0", - "view_parent": "0x198", "web_view_ctor": "0x2b3a51a", "web_view_ctor_prologue": "4157415641545657534883ec384889ce", "web_view_size": "0x5b0" @@ -2055,7 +1966,6 @@ "stack_at_top": "0xb41dd9e", "stack_at_top_prologue": "415656575348", "top_inset": "0x3402f60", - "top_inset_adjust": 0, "top_inset_slot": "0xa4", "view_bounds_offset": "0x1c8" }, @@ -2128,7 +2038,6 @@ "input_new": "0x29687b0", "input_omit_asynchronous": "0x22b", "input_prevent_inline": "0x228", - "input_size": "0x500", "match_contents": "0x2a0", "match_description": "0x2d0", "match_destination": "0x68", @@ -2323,7 +2232,6 @@ "supported": true, "update_border": "0x2e5a182", "update_border_prologue": "4156565755534883ec5089d5", - "view_size": "0x1d0", "web_contents_focused": "0x2e5a01a", "web_contents_focused_prologue": "415741564155415456575553" }, @@ -2535,14 +2443,9 @@ ] ], "console": 40005, - "font_list_new": "0x2b3b05e", - "font_list_new_prologue": "5657534883ec204889d34889ce", - "font_new": "0x26aa68c", - "font_new_prologue": "564883ec204889ce4889d14489c2", "inspect": 40023 }, "get_color": "0x1030e6e", - "get_color_bytes": "4157415641545657534883ec2889d748", "get_widget_slot": "0xa", "skip": "updateicon anchor visible", "toolbar_layout": "0x7fff0000", @@ -2555,33 +2458,13 @@ 58 ], "vertical": { - "browser_offset": "0x1b8", - "browser_view_for_browser": "0x10fc0fa", - "browser_view_view_vtable": "0x11940340", - "destructor": "0xa3dcac0", - "destructor_prologue": "56574883ec2889d74889cee8", "detour_strip": false, - "hwnd_for_view": "0x10a6589", - "invalidate_layout": "0x1028650", - "invalidate_layout_prologue": "41574156565755534883ec38", - "mode_offset": "0x1e8", - "notify_mode_changed": "0xa3db406", - "region_minimum_prologue": "56574883ec284889d64889cf48c70200000000", - "region_minimum_size": "0xcae84e0", - "region_preferred_size": "0xcae8560", - "region_preferred_size_slot": "0x11827450", "set_bounds_rect": "0x7fff0000", "set_bounds_rect_prologue": "00", - "should_display": "0xa3dc360", "should_draw_tab_strip": "0x1038320", "should_draw_tab_strip_prologue": "564883ec204889ce488b8918060000", - "slot": "0x11736700", - "supported": false, "toolbar_in_view": "0x0", "toolbar_leading": 0, - "top_row": null, - "update_collapse_action": "0x0", - "width_offset": "0x1cc", "window_feature": "0x7fff0000", "window_feature_callers": [ "0x0", diff --git a/rivet/runtime/windows/src/browser/mod.rs b/rivet/runtime/windows/src/browser/mod.rs index 46e33f2..54ce9de 100644 --- a/rivet/runtime/windows/src/browser/mod.rs +++ b/rivet/runtime/windows/src/browser/mod.rs @@ -21,14 +21,14 @@ //! | C. Page address and title | page_bar, control, command_bar, link_rules | DevTools target info (`Pages`) | //! | D. Security level and page info | address_bar, omnibox | DevTools security state, then build values | //! | E. New, close, select and restore a tab | tabs, control, tab_list | command ids and DevTools | -//! | F. Tab order and groups | tabs, tab_list, vertical_tabs | build values, reflection to read | +//! | F. Tab order and groups | tabs, tab_list | build values, reflection to read | //! | G. Split view and the second page view | split, split_grid, second_view | build values, reflection for bounds | //! | H. Infobars per pane | pane_infobar | reflection | //! | I. Mini window out and back | mini_window | command id out, build values back | //! | J. App window without a tab strip | app_window, tab_strip | build values | //! | K. Address suggestions | omnibox | build values | //! | L. Frame, caption and paint | frame_layout, look, widgets | build values, reflection to find views | -//! | M. Vertical tabs, side panel, bubbles, DevTools | vertical_tabs, side_panel, bubble_anchor, dev_tools | command ids, reflection, build values | +//! | M. Side panel, bubbles, DevTools | side_panel, bubble_anchor, dev_tools | command ids, reflection, build values | //! //! Only the traits of groups A, C and I (`TabMoves`, for the Mini Window's opening) exist so far. //! A trait is added when the first feature that needs it moves, never before. diff --git a/rivet/runtime/windows/src/browsers/chromium/layout.rs b/rivet/runtime/windows/src/browsers/chromium/layout.rs index 052bf49..b45cae6 100644 --- a/rivet/runtime/windows/src/browsers/chromium/layout.rs +++ b/rivet/runtime/windows/src/browsers/chromium/layout.rs @@ -108,6 +108,11 @@ pub(crate) unsafe extern "system" fn proposed_layout( static APP_ORIGINAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// Whether the app window's layout is patched in this process. +pub(crate) fn app_layout_patched() -> bool { + APP_ORIGINAL.load(std::sync::atomic::Ordering::Acquire) != 0 +} + /// Takes the place of `BrowserViewAppLayoutImpl::CalculateProposedLayout`, the layout of an app /// window, which keeps its views where the tabbed layout keeps them. unsafe extern "system" fn app_proposed_layout( diff --git a/rivet/runtime/windows/src/builds/brave.rs b/rivet/runtime/windows/src/builds/brave.rs index 52d74ff..8234005 100644 --- a/rivet/runtime/windows/src/builds/brave.rs +++ b/rivet/runtime/windows/src/builds/brave.rs @@ -1,6 +1,5 @@ //! Rows for Brave builds. -use super::chrome::DEV_CHROME_156; use super::*; /// Brave's colour ids sit 17 above Chrome's from 574 on. @@ -31,7 +30,6 @@ const DEV_BRAVE_156: DevMode = DevMode { (1072, DEV_ICON_HOT), (1073, DEV_ICON), ], - ..DEV_CHROME_156 }; /// Brave 156.1.98.62 (Chromium 156.0.8078.74). Brave publishes its symbols, so this row is filled from @@ -52,42 +50,12 @@ pub static BRAVE: Build = Build { get_widget_slot: Some(11), dev: DEV_BRAVE_156, get_color: 0x06A9A890, // ?GetColor@ColorProvider@ui@@QEBAIH@Z - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x02EE93A0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x02EEBD70, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: ABSENT, }, vertical: VerticalTabs { - supported: true, - slot: 0x11066E60, // the vtable of tabs::VerticalTabStripStateControllerImpl, at ShouldDisplayVerticalTabs - should_display: 0x039AC440, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x00365C40, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x03BF81A0, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x0B4B7890, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x02916550, // ?UpdateCollapseActionItem@VerticalTabStripStateControllerImpl@tabs@@AEAAXXZ - destructor: 0x02A3E050, // the scalar deleting destructor, two words before ShouldDisplayVerticalTabs - destructor_prologue: &[ - 0x41, 0x56, 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x28, 0x89, 0xD7, 0x48, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x1112C600, // the browser view vtable - region_preferred_size: 0x0CF05490, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x11131130, // slot 74 of ??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@ - invalidate_layout: 0x05CB4A60, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0CF05400, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x48, 0x89, 0xD6, 0x48, 0x89, 0xCF, 0x48, 0xC7, - 0x02, 0x00, 0x00, 0x00, 0x00, - ], should_draw_tab_strip: 0x0661FA10, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], detour_strip: false, @@ -202,7 +170,6 @@ pub static BRAVE: Build = Build { flex_layout: 0x067B5A30, // ?CalculateProposedLayout@FlexLayout@views flex_layout_host: 0x38, location_bar_vtable: ABSENT, - view_size: 0x1D0, signatures: &[ ( 0x0B4E1CF0, @@ -298,7 +265,6 @@ pub static BRAVE: Build = Build { frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x67D, 0x67E, 0x67F], - top_inset_adjust: -12, provider_verified: true, }, }; @@ -327,8 +293,6 @@ pub static BRAVE_63: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x68, ], - view_parent: 0x198, - view_children: 0x1A0, operator_new: 0x6F4DE00, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xE8, 0xD2, 0xCB, 0x22, 0xFE, @@ -383,42 +347,12 @@ pub static BRAVE_63: Build = Build { get_widget_slot: Some(11), dev: DEV_BRAVE_156, get_color: 0x06A5CB00, // ?GetColor@ColorProvider@ui@@QEBAIH@Z - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x02F353F0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x02F37C00, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: 0x01378F50, // ?Layout@ToolbarView, found statically and unverified }, vertical: VerticalTabs { - supported: true, - slot: 0x11024BD8, // the vtable of tabs::VerticalTabStripStateControllerImpl, at ShouldDisplayVerticalTabs - should_display: 0x039C3900, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x00227A40, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x03C06C50, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x0B4738F0, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x029F0BE0, // ?UpdateCollapseActionItem@VerticalTabStripStateControllerImpl@tabs@@AEAAXXZ - destructor: 0x02B00B60, // the scalar deleting destructor, two words before ShouldDisplayVerticalTabs - destructor_prologue: &[ - 0x41, 0x56, 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x28, 0x89, 0xD7, 0x48, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x110EA540, // the browser view vtable - region_preferred_size: 0x0CEC7C70, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x110EF070, // slot 74 of ??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@ - invalidate_layout: 0x05A276E0, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0CEC7BE0, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x48, 0x89, 0xD6, 0x48, 0x89, 0xCF, 0x48, 0xC7, - 0x02, 0x00, 0x00, 0x00, 0x00, - ], should_draw_tab_strip: 0x065EAD20, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], detour_strip: false, @@ -533,7 +467,6 @@ pub static BRAVE_63: Build = Build { flex_layout: 0x06746FC0, // ?CalculateProposedLayout@FlexLayout@views flex_layout_host: 0x38, location_bar_vtable: 0x11133840, // ??_7LocationBarView@@6BLayerDelegate@ui@@@, found statically and unverified - view_size: 0x1D0, signatures: &[ ( 0x0B49DD10, @@ -666,7 +599,6 @@ pub static BRAVE_63: Build = Build { frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x67D, 0x67E, 0x67F], - top_inset_adjust: 0, // Chromium's own GetTopInset, as on Chrome provider_verified: true, }, }; @@ -700,7 +632,6 @@ const DEV_BRAVE_157: DevMode = DevMode { (1079, DEV_ICON_HOT), (1080, DEV_ICON), ], - ..DEV_CHROME_156 }; /// Brave 157.1.99.55 (Chromium 157.0.8103.39), ported by name from the 156.1.98.63 row with this @@ -729,8 +660,6 @@ pub static BRAVE_157_55: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x68, ], - view_parent: 0x198, - view_children: 0x1A0, operator_new: 0x73F5220, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xE8, 0x02, 0x5B, 0x09, 0xFE, @@ -785,42 +714,12 @@ pub static BRAVE_157_55: Build = Build { get_widget_slot: Some(11), dev: DEV_BRAVE_157, get_color: 0x05B6CB30, // ?GetColor@ColorProvider@ui@@QEBAIH@Z - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x00D6A480, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x03153E70, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: 0x011E0460, // ?Layout@ToolbarView, found statically and unverified }, vertical: VerticalTabs { - supported: true, - slot: 0x11501450, // the vtable of tabs::VerticalTabStripStateControllerImpl, at ShouldDisplayVerticalTabs - should_display: 0x03CC0CB0, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x00363EB0, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x03EABEE0, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x0B7ABF10, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x02A4CCE0, // ?UpdateCollapseActionItem@VerticalTabStripStateControllerImpl@tabs@@AEAAXXZ - destructor: 0x02C793A0, // the scalar deleting destructor, two words before ShouldDisplayVerticalTabs - destructor_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30, 0x89, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x11598D50, // the browser view vtable - region_preferred_size: 0x0B5116A0, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x1159D840, // slot 74 of ??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@ - invalidate_layout: 0x05B46EF0, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0B511610, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x48, 0x89, 0xD6, 0x48, 0x89, 0xCF, 0x48, 0xC7, - 0x02, 0x00, 0x00, 0x00, 0x00, - ], should_draw_tab_strip: 0x06A93F30, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], detour_strip: false, @@ -935,7 +834,6 @@ pub static BRAVE_157_55: Build = Build { flex_layout: 0x069ED3B0, // ?CalculateProposedLayout@FlexLayout@views flex_layout_host: 0x38, location_bar_vtable: 0x115CC710, // ??_7LocationBarView@@6BLayerDelegate@ui@@@, found statically and unverified - view_size: 0x1D0, signatures: &[ ( 0x0BDD3650, @@ -1068,7 +966,6 @@ pub static BRAVE_157_55: Build = Build { frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x684, 0x685, 0x686], - top_inset_adjust: 0, // Chromium's own GetTopInset, as on Chrome provider_verified: true, }, }; diff --git a/rivet/runtime/windows/src/builds/chrome.rs b/rivet/runtime/windows/src/builds/chrome.rs index b51e221..d3b6524 100644 --- a/rivet/runtime/windows/src/builds/chrome.rs +++ b/rivet/runtime/windows/src/builds/chrome.rs @@ -2,7 +2,7 @@ use super::*; -pub(super) const DEV_CHROME_156: DevMode = DevMode { +const DEV_CHROME_156: DevMode = DevMode { colours: &[ (0x13C, DEV_GROUND), (1590, DEV_GROUND), @@ -29,21 +29,6 @@ pub(super) const DEV_CHROME_156: DevMode = DevMode { (1055, DEV_ICON_HOT), (1056, DEV_ICON), ], - ..UNCHECKED_DEV -}; - -/// Chrome 156.0.8078.74, whose font functions are read from its public symbols and checked against -/// the module file. -const DEV_CHROME_156_74: DevMode = DevMode { - font_new: 0x02F7_2AE0, // ??0Font@gfx@@QEAA@AEBV?$basic_string@DU?$char_traits@D@__Cr@std@@V?$allocator@D@23@@__Cr@std@@H@Z - font_new_prologue: &[ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x89, 0xD1, 0x44, 0x89, 0xC2, - ], - font_list_new: 0x02F7_27D0, // ??0FontList@gfx@@QEAA@AEBVFont@1@@Z - font_list_new_prologue: &[ - 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xD3, 0x48, 0x89, 0xCE, - ], - ..DEV_CHROME_156 }; pub static CHROME: Build = Build { @@ -59,42 +44,12 @@ pub static CHROME: Build = Build { get_widget_slot: Some(11), dev: DEV_CHROME_156, get_color: 0x04AA24F0, - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x00D5_64A0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x0315_C7C0, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: ABSENT, }, vertical: VerticalTabs { - supported: true, - slot: 0x0FDA_FE00, // .weak.??_7VerticalTabStripStateControllerImpl@tabs@@6BVerticalTabStripStateController@1@@.default.?R - should_display: 0x0369_C6E0, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x0034_D3E0, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x036A_A950, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x0A1D_B330, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x020F_3D90, // ??0VerticalTabStripStateController@tabs@@IEAA@AEAVBrowserWindowInterface@@@Z - destructor: 0x0296_C3F0, // ??_EVerticalTabStripStateControllerImpl@tabs@@UEAAPEAXI@Z - destructor_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xec, 0x28, 0x89, 0xd7, 0x48, 0x89, 0xce, 0xe8, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x0FE7_BF68, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat - region_preferred_size: 0x0BC7_FA80, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x0FF1_7CF8, // .weak.??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$Cd - invalidate_layout: 0x0411_6480, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0BC7_F9F0, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xec, 0x28, 0x48, 0x89, 0xd6, 0x48, 0x89, 0xcf, 0x48, 0xc7, - 0x02, 0, 0, 0, 0, - ], should_draw_tab_strip: 0x0528_6C00, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], window_feature: ABSENT, @@ -255,7 +210,6 @@ pub static CHROME: Build = Build { flex_layout: 0x054FCC60, // views::FlexLayout::CalculateProposedLayout flex_layout_host: 0x38, location_bar_vtable: 0x0FE86BE8, // LocationBarView primary vtable - view_size: 0x1D0, signatures: &[ ( 0x0A20_5410, @@ -381,7 +335,6 @@ pub static CHROME: Build = Build { browser_window_in_view: 0x1f0, caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_ink_ids: &[0x66C, 0x66D, 0x66E], - top_inset_adjust: 0, }, }; @@ -407,8 +360,6 @@ pub static CHROME_156_74: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x68, ], - view_parent: 0x198, - view_children: 0x1A0, operator_new: 0x5A1E310, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xE8, 0x12, 0xD5, 0x21, 0xFE, @@ -461,44 +412,14 @@ pub static CHROME_156_74: Build = Build { version: [156, 0, 8078, 74], toolbar: Toolbar { get_widget_slot: Some(11), - dev: DEV_CHROME_156_74, + dev: DEV_CHROME_156, get_color: 0x0535_9A80, - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x02F4_6B00, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x02F4_8CE0, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: 0x011C_98D0, // ?Layout@ToolbarView@@UEAAXVPassKey@@@Z }, vertical: VerticalTabs { - supported: true, - slot: 0x0FC2_23A8, // .weak.??_7VerticalTabStripStateControllerImpl@tabs@@6BVerticalTabStripStateController@1@@.default.?R - should_display: 0x0345_2850, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x002E_75B0, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x0346_0F20, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x09F9_9710, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x01DB_9180, // ??0VerticalTabStripStateController@tabs@@IEAA@AEAVBrowserWindowInterface@@@Z - destructor: 0x02AD_3050, // ??_EVerticalTabStripStateControllerImpl@tabs@@UEAAPEAXI@Z - destructor_prologue: &[ - 0x41, 0x56, 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x28, 0x89, 0xD7, 0x48, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x0FCE_E270, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat - region_preferred_size: 0x0BAA_5650, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x0FD8_A000, // .weak.??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$Cd - invalidate_layout: 0x046F_2F30, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0BAA_55C0, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xec, 0x28, 0x48, 0x89, 0xd6, 0x48, 0x89, 0xcf, 0x48, 0xc7, - 0x02, 0, 0, 0, 0, - ], should_draw_tab_strip: 0x0504_F960, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], window_feature: ABSENT, @@ -659,7 +580,6 @@ pub static CHROME_156_74: Build = Build { flex_layout: 0x0522_E1B0, // views::FlexLayout::CalculateProposedLayout flex_layout_host: 0x38, location_bar_vtable: 0x0FCF_8EF0, // LocationBarView primary vtable - view_size: 0x1D0, signatures: &[ ( 0x09FC_3C40, @@ -785,23 +705,9 @@ pub static CHROME_156_74: Build = Build { browser_window_in_view: 0x1f0, caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_ink_ids: &[0x66C, 0x66D, 0x66E], - top_inset_adjust: 0, }, }; -/// Chrome 156.0.8078.80's font functions, found by name in its public symbols and unverified. -const DEV_CHROME_156_80: DevMode = DevMode { - font_new: 0x02FC_50E0, // ??0Font@gfx@@QEAA@AEBV?$basic_string@DU?$char_traits@D@__Cr@std@@V?$allocator@D@23@@__Cr@std@@H@Z - font_new_prologue: &[ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x89, 0xD1, 0x44, 0x89, 0xC2, - ], - font_list_new: 0x02FC_4DD0, // ??0FontList@gfx@@QEAA@AEBVFont@1@@Z - font_list_new_prologue: &[ - 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xD3, 0x48, 0x89, 0xCE, - ], - ..DEV_CHROME_156 -}; - /// Google Chrome 156.0.8078.80, ported by name from the 156.0.8078.74 row with this build's own public /// symbols, and every recorded first byte read from the installed module. Every address here was /// found statically and is unverified: no window of this build has been driven yet, so the launcher @@ -827,8 +733,6 @@ pub static CHROME_156_80: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x68, ], - view_parent: 0x198, - view_children: 0x1A0, operator_new: 0x59FC170, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xE8, 0xB2, 0x85, 0x20, 0xFE, @@ -881,44 +785,14 @@ pub static CHROME_156_80: Build = Build { version: [156, 0, 8078, 80], toolbar: Toolbar { get_widget_slot: Some(11), - dev: DEV_CHROME_156_80, + dev: DEV_CHROME_156, get_color: 0x052B_06D0, - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x02F9_C1F0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x02F9_E210, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: 0x0130_94D0, // ?Layout@ToolbarView@@UEAAXVPassKey@@@Z }, vertical: VerticalTabs { - supported: true, - slot: 0x0FC1_D120, // .weak.??_7VerticalTabStripStateControllerImpl@tabs@@6BVerticalTabStripStateController@1@@.default.?R - should_display: 0x0348_10D0, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x0021_19B0, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x0348_D7F0, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x09F8_E9D0, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x0208_FB20, // ??0VerticalTabStripStateController@tabs@@IEAA@AEAVBrowserWindowInterface@@@Z - destructor: 0x0289_05D0, // ??_EVerticalTabStripStateControllerImpl@tabs@@UEAAPEAXI@Z - destructor_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x89, 0xD7, 0x48, 0x89, 0xCE, 0xE8, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x0FCE_91B0, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat - region_preferred_size: 0x0BAA_1270, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x0FD8_4F40, // .weak.??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$Cd - invalidate_layout: 0x044A_1090, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0BAA_11E0, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xec, 0x28, 0x48, 0x89, 0xd6, 0x48, 0x89, 0xcf, 0x48, 0xc7, - 0x02, 0, 0, 0, 0, - ], should_draw_tab_strip: 0x0500_F4B0, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], window_feature: ABSENT, @@ -1079,7 +953,6 @@ pub static CHROME_156_80: Build = Build { flex_layout: 0x051C_9140, // views::FlexLayout::CalculateProposedLayout flex_layout_host: 0x38, location_bar_vtable: 0x0FCF_3E30, // LocationBarView primary vtable - view_size: 0x1D0, signatures: &[ ( 0x09FB_8F00, @@ -1205,11 +1078,10 @@ pub static CHROME_156_80: Build = Build { browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], caption_ink_ids: &[0x66C, 0x66D, 0x66E], - top_inset_adjust: 0, }, }; -/// Chrome 157.0.8103.38's font functions and colour ids, found by name in its public symbols and +/// Chrome 157.0.8103.38's colour ids, found by name in its public symbols and /// in its colour id tables. Unverified. const DEV_CHROME_157_38: DevMode = DevMode { colours: &[ @@ -1238,15 +1110,6 @@ const DEV_CHROME_157_38: DevMode = DevMode { (1062, DEV_ICON_HOT), (1063, DEV_ICON), ], - font_new: 0x0323_9230, // ??0Font@gfx@@QEAA@AEBV?$basic_string@DU?$char_traits@D@__Cr@std@@V?$allocator@D@23@@__Cr@std@@H@Z - font_new_prologue: &[ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x89, 0xD1, 0x44, 0x89, 0xC2, - ], - font_list_new: 0x0323_8F10, // ??0FontList@gfx@@QEAA@AEBVFont@1@@Z - font_list_new_prologue: &[ - 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xD3, 0x48, 0x89, 0xCE, - ], - ..DEV_CHROME_156 }; /// Google Chrome 157.0.8103.38, ported by name from the 156.0.8078.80 row with this build's own public @@ -1275,8 +1138,6 @@ pub static CHROME_157_38: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x68, ], - view_parent: 0x198, - view_children: 0x1A0, operator_new: 0x5E75E90, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xE8, 0x82, 0xB1, 0x05, 0xFE, @@ -1331,42 +1192,12 @@ pub static CHROME_157_38: Build = Build { get_widget_slot: Some(11), dev: DEV_CHROME_157_38, get_color: 0x0454_F050, - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x20, - 0x89, 0xD7, - ], content_window_for_hwnd: 0x00E1_3BC0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x0321_2390, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "", toolbar_layout: 0x0119_5EC0, // ?Layout@ToolbarView@@UEAAXVPassKey@@@Z }, vertical: VerticalTabs { - supported: true, - slot: 0x100A_DE20, // .weak.??_7VerticalTabStripStateControllerImpl@tabs@@6BVerticalTabStripStateController@1@@.default.?R - should_display: 0x0372_F780, // ?ShouldDisplayVerticalTabs@VerticalTabStripStateControllerImpl@tabs@@UEBA_NXZ - browser_view_for_browser: 0x0031_9000, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x0373_9690, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x0A87_5880, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x0204_3D80, // ??0VerticalTabStripStateController@tabs@@IEAA@AEAVBrowserWindowInterface@@@Z - destructor: 0x02AA_EA60, // ??_EVerticalTabStripStateControllerImpl@tabs@@UEAAPEAXI@Z - destructor_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x89, 0xD7, 0x48, 0x89, 0xCE, 0xE8, - ], - browser_offset: 0x1B8, - mode_offset: 0x1E8, - width_offset: 0x1CC, - browser_view_view_vtable: 0x1016_E590, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat - region_preferred_size: 0x0A8D_3A70, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z - region_preferred_size_slot: 0x1017_6640, // .weak.??_7VerticalTabStripRegionView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$Cd - invalidate_layout: 0x0458_7C70, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - region_minimum_size: 0x0A8D_39E0, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x48, 0x89, 0xD6, 0x48, 0x89, 0xCF, 0x48, 0xC7, - 0x02, 0x00, 0x00, 0x00, 0x00, - ], should_draw_tab_strip: 0x054D_6710, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], window_feature: ABSENT, @@ -1527,7 +1358,6 @@ pub static CHROME_157_38: Build = Build { flex_layout: 0x0545_7A60, // views::FlexLayout::CalculateProposedLayout flex_layout_host: 0x38, location_bar_vtable: 0x1015_9FB0, // LocationBarView primary vtable - view_size: 0x1D0, signatures: &[ ( 0x0A89_FA40, @@ -1653,7 +1483,6 @@ pub static CHROME_157_38: Build = Build { browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], caption_ink_ids: &[0x673, 0x674, 0x675], - top_inset_adjust: 0, }, }; @@ -1724,6 +1553,5 @@ pub static CHROME_150: Build = Build { browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], caption_ink_ids: &[1593, 1594, 1595], - top_inset_adjust: 0, }, }; diff --git a/rivet/runtime/windows/src/builds/edge.rs b/rivet/runtime/windows/src/builds/edge.rs index 29ab5c9..3e1f479 100644 --- a/rivet/runtime/windows/src/builds/edge.rs +++ b/rivet/runtime/windows/src/builds/edge.rs @@ -1,10 +1,8 @@ //! Rows for Microsoft Edge builds. -use super::chrome::DEV_CHROME_156; use super::*; -/// Edge 156.0.4314.50. Its colour ids sit 88 to 101 above Chrome's. The font functions are read from -/// its public symbols and checked against the module file. +/// Edge 156.0.4314.50. Its colour ids sit 88 to 101 above Chrome's. const DEV_EDGE_156: DevMode = DevMode { colours: &[ (316, DEV_GROUND), @@ -36,15 +34,6 @@ const DEV_EDGE_156: DevMode = DevMode { (2351, DEV_ICON), (3009, 0), ], - font_new: 0x0267_058C, // ??0Font@gfx@@QEAA@AEBV?$basic_string@DU?$char_traits@D@__Cr@std@@V?$allocator@D@23@@__Cr@std@@H@Z - font_new_prologue: &[ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x89, 0xD1, 0x44, 0x89, 0xC2, - ], - font_list_new: 0x02B0_FDCE, // ??0FontList@gfx@@QEAA@AEBVFont@1@@Z - font_list_new_prologue: &[ - 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xD3, 0x48, 0x89, 0xCE, - ], - ..DEV_CHROME_156 }; pub static EDGE: Build = Build { @@ -60,42 +49,12 @@ pub static EDGE: Build = Build { get_widget_slot: Some(10), dev: DEV_EDGE_156, get_color: 0x0100309E, - get_color_bytes: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x28, 0x89, - 0xD7, 0x48, - ], content_window_for_hwnd: 0x026A4DC6, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z widget_for_window: 0x028C8D78, // ?GetWidgetForNativeView@Widget@views@@SAPEAV12@PEAVWindow@aura@@@Z skip: "updateicon anchor visible", // the address field, icons and bubble anchors are not recorded for Edge yet toolbar_layout: ABSENT, }, vertical: VerticalTabs { - supported: false, // not checked on Edge yet - slot: 0x1172CF10, // VerticalTabStripStateControllerImpl vtable, ShouldDisplayVerticalTabs slot - should_display: 0x0A3D40D0, // ?loaded@TopSitesImpl@history@@UEBA_NXZ - browser_view_for_browser: 0x010CDA9A, // ?GetBrowserViewForBrowser@BrowserView@@SAPEAV1@PEBVBrowserWindowInterface@@@Z - hwnd_for_view: 0x01078A59, // ?HWNDForView@views@@YAPEAUHWND__@@PEBVView@1@@Z - notify_mode_changed: 0x0A3D3176, // ?NotifyModeChanged@VerticalTabStripStateController@tabs@@IEAAXXZ - update_collapse_action: 0x0, // none in Edge - destructor: 0x0A3D4830, // ??_GVerticalTabStripStateControllerImpl@tabs@@UEAAPEAXI@Z - destructor_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x89, 0xD7, 0x48, 0x89, 0xCE, 0xE8, - ], - browser_offset: 0x1B8, // Chrome value, not checked on Edge - mode_offset: 0x1E8, // Chrome value, not checked on Edge - width_offset: 0x1CC, // Chrome value, not checked on Edge - browser_view_view_vtable: 0x11937B18, // BrowserView View vtable - region_preferred_size: 0x0CAE1ED0, // ?CalculatePreferredSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@ - region_preferred_size_slot: 0x1181EC28, // VerticalTabStripRegionView vtable, CalculatePreferredSize slot 86 - invalidate_layout: 0x00FFA880, // ?InvalidateLayout@View@views@@QEAAX_N@Z - invalidate_layout_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x38, - ], - region_minimum_size: 0x0CAE1E50, // ?GetMinimumSize@VerticalTabStripRegionView@@UEBA?AVSize@gfx@@XZ - region_minimum_prologue: &[ - 0x56, 0x57, 0x48, 0x83, 0xec, 0x28, 0x48, 0x89, 0xd6, 0x48, 0x89, 0xcf, 0x48, 0xc7, - 0x02, 0, 0, 0, 0, - ], // Chrome value, not checked on Edge should_draw_tab_strip: 0x0100A550, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ should_draw_tab_strip_prologue: &[ 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x8B, 0x89, 0x18, 0x06, 0x00, @@ -254,7 +213,6 @@ pub static EDGE: Build = Build { flex_layout: 0x0100A8E0, // ?CalculateProposedLayout@FlexLayout@views flex_layout_host: 0x38, location_bar_vtable: 0x11874078, // ??_7LocationBarView@@6BLayerDelegate@ui@@@ - view_size: 0x1D0, // Chrome value, not checked on Edge signatures: &[ ( 0x0A40C036, @@ -385,6 +343,5 @@ pub static EDGE: Build = Build { browser_window_in_view: 0x1F8, // BrowserWindow subobject distance from the BrowserView, read by GetBrowserView caption_paint_prologue: &[0xE9, 0x01, 0x00, 0x00, 0x00, 0xCC, 0x41, 0x57], caption_ink_ids: &[0x66C, 0x66D, 0x66E], // Chrome value, not checked on Edge - top_inset_adjust: 0, }, }; diff --git a/rivet/runtime/windows/src/builds/mod.rs b/rivet/runtime/windows/src/builds/mod.rs index c012b9d..86a3755 100644 --- a/rivet/runtime/windows/src/builds/mod.rs +++ b/rivet/runtime/windows/src/builds/mod.rs @@ -102,7 +102,6 @@ pub struct Omnibox { pub controller_published_result: usize, pub input_new: usize, pub input_drop: usize, - pub input_size: usize, pub input_prevent_inline: usize, pub input_omit_asynchronous: usize, pub start: usize, @@ -139,11 +138,6 @@ pub struct AppWindow { pub detach_prologue: &'static [u8], pub insert: Option, pub insert_prologue: &'static [u8], - /// A `views::View` keeps its parent at this offset and its children vector right after it. Kept - /// for runtimes that read them from the row; this runtime takes both from the layout's bounds - /// offset, by the member order of `views::View`. - pub view_parent: usize, - pub view_children: usize, /// `operator new(size)`, `views::WebView::WebView(this, context)` and the object's size. pub operator_new: usize, pub operator_new_prologue: &'static [u8], @@ -195,7 +189,6 @@ pub struct Toolbar { /// `ui::ColorProvider::GetColor(this, id)`. A provider makes a colour the first time it is asked /// for it, so one that was never asked for is asked for before its value is replaced. pub get_color: usize, - pub get_color_bytes: &'static [u8], /// `views::DesktopWindowTreeHostWin::GetContentWindowForHWND` and /// `views::Widget::GetWidgetForNativeWindow`. pub content_window_for_hwnd: usize, @@ -209,45 +202,10 @@ pub struct Toolbar { } row_struct! { -/// Values for `vertical_tabs.rs`. +/// Values for `tab_strip.rs`, which takes the tab strip out of a Rivet window's layout. A row keeps +/// them under `vertical`, the name of the experiment they first served. pub struct VerticalTabs { - /// Whether this build has been checked for this feature. When it is false the feature is left alone. - pub supported: bool, - /// The vtable slot of `VerticalTabStripStateControllerImpl::ShouldDisplayVerticalTabs`. - pub slot: usize, - pub should_display: usize, - /// `BrowserView::GetBrowserViewForBrowser`. - pub browser_view_for_browser: usize, - /// `views::HWNDForView`. - pub hwnd_for_view: usize, - /// `VerticalTabStripStateController::NotifyModeChanged`. - pub notify_mode_changed: usize, - /// `VerticalTabStripStateControllerImpl::UpdateCollapseActionItem`. - pub update_collapse_action: usize, - pub destructor: usize, - pub destructor_prologue: &'static [u8], - /// Where the controller keeps its browser, its mode and its strip width. - pub browser_offset: usize, - pub mode_offset: usize, - pub width_offset: usize, - /// `BrowserView`'s vtable for its `views::View` base. The browser view is reached through another - /// base, so the view base is found by this vtable before asking for the window. - pub browser_view_view_vtable: usize, - /// `VerticalTabStripRegionView::CalculatePreferredSize`, and the vtable slot that holds it. - pub region_preferred_size: usize, - pub region_preferred_size_slot: usize, - /// `views::View::InvalidateLayout`, with the first bytes that identify it in this build. - pub invalidate_layout: usize, - pub invalidate_layout_prologue: &'static [u8], - /// `VerticalTabStripRegionView::GetMinimumSize`. The browser lays the page out after at least - /// this width, 126 DIPs while the strip is expanded, however little the strip asks for, so a - /// hidden appbar would leave that much of the frame bare. The class is final, so callers reach - /// the function directly and its vtable slot is never used. Rivet detours the function instead: - /// its first instructions are copied to a trampoline and replaced by a jump to Rivet's version. - pub region_minimum_size: usize, - /// `push rsi; push rdi; sub rsp, 0x28; mov rsi, rdx; mov rdi, rcx; mov qword ptr [rdx], 0`. - pub region_minimum_prologue: &'static [u8], - /// `BrowserView::ShouldDrawTabStrip` and its first bytes, for the tab strip experiment. + /// `BrowserView::ShouldDrawTabStrip` and its first bytes. pub should_draw_tab_strip: usize, pub should_draw_tab_strip_prologue: &'static [u8], /// `Browser::SupportsWindowFeature(browser, feature, check)`, for builds whose layout has the tab @@ -427,8 +385,6 @@ pub struct Split { pub flex_layout_host: usize, /// The primary vtable of `LocationBarView`, which tells the top row's container among all hosts. pub location_bar_vtable: usize, - /// Where a view keeps its size, two ints. - pub view_size: usize, /// The first instructions of the functions the split and group calls need. pub signatures: &'static [(usize, &'static [u8])], } @@ -614,11 +570,6 @@ pub struct Layout { /// Colour ids `WindowsCaptionButton::PaintButtonContents` reads for its glyphs: active, inactive /// and on the toolbar. Ids shift between milestones. pub caption_ink_ids: &'static [i32], - /// Added to the top inset a Rivet window reports, in DIPs. Chrome's client area begins at the top - /// of the frame in its one-row layout, whatever the inset says, so Rivet's extra title height only - /// reaches the caption buttons. Brave's client area begins at the inset, which would leave the - /// page lower than the row, so its extra cancels out. - pub top_inset_adjust: i32, } } @@ -630,22 +581,10 @@ pub struct DevMode { /// A build with no colours has no developer bar. The bar's browser commands are Chromium's /// public command ids, which come from `browsers::chromium::commands`, not from the row. pub colours: &'static [(i32, u32)], - /// `gfx::Font::Font(this, &name, size)` and `gfx::FontList::FontList(this, &font)`, which build - /// the monospace font of the address. A build without them keeps the address in its own font. - pub font_new: usize, - pub font_new_prologue: &'static [u8], - pub font_list_new: usize, - pub font_list_new_prologue: &'static [u8], } } -const UNCHECKED_DEV: DevMode = DevMode { - colours: &[], - font_new: ABSENT, - font_new_prologue: &[0], - font_list_new: ABSENT, - font_list_new_prologue: &[0], -}; +const UNCHECKED_DEV: DevMode = DevMode { colours: &[] }; const DEV_GROUND: u32 = 0xFF2A_2C31; const DEV_RULE: u32 = 0xFF17_181B; @@ -663,29 +602,9 @@ const UNCHECKED_TOOLBAR: Toolbar = Toolbar { skip: "", toolbar_layout: ABSENT, get_color: ABSENT, - get_color_bytes: &[0], }; const UNCHECKED_VERTICALTABS: VerticalTabs = VerticalTabs { - supported: false, - slot: 0, - should_display: ABSENT, - browser_view_for_browser: ABSENT, - hwnd_for_view: ABSENT, - notify_mode_changed: ABSENT, - update_collapse_action: ABSENT, - destructor: ABSENT, - destructor_prologue: &[0], - browser_offset: 0, - mode_offset: 0, - width_offset: 0, - browser_view_view_vtable: ABSENT, - region_preferred_size: ABSENT, - region_preferred_size_slot: 0, - invalidate_layout: ABSENT, - invalidate_layout_prologue: &[0], - region_minimum_size: ABSENT, - region_minimum_prologue: &[0], should_draw_tab_strip: ABSENT, should_draw_tab_strip_prologue: &[0], window_feature: ABSENT, @@ -783,7 +702,6 @@ const UNCHECKED_SPLIT: Split = Split { flex_layout: ABSENT, flex_layout_host: 0, location_bar_vtable: ABSENT, - view_size: 0, signatures: &[], }; @@ -883,21 +801,18 @@ const UNCHECKED_LAYOUT: Layout = Layout { browser_window_in_view: 0, caption_paint_prologue: &[0], caption_ink_ids: &[], - top_inset_adjust: 0, }; /// Why a row leaves a feature off though it may record some of its addresses. A feature whose /// addresses are all missing needs no reason of its own. pub fn unchecked_reason(build: &Build, feature: &str) -> &'static str { match (build.browser, feature) { - ("Microsoft Edge", "vertical tabs") => "vertical tabs are not checked on Edge yet", ("Microsoft Edge", "sidebar") => "the only panel Edge registers has no page behind it, so the Sidebar has nothing to show on Edge", ("Samsung Internet", "split view") => { "split view is not checked on Samsung Internet: its split call stops inside the tab collection" } (_, "split view") => "split view is not checked on this browser build", (_, "sidebar") => "the Sidebar is not checked on this browser build", - (_, "vertical tabs") => "vertical tabs are not checked on this browser build", (_, "opening addresses") => "opening addresses is not checked on this browser build", _ => "tab control is not checked on this browser build", } diff --git a/rivet/runtime/windows/src/builds/omnibox_rows.rs b/rivet/runtime/windows/src/builds/omnibox_rows.rs index 9a3b97f..dd11d6a 100644 --- a/rivet/runtime/windows/src/builds/omnibox_rows.rs +++ b/rivet/runtime/windows/src/builds/omnibox_rows.rs @@ -27,7 +27,6 @@ pub(super) const OMNIBOX_CHROME_156_74: Omnibox = Omnibox { controller_published_result: 0x648, input_new: 0x0247_2D40, input_drop: 0x0178_86F0, - input_size: 0x478, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B3, start: 0x01A2_4C30, @@ -160,7 +159,6 @@ pub(super) const OMNIBOX_CHROME_156_80: Omnibox = Omnibox { controller_published_result: 0x648, input_new: 0x0253_84E0, input_drop: 0x0188_B820, - input_size: 0x478, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B3, start: 0x01B2_F220, @@ -295,7 +293,6 @@ pub(super) const OMNIBOX_CHROME_157_38: Omnibox = Omnibox { controller_published_result: 0x648, input_new: 0x0237_2180, input_drop: 0x01B8_D270, - input_size: 0x478, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B3, start: 0x019E_15E0, @@ -429,7 +426,6 @@ pub(super) const OMNIBOX_BRAVE_63: Omnibox = Omnibox { controller_published_result: 0x648, input_new: 0x0261_CB50, input_drop: 0x017A_9AB0, - input_size: 0x478, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B3, start: 0x01B3_3100, @@ -563,7 +559,6 @@ pub(super) const OMNIBOX_BRAVE_157_55: Omnibox = Omnibox { controller_published_result: 0x648, input_new: 0x023A_F2B0, input_drop: 0x01A6_EDD0, - input_size: 0x478, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B3, start: 0x0198_4840, @@ -697,7 +692,6 @@ pub(super) const OMNIBOX_WHALE_57: Omnibox = Omnibox { controller_published_result: 0x628, input_new: 0x0DEE_EE30, input_drop: 0x0DEF_1130, - input_size: 0x470, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B4, start: 0x0DED_A570, @@ -835,7 +829,6 @@ pub(super) const OMNIBOX_SAMSUNG_29: Omnibox = Omnibox { controller_published_result: 0x470, input_new: 0x01D7_9300, input_drop: 0x0128_30A0, - input_size: 0x2C8, input_prevent_inline: 0x1B0, input_omit_asynchronous: 0x1B8, start: 0x02B1_3A30, diff --git a/rivet/runtime/windows/src/builds/samsung.rs b/rivet/runtime/windows/src/builds/samsung.rs index befdbd5..3cc48d4 100644 --- a/rivet/runtime/windows/src/builds/samsung.rs +++ b/rivet/runtime/windows/src/builds/samsung.rs @@ -33,8 +33,6 @@ pub static SAMSUNG: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x68, ], - view_parent: 0x190, - view_children: 0x198, operator_new: 0x55841C8, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xEB, 0x0F, 0x48, 0x8B, 0xCB, diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index cf73bee..645d849 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -163,7 +163,7 @@ fn nfr3_every_row_names_one_module_and_version() { fn nfr3_chrome_150_checks_only_the_frame_hooks() { assert_eq!(CHROME_150.version, [150, 0, 7871, 187]); assert_eq!(CHROME_150.toolbar.skip, "toolbar"); - assert!(!CHROME_150.vertical.supported && !CHROME_150.tabs.supported); + assert!(!CHROME_150.tabs.supported); assert_ne!(CHROME_150.layout.frame_vtable, CHROME.layout.frame_vtable); // Colour ids and View member offsets moved between milestones 150 and 156. assert_eq!(CHROME_150.layout.caption_ink_ids, &[1593, 1594, 1595]); @@ -191,8 +191,7 @@ fn nfr3_whale_maps_only_the_frame_hooks() { assert_eq!(WHALE.module, "whale.dll"); assert_eq!(WHALE.version, [5, 39, 412, 57]); assert!( - !WHALE.vertical.supported - && WHALE.tabs.supported + WHALE.tabs.supported && !WHALE.tabs.groups && !WHALE.split.supported ); @@ -269,8 +268,7 @@ fn nfr3_brave_156_frame_hooks_match_the_installed_build() { fn check_brave_frame_hooks(brave: &Build) { assert!( - brave.vertical.supported - && brave.tabs.supported + brave.tabs.supported && !brave.tabs.groups && brave.navigation.supported ); @@ -505,7 +503,7 @@ fn fr10_edge_side_panel_row_matches_the_installed_build() { } #[test] -fn fr12_brave_156_toolbar_and_vertical_tab_hooks_match_the_installed_build() { +fn fr12_brave_156_toolbar_hooks_match_the_installed_build() { check_brave_toolbar_hooks(&BRAVE); check_brave_toolbar_hooks(&BRAVE_63); } @@ -516,8 +514,7 @@ fn nfr3_samsung_frame_and_tab_hooks_match_the_installed_build() { assert_eq!(SAMSUNG.version, [30, 0, 4, 29]); assert_eq!(SAMSUNG.toolbar.skip, "toolbar"); assert!( - !SAMSUNG.vertical.supported - && SAMSUNG.tabs.supported + SAMSUNG.tabs.supported && !SAMSUNG.tabs.groups && !SAMSUNG.split.supported ); @@ -645,44 +642,6 @@ fn fr11_developer_commands_are_those_of_the_devtools_keys() { } } -#[test] -fn fr11_edge_156_developer_font_functions_match_the_installed_build() { - let path = r"C:\Program Files (x86)\Microsoft\Edge\Application\156.0.4314.50\msedge.dll"; - let Ok(file) = std::fs::read(path) else { - return; - }; - let dev = &EDGE.toolbar.dev; - for (name, rva, prologue) in [ - ("font", dev.font_new, dev.font_new_prologue), - ("font list", dev.font_list_new, dev.font_list_new_prologue), - ] { - assert_eq!( - file_bytes(&file, rva, prologue.len()).as_deref(), - Some(prologue), - "{name} prologue does not match msedge.dll" - ); - } -} - -#[test] -fn fr11_chrome_156_74_developer_font_functions_match_the_installed_build() { - let path = r"C:\Program Files\Google\Chrome\Application\156.0.8078.74\chrome.dll"; - let Ok(file) = std::fs::read(path) else { - return; - }; - let dev = &CHROME_156_74.toolbar.dev; - for (name, rva, prologue) in [ - ("font", dev.font_new, dev.font_new_prologue), - ("font list", dev.font_list_new, dev.font_list_new_prologue), - ] { - assert_eq!( - file_bytes(&file, rva, prologue.len()).as_deref(), - Some(prologue), - "{name}" - ); - } -} - #[test] fn fr9_samsung_split_records_only_the_calls_it_verified() { let row = &SAMSUNG.split; @@ -1106,11 +1065,8 @@ fn nfr3_chromium_157_rows_record_the_members_that_moved() { ); let row = build.app_window.as_ref().unwrap(); assert_eq!(row.web_view_size, 0x520, "{name}"); - assert_eq!( - (row.view_parent, row.view_children), - (0x198, 0x1A0), - "{name}" - ); + let fields = crate::features::app_window::view_fields(build); + assert_eq!(fields, Some((0x198, 0x1A0)), "{name}"); } // Chromium 157 dropped one side panel entry. Brave keeps its own four. assert_eq!( @@ -1220,37 +1176,6 @@ fn check_brave_toolbar_hooks(brave: &Build) { CHROME.layout.caption_ink_ids[2] + 17 ] ); - let Some(file) = brave_dll(brave) else { - return; - }; - for (name, rva, prologue) in [ - ( - "colour", - brave.toolbar.get_color, - brave.toolbar.get_color_bytes, - ), - ( - "view invalidation", - brave.vertical.invalidate_layout, - brave.vertical.invalidate_layout_prologue, - ), - ( - "region minimum size", - brave.vertical.region_minimum_size, - brave.vertical.region_minimum_prologue, - ), - ( - "controller destructor", - brave.vertical.destructor, - brave.vertical.destructor_prologue, - ), - ] { - assert_eq!( - file_bytes(&file, rva, prologue.len()).as_deref(), - Some(prologue), - "{name} prologue does not match Brave's chrome.dll" - ); - } } #[test] @@ -1259,11 +1184,7 @@ fn nfr3_chrome_156_74_hooks_match_the_installed_build() { let Ok(file) = std::fs::read(path) else { return; }; - let (layout, vertical, split) = ( - &CHROME_156_74.layout, - &CHROME_156_74.vertical, - &CHROME_156_74.split, - ); + let (layout, split) = (&CHROME_156_74.layout, &CHROME_156_74.split); for (name, rva, prologue) in [ ("frame paint", layout.on_paint, layout.on_paint_prologue), ( @@ -1276,11 +1197,6 @@ fn nfr3_chrome_156_74_hooks_match_the_installed_build() { layout.get_color_provider, layout.get_color_provider_prologue, ), - ( - "destructor", - vertical.destructor, - vertical.destructor_prologue, - ), ( "rounded corners", split.set_rounded_corners, @@ -1304,7 +1220,6 @@ fn nfr3_recorded_addresses_lie_inside_a_plausible_image() { build.tabs.tab_count, build.split.add_to_new_split, build.side_panel.show, - build.vertical.slot, build.navigation.open_url, ] { // A feature the row leaves unchecked records no address. @@ -1611,17 +1526,22 @@ fn nfr6_a_table_row_carries_the_page_tools_and_bubble_anchor_of_its_prior_row() } /// The parent and children of a view follow from its bounds by the member order of `views::View`. -/// Every row that recorded them by hand agrees, so the rule replaces them. +/// Every row that once recorded them by hand held these values, so the rule replaced them. #[test] fn nfr6_a_views_parent_and_children_are_not_row_values() { let mut seen = 0; for build in compiled() { - let Some(row) = build.app_window.as_ref() else { + if build.app_window.is_none() { continue; + } + let expected = match build.layout.view_bounds_offset { + 0x1C8 => (0x198, 0x1A0), + 0x1C0 => (0x190, 0x198), + other => panic!("{} keeps a view's bounds at {other:#x}", build.browser), }; assert_eq!( crate::features::app_window::view_fields(build), - Some((row.view_parent, row.view_children)), + Some(expected), "{} {:?}", build.browser, build.version @@ -1629,6 +1549,10 @@ fn nfr6_a_views_parent_and_children_are_not_row_values() { seen += 1; } assert!(seen >= 5, "{seen}"); + // The row holds neither value. + let row = crate::row_data::RowValue::to_row(&CHROME_157_38); + assert!(row["app_window"].get("view_parent").is_none()); + assert!(row["app_window"].get("view_children").is_none()); // A row the bounds offset of which moves gives the parent and children of that build. let mut moved = crate::row_data::RowValue::to_row(&CHROME_157_38); moved["layout"]["view_bounds_offset"] = serde_json::json!("0x1d0"); diff --git a/rivet/runtime/windows/src/builds/whale.rs b/rivet/runtime/windows/src/builds/whale.rs index 45931c8..b405e4c 100644 --- a/rivet/runtime/windows/src/builds/whale.rs +++ b/rivet/runtime/windows/src/builds/whale.rs @@ -41,8 +41,6 @@ pub static WHALE: Build = Build { 0x41, 0x57, 0x41, 0x56, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x50, 0x44, 0x89, ], - view_parent: 0x190, - view_children: 0x198, operator_new: 0x3E4AB40, operator_new_prologue: &[ 0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x8B, 0xD9, 0xEB, 0x0F, 0x48, 0x8B, 0xCB, @@ -289,7 +287,6 @@ pub static WHALE: Build = Build { flex_layout: crate::builds::ABSENT, flex_layout_host: 0, location_bar_vtable: crate::builds::ABSENT, - view_size: 0, signatures: &[ ( 0x0819_0FB0, diff --git a/rivet/runtime/windows/src/feature.rs b/rivet/runtime/windows/src/feature.rs index c513455..95ecec3 100644 --- a/rivet/runtime/windows/src/feature.rs +++ b/rivet/runtime/windows/src/feature.rs @@ -30,8 +30,6 @@ pub(crate) enum Feature { Split, /// The layout of the pages of a split view. SplitLayout, - /// The browser's own vertical tab strip, reported to the appbar. - VerticalTabs, /// The browser's tab strip is left out of the layout. TabStrip, } @@ -47,7 +45,6 @@ impl Feature { Feature::TopInset => "top_inset", Feature::Split => "split", Feature::SplitLayout => "split_layout", - Feature::VerticalTabs => "vertical_tabs", Feature::TabStrip => "tab_strip", } } @@ -278,7 +275,7 @@ mod tests { type Pick = (&'static str, fn(&Build) -> Needs, fn(&Build) -> bool); - fn picks() -> [Pick; 5] { + fn picks() -> [Pick; 4] { [ ("navigation", crate::features::navigation::needs, |b| { b.navigation.supported @@ -290,11 +287,6 @@ mod tests { ("sidebar", crate::features::side_panel::needs, |b| { b.side_panel.supported }), - ( - "vertical tabs", - crate::features::vertical_tabs::needs, - |b| b.vertical.supported, - ), ] } @@ -325,12 +317,6 @@ mod tests { #[test] fn nfr3_a_feature_switched_off_with_addresses_names_its_reason() { let edge = &builds::EDGE; - let vertical = crate::features::vertical_tabs::needs(edge); - assert!(vertical.targets.iter().all(Target::recorded)); - assert_eq!( - vertical.unavailable().as_deref(), - Some("vertical tabs are not checked on Edge yet") - ); let sidebar = crate::features::side_panel::needs(edge); assert!(sidebar.targets.iter().any(Target::recorded)); assert!(sidebar @@ -368,7 +354,7 @@ mod tests { type NeedsOf = fn(&Build) -> Needs; - fn all_needs() -> [(Feature, NeedsOf); 7] { + fn all_needs() -> [(Feature, NeedsOf); 6] { use crate::features::{frame_layout, split, tab_strip}; [ (Feature::FrameLayout, frame_layout::needs_layout), @@ -377,7 +363,6 @@ mod tests { (Feature::CaptionLayout, frame_layout::needs_caption_layout), (Feature::Split, split::needs), (Feature::TabStrip, tab_strip::needs), - (Feature::VerticalTabs, crate::features::vertical_tabs::needs), ] } @@ -399,17 +384,13 @@ mod tests { "caption_layout", "split", ]; - assert_eq!( - names(&builds::CHROME), - [&chromium[..], &["vertical_tabs"]].concat() - ); + assert_eq!(names(&builds::CHROME), chromium); assert_eq!( names(&builds::BRAVE), [ "frame_layout", "caption_paint", - "caption_layout", - "vertical_tabs" + "caption_layout" ] ); assert_eq!(names(&builds::EDGE), chromium); diff --git a/rivet/runtime/windows/src/features/address_bar.rs b/rivet/runtime/windows/src/features/address_bar.rs index 857437d..303b598 100644 --- a/rivet/runtime/windows/src/features/address_bar.rs +++ b/rivet/runtime/windows/src/features/address_bar.rs @@ -566,8 +566,7 @@ unsafe fn ensure_layout(window: HWND) { if !DONE.with(|done| done.borrow_mut().insert(window as isize)) { return; } - let installed = crate::hooks::page_area::install() - .and_then(|()| crate::features::omnibox::install_app_layout()); + let installed = crate::hooks::page_area::install_for_app_window(); let reason = installed.as_ref().err().cloned().unwrap_or_default(); match offset_for(installed, crate::features::second_view::available()) { Offset::Layout => { diff --git a/rivet/runtime/windows/src/features/mod.rs b/rivet/runtime/windows/src/features/mod.rs index 9f01396..7488480 100644 --- a/rivet/runtime/windows/src/features/mod.rs +++ b/rivet/runtime/windows/src/features/mod.rs @@ -31,6 +31,5 @@ pub(crate) mod tab_list; pub(crate) mod tab_strip; pub(crate) mod tabs; pub(crate) mod tick_gate; -pub(crate) mod vertical_tabs; pub(crate) mod widgets; pub(crate) mod window_corners; diff --git a/rivet/runtime/windows/src/features/omnibox.rs b/rivet/runtime/windows/src/features/omnibox.rs index 002bed8..316ee36 100644 --- a/rivet/runtime/windows/src/features/omnibox.rs +++ b/rivet/runtime/windows/src/features/omnibox.rs @@ -410,8 +410,8 @@ pub(crate) fn match_count(begin: usize, second: usize, match_size: usize) -> Opt (count <= 64).then_some(count) } -/// Patches the app window's layout so the page area steps run for it too. An app window is laid out -/// by `BrowserViewAppLayoutImpl`, not the tabbed layout the Sidebar patches. +/// Patches the app window's layout so the page area steps run for it. An app window is laid out +/// by `BrowserViewAppLayoutImpl`, not the tabbed layout, so this patch needs nothing of that one. pub(crate) unsafe fn install_app_layout() -> Result<(), String> { let (f, _) = loaded().ok_or("this build has no recorded app window layout")?; crate::browsers::chromium::layout::install_app_layout( diff --git a/rivet/runtime/windows/src/features/vertical_tabs.rs b/rivet/runtime/windows/src/features/vertical_tabs.rs deleted file mode 100644 index 4c6580b..0000000 --- a/rivet/runtime/windows/src/features/vertical_tabs.rs +++ /dev/null @@ -1,522 +0,0 @@ -//! Experiment: Chromium's own vertical-tab layout for Rivet windows only. -//! -//! In vertical-tab mode Chromium puts its toolbar and the caption buttons in one top row and the -//! tab strip on the left. Rivet wants exactly that frame, but the mode is a profile setting and -//! would change every window of the profile. Each browser window owns a controller that keeps the -//! mode. Rivet switches the controllers of Rivet windows the way a setting change would, without -//! writing the setting. -//! -//! Chromium asks a controller for its mode during every layout, including layouts that run while -//! the window is still being built. Resolving the window there is not safe, so the controller is -//! only reported, and each Rivet window checks later, on its own thread, whether the controller is -//! its own. -//! -//! The addresses below belong to Google Chrome 156.0.8078.48 only. They move to the supported-build -//! table once the experiment holds. - -use std::collections::HashMap; -use std::ffi::c_void; -use std::sync::atomic::Ordering; -use std::sync::{Mutex, MutexGuard, OnceLock}; - -use crate::builds::Build; -use crate::chromium::image; -use crate::feature::{available_here, Needs}; -use crate::targets::Target; -use crate::trace::trace; -use windows_sys::Win32::Foundation::HWND; -use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_PROTECTION_FLAGS, PAGE_READWRITE}; - -/// The values of the loaded browser build. -fn bv() -> &'static crate::builds::VerticalTabs { - &crate::builds::get().vertical -} - -/// What the browser's vertical tab strip needs from the browser. -pub(crate) fn needs(build: &Build) -> Needs { - let row = &build.vertical; - Needs::checked( - row.supported, - crate::builds::unchecked_reason(build, "vertical tabs"), - vec![ - Target::new("vertical tab slot", row.slot, &[]), - Target::new( - "vertical tab controller destructor", - row.destructor, - row.destructor_prologue, - ), - Target::new( - "GetBrowserViewForBrowser", - row.browser_view_for_browser, - &[], - ), - Target::new("HWNDForView", row.hwnd_for_view, &[]), - Target::new("NotifyModeChanged", row.notify_mode_changed, &[]), - ], - ) -} - -// The vtable slot of the controller's scalar deleting destructor sits two words before -// `ShouldDisplayVerticalTabs`. - -type ShouldDisplay = unsafe extern "system" fn(*const c_void) -> bool; -type ViewForBrowser = unsafe extern "system" fn(*const c_void) -> *const c_void; -type HwndForView = unsafe extern "system" fn(*const c_void) -> HWND; -type ControllerCall = unsafe extern "system" fn(*mut c_void); -type Destructor = unsafe extern "system" fn(*mut c_void, u32) -> *mut c_void; - -/// Reports a controller that still shows horizontal tabs, so Rivet windows can check it later. -pub type Report = fn(usize); - -struct Hook { - original: ShouldDisplay, - view_for_browser: ViewForBrowser, - hwnd_for_view: HwndForView, - notify_mode_changed: ControllerCall, - update_collapse_action: Option, - report: Report, -} - -static HOOK: OnceLock> = OnceLock::new(); -/// Controllers already reported and not yet destroyed, so each is reported once and a controller -/// that was freed is never dereferenced. Chromium destroys a controller on the UI thread, where -/// the destructor hook removes it, and every use of a controller address checks this list first. -static REPORTED: Mutex> = Mutex::new(Vec::new()); -static DESTRUCTOR_ORIGINAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -/// The switched controller of each Rivet window. -static SWITCHED: Mutex>> = Mutex::new(None); -fn locked(mutex: &'static Mutex) -> MutexGuard<'static, T> { - mutex.lock().unwrap_or_else(|error| error.into_inner()) -} - -/// Records a controller. Returns true the first time it is seen. -fn note_report(controller: usize) -> bool { - let mut reported = locked(&REPORTED); - let fresh = !reported.contains(&controller); - if fresh { - reported.push(controller); - } - fresh -} - -/// Whether the controller has been reported and not destroyed since. -fn is_live(controller: usize) -> bool { - locked(&REPORTED).contains(&controller) -} - -/// Forgets a controller that is being destroyed, so nothing keeps its address. -fn note_destroyed(controller: usize) { - locked(&REPORTED).retain(|known| *known != controller); - if let Some(map) = locked(&SWITCHED).as_mut() { - map.retain(|_, switched| *switched != controller); - } -} - -unsafe extern "system" fn controller_destroyed(controller: *mut c_void, flags: u32) -> *mut c_void { - note_destroyed(controller as usize); - let original: Destructor = std::mem::transmute(DESTRUCTOR_ORIGINAL.load(Ordering::Acquire)); - original(controller, flags) -} - -unsafe extern "system" fn should_display(controller: *const c_void) -> bool { - let Some(Ok(hook)) = HOOK.get() else { - unreachable!("the vtable is only patched after the hook is stored"); - }; - if *controller.cast::().add(bv().mode_offset) == 0 && note_report(controller as usize) { - trace(&format!("reported controller={controller:?}")); - (hook.report)(controller as usize); - } - (hook.original)(controller) -} - -/// The window a controller belongs to. Only safe once the window is built. -unsafe fn controller_window(hook: &Hook, controller: *const c_void) -> Option { - let browser = *(controller.cast::().add(bv().browser_offset) as *const *const c_void); - if browser.is_null() { - return None; - } - let view = (hook.view_for_browser)(browser); - if view.is_null() { - return None; - } - let base = image::recorded()?.base; - let words = view as *const usize; - let index = - (0..0x100).find(|index| *words.add(*index) == base + bv().browser_view_view_vtable)?; - trace(&format!("view base at +{:#x}", index * 8)); - let window = (hook.hwnd_for_view)(words.add(index).cast()); - (!window.is_null()).then_some(window) -} - -/// Switches a reported controller into vertical tabs if it belongs to `window`, the way a setting -/// change does: store the mode, tell the window to rebuild, refresh the collapse action. Runs on -/// the browser UI thread, outside layout. -pub unsafe fn offer(window: HWND, controller: usize) { - let Some(Ok(hook)) = HOOK.get() else { return }; - // The address may have been posted before the controller was destroyed. - if !is_live(controller) { - return; - } - let pointer = controller as *mut c_void; - let owner = controller_window(hook, pointer); - trace(&format!( - "offer window={window:?} controller={pointer:?} owner={owner:?}" - )); - if owner != Some(window) { - return; - } - let mode = pointer.cast::().add(bv().mode_offset); - if *mode != 0 { - return; - } - locked(&SWITCHED) - .get_or_insert_with(HashMap::new) - .insert(window as isize, controller); - *mode = 1; - // Keep Chromium's vertical-tab mode for its toolbar composition. The frame layout hook - // accounts for the strip when it moves the page to the appbar edge. - (hook.notify_mode_changed)(pointer); - if let Some(update) = hook.update_collapse_action { - update(pointer); - } -} - -/// The width Rivet gives the vertical tab strip of each window, in DIPs. Chromium keeps the strip -/// in its layout even though a Rivet window hides it, so the strip is made exactly as wide as the -/// appbar that covers it, or nothing while the appbar is hidden. Nothing is written to the -/// browser's own state or preferences. -static STRIP_WIDTHS: Mutex> = Mutex::new(Vec::new()); - -pub fn set_strip_override(window: HWND, width: i32) { - let mut widths = locked(&STRIP_WIDTHS); - match widths.iter_mut().find(|entry| entry.0 == window as isize) { - Some(entry) => entry.1 = width, - None => widths.push((window as isize, width)), - } -} - -fn strip_override(window: HWND) -> Option { - locked(&STRIP_WIDTHS) - .iter() - .find(|entry| entry.0 == window as isize) - .map(|entry| entry.1) -} - -/// The width the strip takes in the layout of `window`, or `None` while it shows horizontal tabs. -pub fn layout_width(window: HWND) -> Option { - let controller = *locked(&SWITCHED).as_ref()?.get(&(window as isize))?; - Some( - strip_override(window) - .unwrap_or_else(|| unsafe { *((controller + bv().width_offset) as *const i32) }), - ) -} - -/// Forgets a window that is going away, so its controller is never read again. -pub fn forget(window: HWND) { - locked(&STRIP_WIDTHS).retain(|entry| entry.0 != window as isize); - locked(®IONS).retain(|entry| entry.0 != window as isize); - let removed = locked(&SWITCHED) - .as_mut() - .and_then(|map| map.remove(&(window as isize))); - if let Some(controller) = removed { - locked(&REPORTED).retain(|known| *known != controller); - } -} - -pub unsafe fn install(report: Report) -> Result<(), String> { - HOOK.get_or_init(|| patch(report)) - .as_ref() - .map(|_| ()) - .map_err(Clone::clone) -} - -unsafe fn patch(report: Report) -> Result { - if !available_here(needs) { - return Err("this browser build has no recorded vertical-tab controller".into()); - } - let image = image::recorded().ok_or("this browser build has no recorded vertical tabs")?; - let base = image.base; - if !image.points_to(bv().slot, bv().should_display) { - return Err("this browser build has no recorded vertical-tab controller".into()); - } - if !image.points_to(bv().slot - 16, bv().destructor) - || !image.has(bv().destructor, bv().destructor_prologue) - { - return Err("this browser build has no recorded vertical-tab controller destructor".into()); - } - // Zero means the build has no separate collapse action to refresh. - for function in [ - bv().browser_view_for_browser, - bv().hwnd_for_view, - bv().notify_mode_changed, - bv().update_collapse_action, - ] { - if function != 0 && image.at(function, 1).is_none() { - return Err("a recorded vertical-tab function is outside the browser image".into()); - } - } - let slot = image - .at(bv().slot, 8) - .ok_or("recorded slot outside the image")? as *mut usize; - let destructor = image - .at(bv().slot - 16, 8) - .ok_or("recorded slot outside the image")? as *mut usize; - let hook = Hook { - original: std::mem::transmute::(slot.read()), - view_for_browser: std::mem::transmute::( - base + bv().browser_view_for_browser, - ), - hwnd_for_view: std::mem::transmute::(base + bv().hwnd_for_view), - notify_mode_changed: std::mem::transmute::( - base + bv().notify_mode_changed, - ), - update_collapse_action: (bv().update_collapse_action != 0).then(|| { - std::mem::transmute::(base + bv().update_collapse_action) - }), - report, - }; - // Both slots are replaced or neither is: a controller must never be reported without the - // hook that forgets it. - DESTRUCTOR_ORIGINAL.store(destructor.read(), Ordering::Release); - let mut previous: PAGE_PROTECTION_FLAGS = 0; - if VirtualProtect(destructor.cast(), 8, PAGE_READWRITE, &mut previous) == 0 { - return Err("could not unprotect the vertical-tab controller vtable".into()); - } - destructor.write(controller_destroyed as *const () as usize); - VirtualProtect(destructor.cast(), 8, previous, &mut previous); - if VirtualProtect(slot.cast(), 8, PAGE_READWRITE, &mut previous) == 0 { - destructor.write(DESTRUCTOR_ORIGINAL.load(Ordering::Acquire)); - return Err("could not unprotect the vertical-tab controller vtable".into()); - } - slot.write(should_display as *const () as usize); - VirtualProtect(slot.cast(), 8, previous, &mut previous); - match patch_region_size(&image) { - Ok(()) => trace("region size hook installed"), - Err(error) => trace(&format!("region size hook unavailable: {error}")), - } - trace("installed"); - Ok(hook) -} -static REGION_ORIGINAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -static REGIONS: Mutex> = Mutex::new(Vec::new()); - -fn remember_region(window: HWND, view: *mut c_void) { - let mut regions = locked(®IONS); - match regions.iter_mut().find(|entry| entry.0 == window as isize) { - Some(entry) => entry.1 = view as usize, - None => regions.push((window as isize, view as usize)), - } -} - -/// Makes the strip's view ask for its width again. Chromium caches the size it asked for, so a -/// width Rivet changed is only seen after this. -pub unsafe fn invalidate_strip(window: HWND) { - let Some(view) = locked(®IONS) - .iter() - .find(|entry| entry.0 == window as isize) - .map(|entry| entry.1) - else { - return; - }; - let Some(image) = image::recorded() else { - return; - }; - if !image.has(bv().invalidate_layout, bv().invalidate_layout_prologue) { - return; - } - let invalidate: unsafe extern "system" fn(*mut c_void, i32) = - std::mem::transmute(image.base + bv().invalidate_layout); - invalidate(view as *mut c_void, 0); -} - -/// A Rivet window's strip asks for the width Rivet gives it instead of Chromium's own. -unsafe extern "system" fn region_preferred_size( - view: *mut c_void, - out: *mut [i32; 2], - bounds: usize, -) -> *mut c_void { - type Original = unsafe extern "system" fn(*mut c_void, *mut [i32; 2], usize) -> *mut c_void; - let original: Original = std::mem::transmute(REGION_ORIGINAL.load(Ordering::Acquire)); - let result = original(view, out, bounds); - if !locked(&STRIP_WIDTHS).is_empty() { - if let Some(Ok(hook)) = HOOK.get() { - let window = (hook.hwnd_for_view)(view); - if let Some(width) = strip_override(window) { - (*out)[0] = width; - remember_region(window, view); - } - } - } - result -} - -static REGION_MINIMUM_ORIGINAL: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -/// A Rivet window's strip is never required to be wider than the width Rivet gives it. -unsafe extern "system" fn region_minimum_size( - view: *mut c_void, - out: *mut [i32; 2], -) -> *mut c_void { - type Original = unsafe extern "system" fn(*mut c_void, *mut [i32; 2]) -> *mut c_void; - let original: Original = std::mem::transmute(REGION_MINIMUM_ORIGINAL.load(Ordering::Acquire)); - let result = original(view, out); - if !locked(&STRIP_WIDTHS).is_empty() { - if let Some(Ok(hook)) = HOOK.get() { - if let Some(width) = strip_override((hook.hwnd_for_view)(view)) { - (*out)[0] = (*out)[0].min(width); - } - } - } - result -} - -/// `jmp qword ptr [rip + 0]` followed by the absolute target. -pub(crate) fn absolute_jump(target: usize) -> [u8; 14] { - let mut code = [0u8; 14]; - code[..6].copy_from_slice(&[0xff, 0x25, 0, 0, 0, 0]); - code[6..].copy_from_slice(&target.to_le_bytes()); - code -} - -unsafe fn patch_region_minimum(image: &image::Image) -> Result<(), String> { - use windows_sys::Win32::System::Memory::{ - VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, - }; - let length = bv().region_minimum_prologue.len(); - if !image.has(bv().region_minimum_size, bv().region_minimum_prologue) { - return Err("the region view's minimum size is not the recorded function".into()); - } - let function = image - .at(bv().region_minimum_size, length) - .ok_or("function outside the image")? as *mut u8; - let trampoline = VirtualAlloc( - std::ptr::null(), - 64, - MEM_COMMIT | MEM_RESERVE, - PAGE_EXECUTE_READWRITE, - ) as *mut u8; - if trampoline.is_null() { - return Err("could not allocate the minimum size trampoline".into()); - } - let resume = absolute_jump(function as usize + bv().region_minimum_prologue.len()); - std::ptr::copy_nonoverlapping( - bv().region_minimum_prologue.as_ptr(), - trampoline, - bv().region_minimum_prologue.len(), - ); - std::ptr::copy_nonoverlapping( - resume.as_ptr(), - trampoline.add(bv().region_minimum_prologue.len()), - resume.len(), - ); - REGION_MINIMUM_ORIGINAL.store(trampoline as usize, Ordering::Release); - let mut previous: PAGE_PROTECTION_FLAGS = 0; - if VirtualProtect(function.cast(), 19, PAGE_EXECUTE_READWRITE, &mut previous) == 0 { - return Err("could not unprotect the region view's minimum size".into()); - } - let jump = absolute_jump(region_minimum_size as *const () as usize); - std::ptr::copy_nonoverlapping(jump.as_ptr(), function, jump.len()); - // Pad the rest of the replaced instructions with nops. - std::ptr::write_bytes( - function.add(jump.len()), - 0x90, - bv().region_minimum_prologue.len() - jump.len(), - ); - VirtualProtect(function.cast(), 19, previous, &mut previous); - windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache( - windows_sys::Win32::System::Threading::GetCurrentProcess(), - function.cast(), - bv().region_minimum_prologue.len(), - ); - Ok(()) -} - -unsafe fn patch_region_size(image: &image::Image) -> Result<(), String> { - if !image.points_to(bv().region_preferred_size_slot, bv().region_preferred_size) { - return Err("the region view's size slot is not the recorded function".into()); - } - let slot = image - .at(bv().region_preferred_size_slot, 8) - .ok_or("slot outside the image")? as *mut usize; - REGION_ORIGINAL.store(slot.read(), Ordering::Release); - let mut previous: PAGE_PROTECTION_FLAGS = 0; - if VirtualProtect(slot.cast(), 8, PAGE_READWRITE, &mut previous) == 0 { - return Err("could not unprotect the region view's vtable".into()); - } - slot.write(region_preferred_size as *const () as usize); - VirtualProtect(slot.cast(), 8, previous, &mut previous); - patch_region_minimum(image)?; - Ok(()) -} - -/// Controllers reported so far, for a Rivet window that attaches after its own was reported. -pub fn reported() -> Vec { - locked(&REPORTED).clone() -} - -/// Experiment for the other direction: makes `BrowserView::ShouldDrawTabStrip` answer no for -/// every window of the process by overwriting its first instructions. Never for production. -pub unsafe fn hide_tab_strip_everywhere() -> Result<(), String> { - let image = image::recorded().ok_or("this browser build has no recorded tab strip")?; - if !image.has( - bv().should_draw_tab_strip, - bv().should_draw_tab_strip_prologue, - ) { - return Err("ShouldDrawTabStrip is not the recorded function".into()); - } - let code = (image.base + bv().should_draw_tab_strip) as *mut u8; - let mut previous: PAGE_PROTECTION_FLAGS = 0; - let execute_write = windows_sys::Win32::System::Memory::PAGE_EXECUTE_READWRITE; - if VirtualProtect(code.cast(), 3, execute_write, &mut previous) == 0 { - return Err("could not unprotect ShouldDrawTabStrip".into()); - } - // xor eax, eax; ret - std::ptr::copy_nonoverlapping([0x31u8, 0xC0, 0xC3].as_ptr(), code, 3); - VirtualProtect(code.cast(), 3, previous, &mut previous); - windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache( - windows_sys::Win32::System::Threading::GetCurrentProcess(), - code.cast(), - 3, - ); - trace("tab strip hidden everywhere"); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fr12_destroyed_controller_is_no_longer_live() { - let controller = 0x7000_1000; - assert!(note_report(controller)); - assert!(!note_report(controller)); - assert!(is_live(controller)); - note_destroyed(controller); - assert!(!is_live(controller)); - assert!(note_report(controller)); - note_destroyed(controller); - } - - #[test] - fn fr12_destroyed_controller_leaves_the_switched_windows() { - let controller = 0x7000_2000; - note_report(controller); - locked(&SWITCHED) - .get_or_insert_with(HashMap::new) - .insert(0x77, controller); - note_destroyed(controller); - assert!(locked(&SWITCHED).as_ref().unwrap().get(&0x77).is_none()); - assert_eq!(layout_width(0x77 as HWND), None); - } - - #[test] - fn fr12_minimum_size_detour_jumps_through_an_absolute_address() { - let jump = absolute_jump(0x1122_3344_5566_7788); - assert_eq!(&jump[..6], &[0xff, 0x25, 0, 0, 0, 0]); - assert_eq!(&jump[6..], &0x1122_3344_5566_7788usize.to_le_bytes()); - assert!(jump.len() <= bv().region_minimum_prologue.len()); - } -} diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index f031b6f..5a00b8f 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -1020,12 +1020,9 @@ fn slide_of(window: HWND) -> f32 { .unwrap_or(0.0) } -/// Where the page panel begins, in device-independent pixels. Chromium's own vertical tab strip -/// keeps its width at the left even while the appbar is hidden, because the browser offers no way -/// to take it out of the layout, so the page cannot begin before it ends. +/// Where the page panel begins, in device-independent pixels. fn page_x(window: HWND) -> i32 { - let leading = layout_of(window).leading(); - crate::features::vertical_tabs::layout_width(window).map_or(leading, |strip| leading.max(strip)) + layout_of(window).leading() } /// Converts client pixels to device-independent pixels of the appbar's own coordinates: below the @@ -1080,7 +1077,6 @@ pub(crate) fn appbar_settings(window: HWND) -> (i32, bool) { /// Sets the appbar width as a drag of its edge would. pub(crate) unsafe fn set_appbar_width(window: HWND, width: i32) { if edit_layout(window, |layout| layout.set_width(width)) { - sync_strip(window); update_appbar(window); relayout(window); } @@ -2017,17 +2013,9 @@ unsafe fn toggle_message() -> u32 { RegisterWindowMessageW(wide(TOGGLE_MESSAGE).as_ptr()) } -/// Makes Chromium's tab strip, which the appbar covers, as wide as the appbar: nothing while the -/// appbar is hidden. -unsafe fn sync_strip(window: HWND) { - let layout = layout_of(window); - crate::features::vertical_tabs::set_strip_override(window, layout.strip()); -} - /// Lays the browser out again, now that the appbar's width or mode changed, and redraws. unsafe fn relayout(window: HWND) { // The frame view lays out again on request, which also works for a maximized window. - crate::features::vertical_tabs::invalidate_strip(window); if frame_layout::relayout(window) { if is_waiting(window) { crate::trace::trace("attach: asked the frame view to lay out again"); @@ -2144,7 +2132,6 @@ unsafe fn toggle_appbar(window: HWND) { let before = frame_layout::panel_bounds(window).map(|panel| panel.x); edit_layout(window, |layout| layout.toggle()); crate::trace::trace(&format!("appbar: hidden {}", layout_of(window).collapsed)); - sync_strip(window); SLIDE.with(|slides| slides.borrow_mut().remove(&(window as isize))); KillTimer(window, PEEK_TIMER); relayout(window); @@ -2404,7 +2391,6 @@ unsafe fn apply_drag(window: HWND) { let wanted = AppbarLayout::width_at((x as f32 / factor).round() as i32); if edit_layout(window, |layout| layout.set_width(wanted)) { crate::trace::trace(&format!("appbar: width {}", layout_of(window).side)); - sync_strip(window); // The appbar takes its new width before the browser lays the page out, so what the // browser exposes is only ever ground or appbar, never the appbar's old surface over a // page that has already moved. @@ -2472,17 +2458,6 @@ unsafe fn group_probe_message() -> u32 { RegisterWindowMessageW(wide("RivetGroupProbe").as_ptr()) } -unsafe fn vertical_tabs_message() -> u32 { - RegisterWindowMessageW(wide("RivetVerticalTabs").as_ptr()) -} - -fn report_vertical_tabs(controller: usize) { - let windows: Vec = APPBARS.with(|appbars| appbars.borrow().keys().copied().collect()); - for window in windows { - unsafe { PostMessageW(window as HWND, vertical_tabs_message(), controller, 0) }; - } -} - /// The windows of this process that show the Rivet frame. Call it on the browser UI thread. pub(crate) fn rivet_windows() -> Vec { APPBARS.with(|appbars| { @@ -2826,8 +2801,6 @@ unsafe fn call_browser(window: HWND, message: u32, wparam: WPARAM, lparam: LPARA /// What the attach sequence carries from one step to the next. struct Attach { window: HWND, - /// Whether the browser's own vertical tab strip was reported to the appbar. - vertical_tabs: bool, } fn caption_row_height(window: HWND) -> Option { @@ -2934,15 +2907,8 @@ fn attach_steps() -> Vec> { if let Some(path) = trace_file("rivet-nav.log") { crate::trace::set_trace(path); } - let hide = trace_file("rivet-hide-tab-strip.log"); - if let Some(path) = hide { - crate::trace::set_trace(path); - if let Err(error) = crate::features::vertical_tabs::hide_tab_strip_everywhere() { - crate::trace::trace(&format!("hide failed: {error}")); - } - } - // The trace switch only switches the trace on. The toolbar and the - // vertical-tab frame are what the top row needs, so they never depend on it. + // The trace switch only switches the trace on. What the top row needs never + // depends on it. if crate::trace::tracing() { crate::trace::trace_crashes(); } @@ -2979,21 +2945,6 @@ fn attach_steps() -> Vec> { false, None, ), - feature( - Feature::VerticalTabs, - crate::features::vertical_tabs::needs, - |attach| unsafe { - let installed = crate::features::vertical_tabs::install(report_vertical_tabs); - if let Err(error) = &installed { - crate::trace::trace(&format!("unavailable: {error}")); - } - attach.vertical_tabs = installed.is_ok(); - installed - }, - OnFailure::Continue, - false, - None, - ), Step::Setup(|_| { crate::features::app_window::install_features(); true @@ -3015,11 +2966,6 @@ fn attach_steps() -> Vec> { 500, None, ); - if attach.vertical_tabs { - for controller in crate::features::vertical_tabs::reported() { - PostMessageW(window, vertical_tabs_message(), controller, 0); - } - } if let Err(error) = taskbar::apply(window as isize, runtime_directory().as_deref()) { log(&format!( "rivet: could not set the taskbar identity: {error}" @@ -3070,10 +3016,7 @@ unsafe fn create_appbar(window: HWND) { } // Without the layout hook the browser would draw underneath the appbar, so an unknown // browser build keeps working without Rivet instead. - let mut attach = Attach { - window, - vertical_tabs: false, - }; + let mut attach = Attach { window }; crate::feature::run(&attach_steps(), &mut attach, log); } @@ -3090,7 +3033,6 @@ unsafe fn compose_appbar(window: HWND) -> bool { APPBARS.with(|appbars| appbars.borrow_mut().insert(window as isize, appbar)); install_keyboard_hook(); load_persisted(window); - sync_strip(window); APPBAR_STATE.with(|states| { states .borrow_mut() @@ -3629,12 +3571,8 @@ fn reserved_width(window: HWND, bounds: frame_layout::Rect) -> Option { update_appbar(window); } } - // The scale is recorded above for both tab layouts. The strip is only subtracted here. let leading = layout_of(window).leading(); LAID_LEADING.with(|all| all.borrow_mut().insert(window as isize, leading)); - if let Some(strip) = crate::features::vertical_tabs::layout_width(window) { - return Some(crate::reserved_for_strip(leading, strip)); - } Some(leading) } } @@ -4275,7 +4213,6 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> { end_drag(window); if edit_layout(window, |layout| layout.set_width(APPBAR_WIDTH)) { - sync_strip(window); relayout(window); } } @@ -4370,7 +4307,6 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> crate::features::link_preview::forget(window); crate::features::page_links::forget(window); APPBAR_STATE.with(|states| states.borrow_mut().remove(&(window as isize))); - crate::features::vertical_tabs::forget(window); crate::features::tab_strip::forget(window); frame_layout::forget_view(window); crate::features::widgets::forget(window); @@ -4758,10 +4694,6 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> update_appbar(window); 0 } - _ if message == vertical_tabs_message() => { - crate::features::vertical_tabs::offer(window, wparam); - 0 - } _ if message == attach_message() => { // A test run's windows stay off every monitor and inactive from here on, the browser's // new windows and bubbles among them. diff --git a/rivet/runtime/windows/src/hooks/page_area.rs b/rivet/runtime/windows/src/hooks/page_area.rs index d34479c..fa03af8 100644 --- a/rivet/runtime/windows/src/hooks/page_area.rs +++ b/rivet/runtime/windows/src/hooks/page_area.rs @@ -223,13 +223,64 @@ pub(crate) unsafe fn run( /// Whether the row records the browser's layout. That alone decides the patch: the page area /// serves the address bar, the split and the Sidebar, so a build whose Sidebar is off still moves -/// its page with the browser's own layout. +/// its page with the browser's own layout. A row that does without the layout holds no address +/// for it, or zero. pub(crate) fn layout_recorded(layout_vtable: usize, proposed: usize) -> bool { - layout_vtable != crate::builds::ABSENT && proposed != crate::builds::ABSENT + let recorded = |address: usize| address != crate::builds::ABSENT && address != 0; + recorded(layout_vtable) && recorded(proposed) } -/// Patches the layout once per process. Without the recorded layout nothing here runs. +/// Whether the patched layouts are enough for a caller, from what each patch answered. `tabbed` +/// is the patch of the layout the row's Sidebar part records, and `app` makes the patch of an app +/// window's own layout class. +/// +/// Where the build has an app layout class, a Rivet window is laid out by it alone, so the bar of +/// an app window needs only that patch and the tabbed one may be missing. A caller that asks for +/// any window takes the tabbed patch as before, and the app patch where the row has no tabbed +/// layout. An old-layout build lays out every window with the one class its row records, so +/// nothing changes there: the tabbed patch is needed, and an app window needs both. +pub(crate) fn relied_on( + app_window: bool, + old_layout: bool, + tabbed: Result<(), String>, + app: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + match (app_window, old_layout) { + (true, true) => tabbed.and_then(|()| app()), + (true, false) => app(), + (false, true) => tabbed, + (false, false) => tabbed.or_else(|error| app().map_err(|_| error)), + } +} + +fn old_layout() -> bool { + row().old_layout == Some(true) +} + +/// Whether a layout of this process is patched, so the page area steps run after it. +fn patched() -> bool { + original() != 0 || crate::browsers::chromium::layout::app_layout_patched() +} + +/// Patches the layout of the page area once per process, for a caller that asks for any window: +/// the layout the row records, or else the app window's own. pub(crate) unsafe fn install() -> Result<(), String> { + relied_on(false, old_layout(), install_tabbed(), || { + crate::features::omnibox::install_app_layout() + }) +} + +/// Patches the layout that lays out an app window, once per process. The tabbed layout is patched +/// too where the row records it, and only an old-layout build needs it. +pub(crate) unsafe fn install_for_app_window() -> Result<(), String> { + relied_on(true, old_layout(), install_tabbed(), || { + crate::features::omnibox::install_app_layout() + }) +} + +/// Patches the layout the row records, once per process. Without the recorded layout nothing +/// here runs. +unsafe fn install_tabbed() -> Result<(), String> { const MISSING: &str = "this browser build has no recorded layout for the Sidebar"; if !layout_recorded(row().layout_vtable, row().proposed) { return Err(MISSING.into()); @@ -271,12 +322,12 @@ unsafe fn host_of(window: HWND) -> Option { } /// Lays the browser view out again, which runs the patched layout. A window the layout has not run -/// for yet is found through its frame view. Does nothing while the layout is not patched. +/// for yet is found through its frame view. Does nothing while no layout is patched. pub(crate) unsafe fn relayout(window: HWND) { let Some(image) = image::recorded() else { return; }; - if original() == 0 { + if !patched() { return; } let base = image.base; @@ -318,9 +369,8 @@ unsafe fn window_position(view: usize) -> [i32; 2] { } pub(crate) unsafe fn remember_own_area(window: HWND, view: usize) { - if crate::builds::get().side_panel.proposed != crate::builds::ABSENT - && area_top(window).is_some() - { + // A patched layout already recorded the area, whichever layout class ran. + if area_top(window).is_some() { return; } let [x, y] = window_position(view); @@ -364,6 +414,48 @@ mod tests { assert!(layout_recorded(0x0E18_0BE0, 0x013C_8310)); assert!(!layout_recorded(crate::builds::ABSENT, 0x013C_8310)); assert!(!layout_recorded(0x0E18_0BE0, crate::builds::ABSENT)); + // A row made for a build whose tabbed layout was not found holds zero or no address. + assert!(!layout_recorded(0, 0x013C_8310)); + assert!(!layout_recorded(0x0E18_0BE0, 0)); + } + + fn missing() -> Result<(), String> { + Err("no tabbed layout".into()) + } + + fn no_app() -> Result<(), String> { + Err("no app layout".into()) + } + + #[test] + fn fr12_an_app_window_is_laid_out_without_the_tabbed_layout() { + // The row has no tabbed layout, and the app window's own layout class is patched. + assert_eq!(relied_on(true, false, missing(), || Ok(())), Ok(())); + // The tabbed patch alone never lays out an app window. + assert_eq!(relied_on(true, false, Ok(()), no_app), Err("no app layout".into())); + // The Sidebar's callers go on with either patch, and name the tabbed one when both fail. + assert_eq!(relied_on(false, false, missing(), || Ok(())), Ok(())); + assert_eq!(relied_on(false, false, missing(), no_app), Err("no tabbed layout".into())); + } + + #[test] + fn fr12_a_recorded_tabbed_layout_does_not_ask_for_the_app_patch() { + fn never() -> Result<(), String> { + panic!("the app layout was patched") + } + assert_eq!(relied_on(false, false, Ok(()), never), Ok(())); + assert_eq!(relied_on(false, true, Ok(()), never), Ok(())); + } + + #[test] + fn fr10_an_old_layout_build_still_needs_the_layout_its_row_records() { + // One class lays out every window of such a build, so the app patch is no substitute. + let no_tabbed = Err("no tabbed layout".to_owned()); + assert_eq!(relied_on(true, true, missing(), || Ok(())), no_tabbed); + assert_eq!(relied_on(false, true, missing(), || Ok(())), no_tabbed); + // An app window of such a build needs both, as before. + assert_eq!(relied_on(true, true, Ok(()), no_app), Err("no app layout".into())); + assert_eq!(relied_on(true, true, Ok(()), || Ok(())), Ok(())); } #[test] diff --git a/rivet/runtime/windows/src/lib.rs b/rivet/runtime/windows/src/lib.rs index 13bea41..fe8604f 100644 --- a/rivet/runtime/windows/src/lib.rs +++ b/rivet/runtime/windows/src/lib.rs @@ -126,14 +126,6 @@ impl AppbarLayout { } } -/// What to reserve left of the client view so the page begins at `leading`, when the browser lays -/// its own strip out at the view's leading edge with `strip` DIPs. The reservation is never -/// negative, because the browser does not lay out a view that starts left of its window. -#[cfg(any(windows, test))] -fn reserved_for_strip(leading: i32, strip: i32) -> i32 { - (leading - strip).max(0) -} - /// The toggle button's rectangle as (x, y, width, height) in device-independent pixels of the /// window's client area, for a page panel that begins at `leading`. #[cfg(any(windows, test))] @@ -531,18 +523,6 @@ mod tests { assert_eq!(strip_hit(416, 100, 96, 0, 420), StripHit::Resizer); } - #[test] - fn fr3_page_edge_follows_the_appbar_for_every_width_and_when_hidden() { - // The strip is made as wide as the appbar, so the page begins at the appbar's edge. - for side in [200, 240, 268, 420] { - assert_eq!(reserved_for_strip(side, side) + side, side); - } - // Hidden: no strip, and the page begins after the gap. - assert_eq!(reserved_for_strip(FLOAT_INSET, 0), FLOAT_INSET); - // A strip wider than the wanted edge never pushes the view off the window. - assert_eq!(reserved_for_strip(200, 240), 0); - } - #[test] #[cfg(windows)] fn fr12_caption_buttons_answer_over_the_whole_row_height() { diff --git a/rivet/runtime/windows/src/row_data.rs b/rivet/runtime/windows/src/row_data.rs index c71f0b3..a1e3a63 100644 --- a/rivet/runtime/windows/src/row_data.rs +++ b/rivet/runtime/windows/src/row_data.rs @@ -391,7 +391,10 @@ mod tests { assert_eq!(read.to_row(), row, "{} {:?}", build.browser, build.version); assert_eq!(read.version, build.version); assert_eq!(read.toolbar.get_color, build.toolbar.get_color); - assert_eq!(read.toolbar.get_color_bytes, build.toolbar.get_color_bytes); + assert_eq!( + read.layout.layout_immediately_prologue, + build.layout.layout_immediately_prologue + ); assert_eq!(read.layout.caption_ink_ids, build.layout.caption_ink_ids); } } @@ -435,6 +438,11 @@ mod tests { let mut row = builds::CHROME.to_row(); row["toolbar"]["added_later"] = json!("0x1234"); assert!(builds::Build::from_row(&row).is_ok()); + // So does a row from an older generator, with values no runtime reads any more. + row["toolbar"]["get_color_bytes"] = json!("41574156"); + row["layout"]["top_inset_adjust"] = json!(-12); + row["split"]["view_size"] = json!("0x1d0"); + assert!(builds::Build::from_row(&row).is_ok()); } #[test] @@ -445,7 +453,7 @@ mod tests { Some("0x") ); assert!(row["layout"]["caption_ink_ids"][0].is_number()); - let bytes = row["toolbar"]["get_color_bytes"].as_str().unwrap(); + let bytes = row["layout"]["layout_immediately_prologue"].as_str().unwrap(); assert!(!bytes.starts_with("0x") && bytes.len() % 2 == 0); assert!(row["version"][0].is_number()); } From 3b902d9f5bb3b76e33c1bd2bfe0e66804625fa50 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:53:04 +0000 Subject: [PATCH 22/29] Publish: develop 4fcfd29 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_features.rs | 19 - rivet/platform/windows/src/row_port.rs | 11 +- rivet/platform/windows/src/row_recipe.rs | 11 +- rivet/runtime/windows/rows/table.json | 72 +--- rivet/runtime/windows/src/browser/mod.rs | 2 +- rivet/runtime/windows/src/builds/brave.rs | 18 - rivet/runtime/windows/src/builds/chrome.rs | 53 --- rivet/runtime/windows/src/builds/edge.rs | 16 - rivet/runtime/windows/src/builds/mod.rs | 50 --- rivet/runtime/windows/src/builds/samsung.rs | 23 -- rivet/runtime/windows/src/builds/tests.rs | 29 +- rivet/runtime/windows/src/builds/whale.rs | 11 - rivet/runtime/windows/src/feature.rs | 15 +- rivet/runtime/windows/src/features/mod.rs | 1 - .../runtime/windows/src/features/tab_strip.rs | 383 ------------------ rivet/runtime/windows/src/frame.rs | 17 - scripts/tests/layers.baseline | 3 - 17 files changed, 14 insertions(+), 720 deletions(-) delete mode 100644 rivet/runtime/windows/src/features/tab_strip.rs diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs index 099d09f..273db12 100644 --- a/rivet/platform/windows/src/row_features.rs +++ b/rivet/platform/windows/src/row_features.rs @@ -228,21 +228,6 @@ pub const UNUSED_WHEN: &[UnusedWhen] = &[ when: When::Recorded("tabs.tab_at"), why: "the build has its own GetWebContentsAt", }, - UnusedWhen { - paths: &[ - "vertical.window_feature_tab_strip", - "vertical.window_feature_callers", - "vertical.toolbar_in_view", - "vertical.toolbar_leading", - ], - when: When::Absent("vertical.window_feature"), - why: "the tab strip is left out through ShouldDrawTabStrip, not the window feature", - }, - UnusedWhen { - paths: &["vertical.should_draw_tab_strip"], - when: When::False("vertical.detour_strip"), - why: "the build does not leave its tab strip out by a detour", - }, UnusedWhen { paths: &[ "side_panel.layout_vtable", @@ -458,16 +443,12 @@ mod tests { fn nfr6_a_value_the_runtime_does_not_read_is_not_a_value_of_the_build() { let build = json!({ "tabs": {"tab_at": "0x326a00", "tab_collection": "0x30"}, - "vertical": {"window_feature": "0x7fff0000", "window_feature_callers": ["0x0", "0x0"]}, }); assert!(unused(&build, "tabs.tab_collection").is_some()); - assert!(unused(&build, "vertical.window_feature_callers[1]").is_some()); let build = json!({ "tabs": {"tab_at": "0x7fff0000"}, - "vertical": {"window_feature": "0x1234560"}, }); assert!(unused(&build, "tabs.tab_collection").is_none()); - assert!(unused(&build, "vertical.toolbar_in_view").is_none()); } #[test] diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index d0519ea..8e702c2 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -2776,7 +2776,7 @@ mod tests { #[test] fn nfr6_unplaced_functions_of_a_feature_that_is_off_do_not_block_the_row() { // Edge 157's row stopped on functions no method placed, most of which only features the - // runtime can do without hold. The prior build gave these two no fingerprint. + // runtime can do without hold. The prior build gave this one no fingerprint. let mut prior = verified_row(); prior["build"]["split"] = json!({ "supported": true, @@ -2784,17 +2784,12 @@ mod tests { "remove_split_prologue": "4883ec28488b0d10000000", "signatures": [["0x101400", "4883ec28"]], }); - prior["build"]["vertical"] = json!({ - "detour_strip": false, - "should_draw_tab_strip": "0x101500", - "should_draw_tab_strip_prologue": "4883ec28", - }); let bytes = module(&code_refs(&shifted_code(0x2000, 0x44))); let pe = PeFile::parse(&bytes).unwrap(); let prints = prints_of_prior(); let (row, report) = find_candidate(&prior, &prints, None, &no_classes(), "1.0.0.3", &pe); assert_eq!(report.review, Vec::::new()); - assert_eq!(report.unplaced.len(), 2, "{:?}", report.unplaced); + assert_eq!(report.unplaced.len(), 1, "{:?}", report.unplaced); assert!(report.unplaced[0].starts_with("0x101400: no fingerprint")); assert!(report.unplaced[0].ends_with("split.remove_split, split.signatures[0][0]")); let build = &row["build"]; @@ -2812,8 +2807,6 @@ mod tests { "{:?}", report.switched_off ); - // A function this build does not read is absent, and turns nothing off. - assert_eq!(build["vertical"]["should_draw_tab_strip"], "0x7fff0000"); assert_eq!(report.switched_off.len(), 1, "{:?}", report.switched_off); // The rest of the row is found. assert_eq!(build["toolbar"]["paint"], "0x103300"); diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index 642f712..6131917 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -355,10 +355,8 @@ pub fn derive_row(build: &mut Value, pe: &PeFile) -> Derived { } /// Values Rivet chooses rather than reads from a build, such as how long it waits before it opens -/// a new tab and how far its toolbar starts after the browser view's edge to leave room for -/// Rivet's toggle button. The row carries them for the runtime, so they are kept from the prior -/// row. -pub const SETTINGS: &[&str] = &["tabs.new_tab_delay_ms", "vertical.toolbar_leading"]; +/// a new tab. The row carries them for the runtime, so they are kept from the prior row. +pub const SETTINGS: &[&str] = &["tabs.new_tab_delay_ms"]; /// Lists of `[id, colour]` pairs: the id is a value of the build, and the colour is Rivet's choice. pub const ID_COLOUR_PAIRS: &[&str] = &["toolbar.dev.colours"]; @@ -639,11 +637,6 @@ mod tests { "toolbar.dev.colours[1][0]" ] ); - let chosen = json!({ - "vertical": {"toolbar_leading": 26, "toolbar_in_view": "0x60"}, - }); - assert_eq!(without_recipe(&chosen), vec!["vertical.toolbar_in_view"]); - assert_eq!(settings(&chosen), vec!["vertical.toolbar_leading"]); assert_eq!( settings(&build), vec![ diff --git a/rivet/runtime/windows/rows/table.json b/rivet/runtime/windows/rows/table.json index 2604b42..9fb549d 100644 --- a/rivet/runtime/windows/rows/table.json +++ b/rivet/runtime/windows/rows/table.json @@ -600,23 +600,7 @@ 0, 8078, 81 - ], - "vertical": { - "detour_strip": false, - "set_bounds_rect": "0x7fff0000", - "set_bounds_rect_prologue": "00", - "should_draw_tab_strip": "0x500f570", - "should_draw_tab_strip_prologue": "565753", - "toolbar_in_view": "0x0", - "toolbar_leading": 0, - "window_feature": "0x7fff0000", - "window_feature_callers": [ - "0x0", - "0x0" - ], - "window_feature_prologue": "00", - "window_feature_tab_strip": 0 - } + ] }, "frame": { "browser": "Google Chrome", @@ -1225,23 +1209,7 @@ 0, 8078, 82 - ], - "vertical": { - "detour_strip": false, - "set_bounds_rect": "0x7fff0000", - "set_bounds_rect_prologue": "00", - "should_draw_tab_strip": "0x500f430", - "should_draw_tab_strip_prologue": "565753", - "toolbar_in_view": "0x0", - "toolbar_leading": 0, - "window_feature": "0x7fff0000", - "window_feature_callers": [ - "0x0", - "0x0" - ], - "window_feature_prologue": "00", - "window_feature_tab_strip": 0 - } + ] }, "frame": { "browser": "Google Chrome", @@ -1850,23 +1818,7 @@ 0, 8103, 39 - ], - "vertical": { - "detour_strip": false, - "set_bounds_rect": "0x7fff0000", - "set_bounds_rect_prologue": "00", - "should_draw_tab_strip": "0x54d6590", - "should_draw_tab_strip_prologue": "565753", - "toolbar_in_view": "0x0", - "toolbar_leading": 0, - "window_feature": "0x7fff0000", - "window_feature_callers": [ - "0x0", - "0x0" - ], - "window_feature_prologue": "00", - "window_feature_tab_strip": 0 - } + ] }, "frame": { "browser": "Google Chrome", @@ -2456,23 +2408,7 @@ 0, 4314, 58 - ], - "vertical": { - "detour_strip": false, - "set_bounds_rect": "0x7fff0000", - "set_bounds_rect_prologue": "00", - "should_draw_tab_strip": "0x1038320", - "should_draw_tab_strip_prologue": "564883ec204889ce488b8918060000", - "toolbar_in_view": "0x0", - "toolbar_leading": 0, - "window_feature": "0x7fff0000", - "window_feature_callers": [ - "0x0", - "0x0" - ], - "window_feature_prologue": "00", - "window_feature_tab_strip": 0 - } + ] }, "frame": { "browser": "Microsoft Edge", diff --git a/rivet/runtime/windows/src/browser/mod.rs b/rivet/runtime/windows/src/browser/mod.rs index 54ce9de..355e20b 100644 --- a/rivet/runtime/windows/src/browser/mod.rs +++ b/rivet/runtime/windows/src/browser/mod.rs @@ -25,7 +25,7 @@ //! | G. Split view and the second page view | split, split_grid, second_view | build values, reflection for bounds | //! | H. Infobars per pane | pane_infobar | reflection | //! | I. Mini window out and back | mini_window | command id out, build values back | -//! | J. App window without a tab strip | app_window, tab_strip | build values | +//! | J. App window without a tab strip | app_window | build values | //! | K. Address suggestions | omnibox | build values | //! | L. Frame, caption and paint | frame_layout, look, widgets | build values, reflection to find views | //! | M. Side panel, bubbles, DevTools | side_panel, bubble_anchor, dev_tools | command ids, reflection, build values | diff --git a/rivet/runtime/windows/src/builds/brave.rs b/rivet/runtime/windows/src/builds/brave.rs index 8234005..2d61e51 100644 --- a/rivet/runtime/windows/src/builds/brave.rs +++ b/rivet/runtime/windows/src/builds/brave.rs @@ -55,12 +55,6 @@ pub static BRAVE: Build = Build { skip: "", toolbar_layout: ABSENT, }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x0661FA10, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x02EE93A0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z @@ -352,12 +346,6 @@ pub static BRAVE_63: Build = Build { skip: "", toolbar_layout: 0x01378F50, // ?Layout@ToolbarView, found statically and unverified }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x065EAD20, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x02F353F0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z @@ -719,12 +707,6 @@ pub static BRAVE_157_55: Build = Build { skip: "", toolbar_layout: 0x011E0460, // ?Layout@ToolbarView, found statically and unverified }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x06A93F30, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x00D6A480, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z diff --git a/rivet/runtime/windows/src/builds/chrome.rs b/rivet/runtime/windows/src/builds/chrome.rs index d3b6524..b73a9af 100644 --- a/rivet/runtime/windows/src/builds/chrome.rs +++ b/rivet/runtime/windows/src/builds/chrome.rs @@ -49,19 +49,6 @@ pub static CHROME: Build = Build { skip: "", toolbar_layout: ABSENT, }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x0528_6C00, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - window_feature: ABSENT, - window_feature_prologue: &[0], - window_feature_tab_strip: 0, - window_feature_callers: (0, 0), - set_bounds_rect: ABSENT, - set_bounds_rect_prologue: &[0], - toolbar_in_view: 0, - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x00D5_64A0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z @@ -419,19 +406,6 @@ pub static CHROME_156_74: Build = Build { skip: "", toolbar_layout: 0x011C_98D0, // ?Layout@ToolbarView@@UEAAXVPassKey@@@Z }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x0504_F960, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - window_feature: ABSENT, - window_feature_prologue: &[0], - window_feature_tab_strip: 0, - window_feature_callers: (0, 0), - set_bounds_rect: ABSENT, - set_bounds_rect_prologue: &[0], - toolbar_in_view: 0, - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x02F4_6B00, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z @@ -792,19 +766,6 @@ pub static CHROME_156_80: Build = Build { skip: "", toolbar_layout: 0x0130_94D0, // ?Layout@ToolbarView@@UEAAXVPassKey@@@Z }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x0500_F4B0, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - window_feature: ABSENT, - window_feature_prologue: &[0], - window_feature_tab_strip: 0, - window_feature_callers: (0, 0), - set_bounds_rect: ABSENT, - set_bounds_rect_prologue: &[0], - toolbar_in_view: 0, - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x02F9_C1F0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z @@ -1197,19 +1158,6 @@ pub static CHROME_157_38: Build = Build { skip: "", toolbar_layout: 0x0119_5EC0, // ?Layout@ToolbarView@@UEAAXVPassKey@@@Z }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x054D_6710, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[0x56, 0x57, 0x53], - window_feature: ABSENT, - window_feature_prologue: &[0], - window_feature_tab_strip: 0, - window_feature_callers: (0, 0), - set_bounds_rect: ABSENT, - set_bounds_rect_prologue: &[0], - toolbar_in_view: 0, - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, content_window_for_hwnd: 0x00E1_3BC0, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z @@ -1501,7 +1449,6 @@ pub static CHROME_150: Build = Build { skip: "toolbar", ..UNCHECKED_TOOLBAR }, - vertical: UNCHECKED_VERTICALTABS, navigation: UNCHECKED_NAVIGATION, tabs: UNCHECKED_TABS, split: UNCHECKED_SPLIT, diff --git a/rivet/runtime/windows/src/builds/edge.rs b/rivet/runtime/windows/src/builds/edge.rs index 3e1f479..f53e1cf 100644 --- a/rivet/runtime/windows/src/builds/edge.rs +++ b/rivet/runtime/windows/src/builds/edge.rs @@ -54,22 +54,6 @@ pub static EDGE: Build = Build { skip: "updateicon anchor visible", // the address field, icons and bubble anchors are not recorded for Edge yet toolbar_layout: ABSENT, }, - vertical: VerticalTabs { - should_draw_tab_strip: 0x0100A550, // ?ShouldDrawTabStrip@BrowserView@@QEBA_NXZ - should_draw_tab_strip_prologue: &[ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x8B, 0x89, 0x18, 0x06, 0x00, - 0x00, - ], - window_feature: ABSENT, - window_feature_prologue: &[0], - window_feature_tab_strip: 0, - window_feature_callers: (0, 0), - set_bounds_rect: ABSENT, - set_bounds_rect_prologue: &[0], - toolbar_in_view: 0, - detour_strip: false, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, // opening an address in a tab checked on Edge 156.0.4314.50 content_window_for_hwnd: 0x026A4DC6, // ?GetContentWindowForHWND@DesktopWindowTreeHostWin@views@@SAPEAVWindow@aura@@PEAUHWND__@@@Z diff --git a/rivet/runtime/windows/src/builds/mod.rs b/rivet/runtime/windows/src/builds/mod.rs index 86a3755..1f0cbdf 100644 --- a/rivet/runtime/windows/src/builds/mod.rs +++ b/rivet/runtime/windows/src/builds/mod.rs @@ -38,7 +38,6 @@ pub struct Build { pub module: &'static str, pub version: [u16; 4], pub toolbar: Toolbar, - pub vertical: VerticalTabs, pub navigation: Navigation, pub tabs: Tabs, pub split: Split, @@ -201,41 +200,6 @@ pub struct Toolbar { } } -row_struct! { -/// Values for `tab_strip.rs`, which takes the tab strip out of a Rivet window's layout. A row keeps -/// them under `vertical`, the name of the experiment they first served. -pub struct VerticalTabs { - /// `BrowserView::ShouldDrawTabStrip` and its first bytes. - pub should_draw_tab_strip: usize, - pub should_draw_tab_strip_prologue: &'static [u8], - /// `Browser::SupportsWindowFeature(browser, feature, check)`, for builds whose layout has the tab - /// strip decision inlined so no function of its own answers it. Rivet detours it to answer no - /// for the tab strip feature of the browsers of Rivet windows. The prologue must be 12 or more - /// bytes, end on an instruction boundary and hold no relative operand. - pub window_feature: usize, - pub window_feature_prologue: &'static [u8], - /// The value of the tab strip feature. - pub window_feature_tab_strip: u32, - /// The code range whose questions Rivet answers, as start and end RVAs, or `(0, 0)` for every - /// caller. Other callers ask the same question for other reasons, and the frame view takes the - /// caption buttons away with the strip when it hears the answer. - pub window_feature_callers: (usize, usize), - /// `View::SetBoundsRect` and the offset of the toolbar view in the browser view. With the strip - /// gone the toolbar runs under the caption buttons, so Rivet detours the bounds function to stop - /// the toolbar of a Rivet window short of them. The prologue must be 12 or more bytes with no - /// relative operand. - pub set_bounds_rect: usize, - pub set_bounds_rect_prologue: &'static [u8], - pub toolbar_in_view: usize, - /// How far, in DIPs, the toolbar of a Rivet window starts to the right of the browser view's left - /// edge, so Rivet's toggle button has the room before the back button that Chrome's toolbar gives it. - pub toolbar_leading: i32, - /// Whether a Rivet window leaves that function out of its layout by a detour, with this build's - /// prologue copied to a trampoline. Only builds where this has been checked set it. - pub detour_strip: bool, -} -} - row_struct! { /// Values for `chrome_navigation.rs`. pub struct Navigation { @@ -604,20 +568,6 @@ const UNCHECKED_TOOLBAR: Toolbar = Toolbar { get_color: ABSENT, }; -const UNCHECKED_VERTICALTABS: VerticalTabs = VerticalTabs { - should_draw_tab_strip: ABSENT, - should_draw_tab_strip_prologue: &[0], - window_feature: ABSENT, - window_feature_prologue: &[0], - window_feature_tab_strip: 0, - window_feature_callers: (0, 0), - set_bounds_rect: ABSENT, - set_bounds_rect_prologue: &[0], - toolbar_in_view: 0, - toolbar_leading: 0, - detour_strip: false, -}; - const UNCHECKED_NAVIGATION: Navigation = Navigation { supported: false, content_window_for_hwnd: ABSENT, diff --git a/rivet/runtime/windows/src/builds/samsung.rs b/rivet/runtime/windows/src/builds/samsung.rs index 3cc48d4..1b8cf3b 100644 --- a/rivet/runtime/windows/src/builds/samsung.rs +++ b/rivet/runtime/windows/src/builds/samsung.rs @@ -80,29 +80,6 @@ pub static SAMSUNG: Build = Build { skip: "toolbar", ..UNCHECKED_TOOLBAR }, - vertical: VerticalTabs { - // The tabbed layout's function (0x13c8310) inlines `BrowserView::ShouldDrawTabStrip`, whose - // copies at 0x2b44ed0 and 0x2b44420 it never calls, and starts that test by asking this - // function for feature 2, the tab strip, at 0x13c8510. Its other callers, the frame's - // top inset among them, must keep the browser's answer or the caption buttons go with the - // strip. The prologue is 12 bytes and ends on an instruction boundary. - window_feature: 0x001F_BB10, - window_feature_prologue: &[ - 0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x44, 0x89, 0xC3, 0x89, 0xD6, - ], - window_feature_tab_strip: 2, - window_feature_callers: (0x013C_8310, 0x013C_A742), - set_bounds_rect: 0x047C_EA60, - set_bounds_rect_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - toolbar_in_view: 0x5B0, - // The toggle ends 36 DIPs in and the toolbar keeps 8 before its first button; the back button - // then sits 30 DIPs from the toggle's centre, as Chrome's does. - toolbar_leading: 32, - detour_strip: true, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, // opening the start page in a new tab checked on Samsung Internet 30.0.4.29 content_window_for_hwnd: 0x00B5_A010, diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index 645d849..1a03c23 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -196,16 +196,6 @@ fn nfr3_whale_maps_only_the_frame_hooks() { && !WHALE.split.supported ); assert!(WHALE.navigation.supported && WHALE.side_panel.supported); - assert!( - WHALE.vertical.detour_strip && WHALE.vertical.should_draw_tab_strip_prologue.len() >= 14 - ); - assert!( - all() - .iter() - .filter(|build| build.vertical.detour_strip) - .count() - == 2 - ); assert_eq!(WHALE.toolbar.skip, "toolbar"); // Hooks without a verified address are absent, so their checks fail. assert_eq!(WHALE.layout.corner_paint, ABSENT); @@ -272,7 +262,7 @@ fn check_brave_frame_hooks(brave: &Build) { && !brave.tabs.groups && brave.navigation.supported ); - assert!(!brave.split.supported && !brave.vertical.detour_strip); + assert!(!brave.split.supported); // The .62 row records no frame paint or top inset. The .63 row records Chromium's own. if brave.version == BRAVE.version { assert_eq!( @@ -532,23 +522,6 @@ fn nfr3_samsung_frame_and_tab_hooks_match_the_installed_build() { let Ok(file) = std::fs::read(path) else { return; }; - // The inlined tab strip test: `call` of the window feature function from the layout. - assert_eq!( - file_bytes(&file, 0x13c8510, 5).as_deref(), - Some(&[0xE8, 0xFB, 0x35, 0xE3, 0xFE][..]) - ); - let callers = SAMSUNG.vertical.window_feature_callers; - assert!(callers.0 <= 0x13c8510 && 0x13c8515 <= callers.1); - let bounds = SAMSUNG.vertical.set_bounds_rect_prologue; - assert_eq!( - file_bytes(&file, SAMSUNG.vertical.set_bounds_rect, bounds.len()).as_deref(), - Some(bounds) - ); - let bytes = SAMSUNG.vertical.window_feature_prologue; - assert_eq!( - file_bytes(&file, SAMSUNG.vertical.window_feature, bytes.len()).as_deref(), - Some(bytes) - ); for (rva, bytes) in SAMSUNG.tabs.signatures { assert_eq!( file_bytes(&file, *rva, bytes.len()).as_deref(), diff --git a/rivet/runtime/windows/src/builds/whale.rs b/rivet/runtime/windows/src/builds/whale.rs index b405e4c..5c9711a 100644 --- a/rivet/runtime/windows/src/builds/whale.rs +++ b/rivet/runtime/windows/src/builds/whale.rs @@ -89,17 +89,6 @@ pub static WHALE: Build = Build { skip: "toolbar", ..UNCHECKED_TOOLBAR }, - vertical: VerticalTabs { - // Chromium's `BrowserView::ShouldDrawTabStrip` in this build. The - // prologue ends on an instruction boundary and holds no relative operand. - should_draw_tab_strip: 0x0E6CBE60, - should_draw_tab_strip_prologue: &[ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x8B, 0x89, 0xC0, 0x05, 0x00, - 0x00, - ], - detour_strip: true, - ..UNCHECKED_VERTICALTABS - }, navigation: Navigation { supported: true, // opening an address in a tab checked on Whale 5.39.412.57 content_window_for_hwnd: 0x08F36620, diff --git a/rivet/runtime/windows/src/feature.rs b/rivet/runtime/windows/src/feature.rs index 95ecec3..902925e 100644 --- a/rivet/runtime/windows/src/feature.rs +++ b/rivet/runtime/windows/src/feature.rs @@ -30,8 +30,6 @@ pub(crate) enum Feature { Split, /// The layout of the pages of a split view. SplitLayout, - /// The browser's tab strip is left out of the layout. - TabStrip, } impl Feature { @@ -45,7 +43,6 @@ impl Feature { Feature::TopInset => "top_inset", Feature::Split => "split", Feature::SplitLayout => "split_layout", - Feature::TabStrip => "tab_strip", } } } @@ -354,15 +351,14 @@ mod tests { type NeedsOf = fn(&Build) -> Needs; - fn all_needs() -> [(Feature, NeedsOf); 6] { - use crate::features::{frame_layout, split, tab_strip}; + fn all_needs() -> [(Feature, NeedsOf); 5] { + use crate::features::{frame_layout, split}; [ (Feature::FrameLayout, frame_layout::needs_layout), (Feature::FrameColour, frame_layout::needs_colour), (Feature::CaptionPaint, frame_layout::needs_caption_paint), (Feature::CaptionLayout, frame_layout::needs_caption_layout), (Feature::Split, split::needs), - (Feature::TabStrip, tab_strip::needs), ] } @@ -403,11 +399,8 @@ mod tests { "caption_layout" ] ); - assert_eq!( - names(&builds::WHALE), - ["frame_layout", "frame_colour", "tab_strip"] - ); - assert_eq!(names(&builds::SAMSUNG), ["frame_layout", "tab_strip"]); + assert_eq!(names(&builds::WHALE), ["frame_layout", "frame_colour"]); + assert_eq!(names(&builds::SAMSUNG), ["frame_layout"]); } fn nothing(_: &Build) -> Needs { diff --git a/rivet/runtime/windows/src/features/mod.rs b/rivet/runtime/windows/src/features/mod.rs index 7488480..495dc87 100644 --- a/rivet/runtime/windows/src/features/mod.rs +++ b/rivet/runtime/windows/src/features/mod.rs @@ -28,7 +28,6 @@ pub(crate) mod sidebar_page; pub(crate) mod split; pub(crate) mod split_grid; pub(crate) mod tab_list; -pub(crate) mod tab_strip; pub(crate) mod tabs; pub(crate) mod tick_gate; pub(crate) mod widgets; diff --git a/rivet/runtime/windows/src/features/tab_strip.rs b/rivet/runtime/windows/src/features/tab_strip.rs deleted file mode 100644 index cd156af..0000000 --- a/rivet/runtime/windows/src/features/tab_strip.rs +++ /dev/null @@ -1,383 +0,0 @@ -//! Takes the horizontal tab strip out of a Rivet window's layout. -//! -//! The browser view decides in one function whether the window draws a tab strip. Rivet detours -//! that function: it answers no for the browser views of Rivet windows and runs the browser's own -//! code for every other window. The views are recorded when a window attaches, on the UI thread, -//! because the layout itself must not resolve a window while the window is being built. - -use std::ffi::c_void; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Mutex, MutexGuard, OnceLock}; - -use windows_sys::Win32::Foundation::HWND; - -use crate::builds::Build; -use crate::chromium::image; -use crate::feature::Needs; -use crate::targets::Target; - -type ShouldDraw = unsafe extern "system" fn(*const c_void) -> bool; - -static ORIGINAL: AtomicUsize = AtomicUsize::new(0); -static BOUNDS_ORIGINAL: AtomicUsize = AtomicUsize::new(0); -static FEATURE_ORIGINAL: AtomicUsize = AtomicUsize::new(0); -/// Each Rivet window and its browser, so a closed window's browser is forgotten by the window. -static BROWSERS: Mutex> = Mutex::new(Vec::new()); -static VIEWS: Mutex> = Mutex::new(Vec::new()); -static INSTALLED: OnceLock> = OnceLock::new(); - -fn locked() -> MutexGuard<'static, Vec> { - VIEWS.lock().unwrap_or_else(|error| error.into_inner()) -} - -/// Whether this build records the function and has room for a detour in its first instructions. -pub fn supported() -> bool { - supported_in(&crate::builds::get().vertical) -} - -fn supported_in(vertical: &crate::builds::VerticalTabs) -> bool { - if !vertical.detour_strip { - return false; - } - if vertical.window_feature != crate::builds::ABSENT { - return vertical.window_feature_prologue.len() >= SHORT_JUMP - && (vertical.set_bounds_rect == crate::builds::ABSENT - || vertical.set_bounds_rect_prologue.len() >= SHORT_JUMP); - } - vertical.should_draw_tab_strip != crate::builds::ABSENT - && vertical.should_draw_tab_strip_prologue.len() >= 14 -} - -/// What leaving the browser's tab strip out of the layout needs from the browser. -pub(crate) fn needs(build: &Build) -> Needs { - let row = &build.vertical; - let mut targets = Vec::new(); - if row.window_feature != crate::builds::ABSENT { - targets.push(Target::new( - "supports window feature", - row.window_feature, - row.window_feature_prologue, - )); - if row.set_bounds_rect != crate::builds::ABSENT { - targets.push(Target::new( - "set bounds rect", - row.set_bounds_rect, - row.set_bounds_rect_prologue, - )); - } - } else { - targets.push(Target::new( - "should draw tab strip", - row.should_draw_tab_strip, - row.should_draw_tab_strip_prologue, - )); - } - Needs::checked( - supported_in(row), - "this build does not record a tab strip detour", - targets, - ) -} - -/// The shortest prologue the short detour replaces: `mov rax, imm64; jmp rax` is 12 bytes. -const SHORT_JUMP: usize = 12; - -type SupportsFeature = unsafe extern "system" fn(*const c_void, u32, bool) -> bool; - -fn browsers() -> MutexGuard<'static, Vec<(isize, usize)>> { - BROWSERS.lock().unwrap_or_else(|error| error.into_inner()) -} - -/// Whether the call came from code inside `callers`, an RVA range of the browser image, or from -/// anywhere when it is `(0, 0)`. -unsafe fn asked_by_layout(callers: (usize, usize), caller: usize) -> bool { - if callers == (0, 0) { - return true; - } - let Some(image) = image::recorded() else { - return false; - }; - let address = caller.wrapping_sub(image.base); - address >= callers.0 && address < callers.1 -} - -// The detour is entered by a jump, so the browser's return address is on top of the stack. The -// stub hands it to the Rust function as a fourth argument and jumps there, which leaves the -// stack exactly as the browser's call made it. -std::arch::global_asm!( - ".globl rivet_supports_feature_stub", - "rivet_supports_feature_stub:", - "mov r9, [rsp]", - "jmp {target}", - target = sym supports_feature, -); - -extern "C" { - fn rivet_supports_feature_stub(); -} - -/// Answers no to the tab strip feature for the browsers of Rivet windows, when the layout asks. -unsafe extern "system" fn supports_feature( - browser: *const c_void, - feature: u32, - check: bool, - caller: usize, -) -> bool { - let vertical = &crate::builds::get().vertical; - if feature == vertical.window_feature_tab_strip - && browsers() - .iter() - .any(|(_, known)| *known == browser as usize) - && asked_by_layout(vertical.window_feature_callers, caller) - { - return false; - } - let original: SupportsFeature = std::mem::transmute(FEATURE_ORIGINAL.load(Ordering::Acquire)); - original(browser, feature, check) -} - -type SetBounds = unsafe extern "system" fn(*mut c_void, *const [i32; 4]); - -/// A view keeps its parent at +0x190, the begin and end of its children at +0x198 and +0x1A0 and -/// its bounds as x, y, width, height at +0x1C0, in the build this is recorded for. -const PARENT: usize = 0x190; -const CHILDREN: usize = 0x198; -const BOUNDS: usize = 0x1C0; - -/// A word of memory that may not belong to a view, read so that a wrong guess cannot fault. -unsafe fn read(address: usize, bytes: usize, out: *mut u8) -> bool { - use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; - // Memory known readable is copied in place, without a system call for every word. - if address > 0x10000 && crate::chromium::memory::readable(address, bytes) { - std::ptr::copy_nonoverlapping(address as *const u8, out, bytes); - return true; - } - address > 0x10000 - && ReadProcessMemory( - windows_sys::Win32::System::Threading::GetCurrentProcess(), - address as *const c_void, - out.cast(), - bytes, - std::ptr::null_mut(), - ) != 0 -} - -unsafe fn word(address: usize) -> Option { - let mut value = 0usize; - read(address, 8, (&mut value as *mut usize).cast()).then_some(value) -} - -unsafe fn bounds_of(view: usize) -> Option<[i32; 4]> { - let mut value = [0i32; 4]; - read(view + BOUNDS, 16, value.as_mut_ptr().cast()).then_some(value) -} - -/// The left edge, in the frame's coordinates, of the caption buttons: the right-aligned short row -/// among the frame's children, which is the caption button container. -unsafe fn caption_left(frame: usize) -> Option { - let frame_width = bounds_of(frame)?[2]; - let begin = word(frame + CHILDREN)?; - let end = word(frame + CHILDREN + 8)?; - if end < begin || (end - begin) / 8 > 64 { - return None; - } - let mut found = None; - for slot in (begin..end).step_by(8) { - let Some(child) = word(slot) else { continue }; - let Some([x, y, width, height]) = bounds_of(child) else { - continue; - }; - // The browser lays the client view out before the caption row, which has no height yet. - if width > 0 - && height <= 100 - && y <= 20 - && x + width >= frame_width - 20 - && x > frame_width / 2 - { - found = Some(found.map_or(x, |known: i32| known.min(x))); - } - } - found -} - -/// The toolbar of a Rivet window stops short of the caption buttons, which the browser's layout -/// left to the strip it no longer places. -unsafe extern "system" fn set_bounds_rect(view: *mut c_void, rect: *const [i32; 4]) { - let original: SetBounds = std::mem::transmute(BOUNDS_ORIGINAL.load(Ordering::Acquire)); - let vertical = &crate::builds::get().vertical; - let mut moved = *rect; - let known = locked() - .iter() - .any(|browser_view| word(browser_view + vertical.toolbar_in_view) == Some(view as usize)); - if known { - // The toggle button of the appbar sits over the toolbar's first button unless the toolbar - // starts after it. - let lead = vertical.toolbar_leading.min(moved[2]).max(0); - moved[0] += lead; - moved[2] -= lead; - let frame_vtable = - image::recorded().map(|image| image.base + crate::builds::get().layout.frame_vtable); - let mut at = word(view as usize + PARENT); - let mut left = 0; - for _ in 0..8 { - let Some(ancestor) = at else { break }; - if word(ancestor) == frame_vtable { - if let Some(caption) = caption_left(ancestor) { - moved[2] = moved[2].min(caption - left - moved[0]).max(0); - } - break; - } - let Some(bounds) = bounds_of(ancestor) else { - break; - }; - left += bounds[0]; - at = word(ancestor + PARENT); - } - } - original(view, &moved) -} - -unsafe extern "system" fn should_draw(view: *const c_void) -> bool { - if locked().contains(&(view as usize)) { - return false; - } - let original: ShouldDraw = std::mem::transmute(ORIGINAL.load(Ordering::Acquire)); - original(view) -} - -/// Detours the function once for the whole process. Nothing changes for a window until `hide`. -pub unsafe fn install() -> Result<(), String> { - INSTALLED.get_or_init(|| patch()).clone() -} - -unsafe fn patch() -> Result<(), String> { - if !supported() { - return Err("this browser build has no recorded tab strip function".into()); - } - let vertical = &crate::builds::get().vertical; - // In an app window the same window feature function is answered by the app window, which - // already leaves the tab strip out of the layout. Two detours on one prologue would refuse - // each other, whichever came first. - if answered_by_app_window( - vertical.window_feature, - crate::features::app_window::recorded("feature_impl"), - ) { - return Ok(()); - } - let image = image::recorded().ok_or("no recorded browser image")?; - let (rva, prologue, hook, original) = if vertical.window_feature != crate::builds::ABSENT { - ( - vertical.window_feature, - vertical.window_feature_prologue, - rivet_supports_feature_stub as *const () as usize, - &FEATURE_ORIGINAL, - ) - } else { - ( - vertical.should_draw_tab_strip, - vertical.should_draw_tab_strip_prologue, - should_draw as *const () as usize, - &ORIGINAL, - ) - }; - if vertical.set_bounds_rect != crate::builds::ABSENT - && !image.has(vertical.set_bounds_rect, vertical.set_bounds_rect_prologue) - { - return Err("SetBoundsRect is not the recorded function".into()); - } - detour(&image, rva, prologue, hook, original)?; - if vertical.set_bounds_rect != crate::builds::ABSENT { - detour( - &image, - vertical.set_bounds_rect, - vertical.set_bounds_rect_prologue, - set_bounds_rect as *const () as usize, - &BOUNDS_ORIGINAL, - )?; - } - Ok(()) -} - -/// Whether the app window's feature answer sits on the tab strip's window feature function. -fn answered_by_app_window(window_feature: usize, app_feature: Option) -> bool { - window_feature != crate::builds::ABSENT && app_feature == Some(window_feature) -} - -/// Replaces the first instructions of a function with a jump to `hook` and keeps them in a -/// trampoline that resumes the function after them. -unsafe fn detour( - image: &image::Image, - rva: usize, - prologue: &[u8], - hook: usize, - original: &AtomicUsize, -) -> Result<(), String> { - use crate::targets::{detour_styled, Cookie, Style}; - if !image.has(rva, prologue) { - return Err(format!("{rva:#x} is not the recorded function")); - } - let style = Style { - cookie: Cookie::None, - journaled: false, - absolute_if_room: true, - ..Style::JOURNALED - }; - detour_styled(image.base, rva, prologue, hook, Some(original), style).map(|_| ()) -} - -/// The browser view of a window, for the hook to recognise. -unsafe fn view_of(window: HWND) -> Option { - crate::features::tabs::browser_view(window).map(|view| view as usize) -} - -/// Removes the tab strip from the window's layout. -pub unsafe fn hide(window: HWND) -> bool { - if install().is_err() { - return false; - } - let Some(view) = view_of(window) else { - return false; - }; - if crate::builds::get().vertical.window_feature != crate::builds::ABSENT { - let Some(base) = image::recorded().map(|image| image.base) else { - return false; - }; - let Some(browser) = crate::features::tabs::browser(base, window) else { - return false; - }; - let mut known = browsers(); - known.retain(|(owner, _)| *owner != window as isize); - known.push((window as isize, browser as usize)); - } - let mut views = locked(); - if !views.contains(&view) { - views.push(view); - } - true -} - -/// Forgets a window that is going away, so its view's address is never matched again. -pub unsafe fn forget(window: HWND) { - if let Some(view) = view_of(window) { - locked().retain(|known| *known != view); - } - browsers().retain(|(owner, _)| *owner != window as isize); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fr13_samsung_window_feature_is_detoured_once_by_the_app_window() { - let vertical = &crate::builds::SAMSUNG.vertical; - let app = crate::builds::SAMSUNG - .app_window - .as_ref() - .and_then(|row| row.feature_impl); - assert!(answered_by_app_window(vertical.window_feature, app)); - // A build whose app window does not answer the feature keeps the tab strip detour. - assert!(!answered_by_app_window(vertical.window_feature, None)); - assert!(!answered_by_app_window(crate::builds::ABSENT, None)); - } -} diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index 5a00b8f..96dd628 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -2974,22 +2974,6 @@ fn attach_steps() -> Vec> { set_rivet_icons(window); true }), - feature( - Feature::TabStrip, - crate::features::tab_strip::needs, - |attach| unsafe { - let hidden = crate::features::tab_strip::hide(attach.window); - crate::trace::trace(&format!("tab strip hidden: {hidden}")); - if hidden { - Ok(()) - } else { - Err("the tab strip was not hidden".to_owned()) - } - }, - OnFailure::Continue, - true, - None, - ), Step::Setup(|attach| unsafe { // A frame change makes the browser lay out its frame again, now through the layout hook. SetWindowPos( @@ -4307,7 +4291,6 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> crate::features::link_preview::forget(window); crate::features::page_links::forget(window); APPBAR_STATE.with(|states| states.borrow_mut().remove(&(window as isize))); - crate::features::tab_strip::forget(window); frame_layout::forget_view(window); crate::features::widgets::forget(window); crate::side_rail::forget(window); diff --git a/scripts/tests/layers.baseline b/scripts/tests/layers.baseline index 76d8219..a47b235 100644 --- a/scripts/tests/layers.baseline +++ b/scripts/tests/layers.baseline @@ -60,9 +60,6 @@ rivet/runtime/windows/src/features/split.rs unsafe 17 rivet/runtime/windows/src/features/split.rs windows_sys 4 rivet/runtime/windows/src/features/tab_list.rs unsafe 17 rivet/runtime/windows/src/features/tab_list.rs windows_sys 1 -rivet/runtime/windows/src/features/tab_strip.rs rows 21 -rivet/runtime/windows/src/features/tab_strip.rs unsafe 17 -rivet/runtime/windows/src/features/tab_strip.rs windows_sys 3 rivet/runtime/windows/src/features/tabs.rs rows 56 rivet/runtime/windows/src/features/tabs.rs unsafe 52 rivet/runtime/windows/src/features/tabs.rs windows_sys 5 From 6c73d3ae085df46ff1179ffe7465f8dd2fd704e6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:58:53 +0000 Subject: [PATCH 23/29] Publish: develop 4dcc35b to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- scripts/tests/layers.test.sh | 250 ++++++++++++++++++----------------- 1 file changed, 126 insertions(+), 124 deletions(-) diff --git a/scripts/tests/layers.test.sh b/scripts/tests/layers.test.sh index 4e0d00f..65626aa 100755 --- a/scripts/tests/layers.test.sh +++ b/scripts/tests/layers.test.sh @@ -1,124 +1,126 @@ -#!/usr/bin/env bash -# Keeps the feature layer of the Windows runtime off Windows calls and off Chromium internals. -# -# A file under rivet/runtime/windows/src/features/ may use only the traits of the operating -# system layer and the browser access layer. It must not name `windows_sys`, write `unsafe` or -# read a build row. Most features still do all three, so the current counts are recorded in -# scripts/tests/layers.baseline. A count may go down as features move behind the traits, but it -# may never go up, and a file that is not in the baseline must have none. -# -# Usage: layers.test.sh check the counts against the baseline -# layers.test.sh --update write the current counts as the new baseline -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -cd "$repo_root" - -features="rivet/runtime/windows/src/features" -baseline="scripts/tests/layers.baseline" - -# One pattern per kind of violation. Comment lines are left out before matching. -kinds=(windows_sys unsafe rows) -pattern_windows_sys='windows_sys' -pattern_unsafe='\bunsafe\b' -pattern_rows='builds::|row_data|\bbv\(\)|\brow\(\)|\bBuild\b' - -pattern_of() { - local name="pattern_$1" - printf '%s' "${!name}" -} - -# Counts the lines of standard input that match one kind, ignoring comment lines. -count_kind() { - grep -vE '^[[:space:]]*//' | grep -cE "$(pattern_of "$1")" || true -} - -# Checks the counter itself on a small sample, so a broken pattern cannot pass every file. -self_check() { - local sample - sample=$'use windows_sys::Win32::Foundation::HWND;\n' - sample+=$'unsafe fn f() {}\n' - sample+=$'let x = unsafe { g() };\n' - sample+=$'// unsafe in a comment does not count\n' - sample+=$'fn bv() -> &\'static crate::builds::Tabs { todo!() }\n' - sample+=$'let y = bv().tab_at;\n' - sample+=$'fn needs(build: &Build) {}\n' - sample+=$'let unsafely = 1; let Builder = 2;\n' - local expected=(1 2 3) - local index=0 - for kind in "${kinds[@]}"; do - local got - got="$(printf '%s' "$sample" | count_kind "$kind")" - if [[ "$got" != "${expected[$index]}" ]]; then - echo "error: the $kind counter found $got lines in the sample, expected ${expected[$index]}" >&2 - exit 1 - fi - index=$((index + 1)) - done -} - -# Prints " " for every non-zero count, sorted. -current_counts() { - git ls-files --cached --others --exclude-standard -- "$features/*.rs" | sort -u | while read -r file; do - [[ -f "$file" ]] || continue - for kind in "${kinds[@]}"; do - local count - count="$(count_kind "$kind" <"$file")" - if [[ "$count" != "0" ]]; then - echo "$file $kind $count" - fi - done - done | sort -} - -self_check -counts="$(current_counts)" - -if [[ "${1:-}" == "--update" ]]; then - { - echo "# Feature layer violations per file: ." - echo "# Written by scripts/tests/layers.test.sh --update. Counts may only go down." - printf '%s\n' "$counts" - } >"$baseline" - echo "ok wrote $baseline" - exit 0 -fi - -if [[ ! -f "$baseline" ]]; then - echo "error: $baseline is missing; run $0 --update" >&2 - exit 1 -fi - -failed=0 -lowered=0 -while read -r file kind count; do - [[ -n "$file" ]] || continue - allowed="$(awk -v f="$file" -v k="$kind" '$1 == f && $2 == k { print $3 }' "$baseline")" - allowed="${allowed:-0}" - if (( count > allowed )); then - echo "error: $file has $count $kind lines, the baseline allows $allowed" >&2 - failed=1 - fi -done <<<"$counts" - -while read -r file kind allowed; do - [[ -n "$file" && "$file" != \#* ]] || continue - count="$(awk -v f="$file" -v k="$kind" '$1 == f && $2 == k { print $3 }' <<<"$counts")" - count="${count:-0}" - if (( count < allowed )); then - echo "note $file has $count $kind lines, below its baseline of $allowed" - lowered=1 - fi -done <"$baseline" - -if (( failed )); then - echo "error: the feature layer must use only the operating system and browser access traits" >&2 - exit 1 -fi -if (( lowered )); then - echo "note run $0 --update to lower the baseline" -fi -for kind in "${kinds[@]}"; do - total="$(awk -v k="$kind" '$2 == k { sum += $3 } END { print sum + 0 }' <<<"$counts")" - echo "ok $kind lines in features: $total, none above the baseline" -done +#!/usr/bin/env bash +# Keeps the feature layer of the Windows runtime off Windows calls and off Chromium internals. +# +# A file under rivet/runtime/windows/src/features/ may use only the traits of the operating +# system layer and the browser access layer. It must not name `windows_sys`, write `unsafe` or +# read a build row. Most features still do all three, so the current counts are recorded in +# scripts/tests/layers.baseline. A count may go down as features move behind the traits, but it +# may never go up, and a file that is not in the baseline must have none. +# +# Usage: layers.test.sh check the counts against the baseline +# layers.test.sh --update write the current counts as the new baseline +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo_root" + +features="rivet/runtime/windows/src/features" +baseline="scripts/tests/layers.baseline" + +# One pattern per kind of violation. Comment lines are left out before matching. +kinds=(windows_sys unsafe rows) +pattern_windows_sys='windows_sys' +pattern_unsafe='\bunsafe\b' +pattern_rows='builds::|row_data|\bbv\(\)|\brow\(\)|\bBuild\b' + +pattern_of() { + local name="pattern_$1" + printf '%s' "${!name}" +} + +# Counts the lines of standard input that match one kind, ignoring comment lines. +count_kind() { + grep -vE '^[[:space:]]*//' | grep -cE "$(pattern_of "$1")" || true +} + +# Checks the counter itself on a small sample, so a broken pattern cannot pass every file. +self_check() { + local sample + sample=$'use windows_sys::Win32::Foundation::HWND;\n' + sample+=$'unsafe fn f() {}\n' + sample+=$'let x = unsafe { g() };\n' + sample+=$'// unsafe in a comment does not count\n' + sample+=$'fn bv() -> &\'static crate::builds::Tabs { todo!() }\n' + sample+=$'let y = bv().tab_at;\n' + sample+=$'fn needs(build: &Build) {}\n' + sample+=$'let unsafely = 1; let Builder = 2;\n' + local expected=(1 2 3) + local index=0 + for kind in "${kinds[@]}"; do + local got + got="$(printf '%s' "$sample" | count_kind "$kind")" + if [[ "$got" != "${expected[$index]}" ]]; then + echo "error: the $kind counter found $got lines in the sample, expected ${expected[$index]}" >&2 + exit 1 + fi + index=$((index + 1)) + done +} + +# Prints " " for every non-zero count, sorted. +current_counts() { + git ls-files --cached --others --exclude-standard -- "$features/*.rs" | sort -u | while read -r file; do + [[ -f "$file" ]] || continue + for kind in "${kinds[@]}"; do + local count + count="$(count_kind "$kind" <"$file")" + if [[ "$count" != "0" ]]; then + echo "$file $kind $count" + fi + done + done | sort +} + +self_check +counts="$(current_counts)" + +if [[ "${1:-}" == "--update" ]]; then + { + echo "# Feature layer violations per file: ." + echo "# Written by scripts/tests/layers.test.sh --update. Counts may only go down." + printf '%s\n' "$counts" + } >"$baseline" + echo "ok wrote $baseline" + exit 0 +fi + +if [[ ! -f "$baseline" ]]; then + echo "error: $baseline is missing; run $0 --update" >&2 + exit 1 +fi + +failed=0 +# A checkout on Windows may give the file carriage returns, which are not part of a count. +rows="$(tr -d '\r ' <"$baseline")" +lowered=0 +while read -r file kind count; do + [[ -n "$file" ]] || continue + allowed="$(awk -v f="$file" -v k="$kind" '$1 == f && $2 == k { print $3 }' <<<"$rows")" + allowed="${allowed:-0}" + if (( count > allowed )); then + echo "error: $file has $count $kind lines, the baseline allows $allowed" >&2 + failed=1 + fi +done <<<"$counts" + +while read -r file kind allowed; do + [[ -n "$file" && "$file" != \#* ]] || continue + count="$(awk -v f="$file" -v k="$kind" '$1 == f && $2 == k { print $3 }' <<<"$counts")" + count="${count:-0}" + if (( count < allowed )); then + echo "note $file has $count $kind lines, below its baseline of $allowed" + lowered=1 + fi +done <<<"$rows" + +if (( failed )); then + echo "error: the feature layer must use only the operating system and browser access traits" >&2 + exit 1 +fi +if (( lowered )); then + echo "note run $0 --update to lower the baseline" +fi +for kind in "${kinds[@]}"; do + total="$(awk -v k="$kind" '$2 == k { sum += $3 } END { print sum + 0 }' <<<"$counts")" + echo "ok $kind lines in features: $total, none above the baseline" +done From c7d0835a69862bcde50e88905b1301697b71dfd0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:34:53 +0000 Subject: [PATCH 24/29] Publish: develop ec2fd00 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/runtime/windows/src/appbar.rs | 8 + .../windows/src/features/frame_layout.rs | 115 +++++++- .../src/features/layout_experiments.rs | 255 ++++++++++++++++++ rivet/runtime/windows/src/features/mod.rs | 1 + .../windows/src/features/second_view.rs | 21 ++ rivet/runtime/windows/src/frame.rs | 220 ++++++++++++++- rivet/runtime/windows/src/hooks/page_area.rs | 29 ++ 7 files changed, 639 insertions(+), 10 deletions(-) create mode 100644 rivet/runtime/windows/src/features/layout_experiments.rs diff --git a/rivet/runtime/windows/src/appbar.rs b/rivet/runtime/windows/src/appbar.rs index 961bf07..4b2ad8e 100644 --- a/rivet/runtime/windows/src/appbar.rs +++ b/rivet/runtime/windows/src/appbar.rs @@ -600,6 +600,14 @@ impl Appbar { } } + /// Experiment: moves every Rivet visual of the window by `x` and `y` physical pixels, so they keep + /// their place in the window while the client area starts further in. + pub(crate) unsafe fn offset_root(&self, x: f32, y: f32) -> Result<()> { + self.root.SetOffsetX2(x)?; + self.root.SetOffsetY2(y)?; + self.device.Commit() + } + fn scene(&self) -> Scene<'_> { Scene { tabs: &self.tabs, diff --git a/rivet/runtime/windows/src/features/frame_layout.rs b/rivet/runtime/windows/src/features/frame_layout.rs index cda859d..06fd4b5 100644 --- a/rivet/runtime/windows/src/features/frame_layout.rs +++ b/rivet/runtime/windows/src/features/frame_layout.rs @@ -493,7 +493,22 @@ unsafe extern "system" fn client_view_bounds(view: *const c_void, out: *mut Rect *out = panel_from_client(*out); lift_cached_client_area(view, browser_chose); } - record_panel((hook.hwnd_for_view)(view), *out); + let window = (hook.hwnd_for_view)(view); + // With the client area shrunk by Windows, Rivet still draws in the coordinates of the + // whole window, so the panel it records moves back by the inset. + let shift = crate::frame::client_inset_dips(window); + let recorded = shifted(*out, shift); + if shift != [0, 0] { + crate::trace::trace_changed( + "experiment client view", + &format!( + "experiment client area: the browser chose client view {browser_chose:?}, \ + panel {:?} in the client, {recorded:?} in the window", + *out + ), + ); + } + record_panel(window, recorded); } result } @@ -524,6 +539,26 @@ fn record_panel(window: HWND, panel: Rect) { } } +/// `bounds` moved by `shift` DIPs. +fn shifted(bounds: Rect, shift: [i32; 2]) -> Rect { + Rect { + x: bounds.x + shift[0], + y: bounds.y + shift[1], + ..bounds + } +} + +/// The panel of a Rivet window from its client area alone, as the browser's layout would place it +/// with the client view hook: `reserved` DIPs at the left, then the panel's gap. +pub fn rivet_panel(client: Rect, reserved: i32) -> Rect { + panel_from_client(reserve_leading(client, reserved)) +} + +/// Records a panel Rivet placed itself, where the browser's layout is not hooked. +pub fn place_panel(window: HWND, panel: Rect) { + record_panel(window, panel); +} + /// The page panel the browser laid out for a window, once it has laid the window out. pub fn panel_bounds(window: HWND) -> Option { PANELS @@ -537,13 +572,22 @@ pub fn panel_bounds(window: HWND) -> Option { /// Installs the layout hook once per browser process. Returns why it cannot when the build is /// not recognised, so Rivet refuses to attach rather than guess. pub unsafe fn install(reserved: Reserve) -> Result<(), String> { - HOOK.get_or_init(|| patch(reserved)) + HOOK.get_or_init(|| patch(reserved, true)) .as_ref() .map(|_| ()) .map_err(Clone::clone) } -unsafe fn patch(reserved: Reserve) -> Result { +/// Experiment: finds the build's frame view functions as `install` does, so a view's window can be +/// told, but leaves the client view placement to the browser. Rivet then places the panel itself. +pub unsafe fn install_unpatched(reserved: Reserve) -> Result<(), String> { + HOOK.get_or_init(|| patch(reserved, false)) + .as_ref() + .map(|_| ()) + .map_err(Clone::clone) +} + +unsafe fn patch(reserved: Reserve, replace_slot: bool) -> Result { log(&format!("rivet: {}", crate::builds::table_note())); crate::trace::trace(&format!("build table: {}", crate::builds::table_note())); let (build, image) = crate::builds::frame_rows() @@ -568,6 +612,14 @@ unsafe fn patch(reserved: Reserve) -> Result { ), reserved, }; + if !replace_slot { + log(&format!( + "rivet: {} {} keeps its own client view placement", + build.browser, build.version + )); + crate::trace::trace("experiment page view only: the client view placement is not replaced"); + return Ok(hook); + } // Layout runs on this UI thread only, so no call can reach the new slot before HOOK holds // this value. let mut previous: PAGE_PROTECTION_FLAGS = 0; @@ -676,6 +728,57 @@ mod tests { } } + #[test] + fn fr12_panel_placed_by_rivet_matches_the_hooked_layout() { + // The browser's client view reaches the window's top edge once lifted, so the panel Rivet + // works out from the client area is the one the hook makes of any title row height. + let client = Rect { + x: 0, + y: 0, + width: 1600, + height: 1000, + }; + for top in [0, 32, 41] { + let chose = Rect { + y: top, + height: 1000 - top, + ..client + }; + assert_eq!( + rivet_panel(client, 268), + panel_from_client(reserve_leading(chose, 268)) + ); + } + assert_eq!( + rivet_panel(client, 268), + Rect { + x: 268, + y: PANEL_GAP, + width: 1324, + height: 1000 - 2 * PANEL_GAP + } + ); + } + + #[test] + fn fr2_panel_in_a_shrunk_client_area_is_recorded_in_window_coordinates() { + let panel = Rect { + x: 0, + y: 8, + width: 1324, + height: 984, + }; + assert_eq!(shifted(panel, [0, 0]), panel); + assert_eq!( + shifted(panel, [268, 52]), + Rect { + x: 268, + y: 60, + ..panel + } + ); + } + #[test] fn fr12_caption_ink_is_independent_of_window_activation() { assert_eq!(caption_ink(), 0xff1a_1a1a); @@ -951,6 +1054,12 @@ unsafe fn clip_panel(frame: *mut c_void) { /// can undo it and the caller repeats it after each layout. pub unsafe fn raise_view(view: *mut c_void) { let Some((set_layer, _, _)) = PANEL_LAYER.get() else { + if crate::features::layout_experiments::page_view_only() { + crate::trace::trace_changed( + "experiment raise", + "experiment page view only: no layer helpers, the side panel is not raised", + ); + } return; }; let Some(stack_at_top) = STACK_AT_TOP.get() else { diff --git a/rivet/runtime/windows/src/features/layout_experiments.rs b/rivet/runtime/windows/src/features/layout_experiments.rs new file mode 100644 index 0000000..b2239d8 --- /dev/null +++ b/rivet/runtime/windows/src/features/layout_experiments.rs @@ -0,0 +1,255 @@ +//! Two experiments that leave room for Rivet's surfaces without hooking the browser's layout. +//! +//! Both are off unless switched on for the browser process. A switch is an environment variable +//! the browser process inherits, or a flag file of the same name in the debug folder. Each is read +//! once per process, so a change needs a new browser process. +//! +//! - `RIVET_EXPERIMENT_NCCALCSIZE`: the window procedure answers `WM_NCCALCSIZE` with a client +//! area that leaves out the appbar's column (`1`), or the column and the top row (`2`). The +//! browser then lays itself out in the smaller client area, and the frame layout hook reserves +//! nothing. Rivet's visuals move by the same amount the other way, which shows whether a visual +//! of the window's composition target can still draw outside the client area. +//! - `RIVET_EXPERIMENT_PAGE_VIEW_ONLY`: the frame view's client view placement is not replaced, +//! the caption layout, caption height and top inset are not installed and the page area layout +//! is not patched. Rivet works out the panel from the client area itself and places the window's +//! page view, and the pages of a grid, inside it. +//! +//! When both are on, only the page view experiment runs, since it already places every page. + +use std::sync::OnceLock; + +use crate::features::frame_layout::Rect; + +/// The environment variable and flag file name of experiment A. +pub(crate) const NCCALCSIZE: &str = "RIVET_EXPERIMENT_NCCALCSIZE"; +/// The environment variable and flag file name of experiment B. +pub(crate) const PAGE_VIEW_ONLY: &str = "RIVET_EXPERIMENT_PAGE_VIEW_ONLY"; + +/// What experiment A takes out of the client area. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum NcInset { + Off, + /// The appbar's column at the left. + Left, + /// The appbar's column and the top row. + LeftAndTop, +} + +/// Experiment A from the variable's value and whether its flag file exists. A flag file alone +/// means the column only. +pub(crate) fn parse_nccalcsize(value: Option<&str>, flag: bool) -> NcInset { + let value = value.map(|value| value.trim().to_ascii_lowercase()); + match value.as_deref() { + Some("1" | "left" | "on" | "true") => NcInset::Left, + Some("2" | "top" | "left+top") => NcInset::LeftAndTop, + Some("0" | "off" | "false") => NcInset::Off, + _ if flag => NcInset::Left, + _ => NcInset::Off, + } +} + +/// An on or off switch from the variable's value and whether its flag file exists. +pub(crate) fn parse_switch(value: Option<&str>, flag: bool) -> bool { + let value = value.map(|value| value.trim().to_ascii_lowercase()); + match value.as_deref() { + Some("1" | "on" | "true") => true, + Some("0" | "off" | "false") => false, + _ => flag, + } +} + +/// Experiment A gives way to experiment B, which places every page itself. +pub(crate) fn effective_nccalcsize(inset: NcInset, page_view_only: bool) -> NcInset { + if page_view_only { + NcInset::Off + } else { + inset + } +} + +fn flag_exists(name: &str) -> bool { + crate::frame::debug_directory() + .is_some_and(|dir| dir.join(format!("{name}.flag")).exists()) +} + +fn variable(name: &str) -> Option { + std::env::var(name).ok() +} + +/// Experiment B, read once per process. +pub(crate) fn page_view_only() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = parse_switch( + variable(PAGE_VIEW_ONLY).as_deref(), + flag_exists(PAGE_VIEW_ONLY), + ); + crate::trace::trace(&format!("experiment: page view only {on}")); + on + }) +} + +/// Experiment A, read once per process. +pub(crate) fn nccalcsize() -> NcInset { + static INSET: OnceLock = OnceLock::new(); + *INSET.get_or_init(|| { + let inset = effective_nccalcsize( + parse_nccalcsize(variable(NCCALCSIZE).as_deref(), flag_exists(NCCALCSIZE)), + page_view_only(), + ); + crate::trace::trace(&format!("experiment: client area inset {inset:?}")); + inset + }) +} + +/// The pixels experiment A takes from the left and the top of the client area, for an appbar +/// column `leading` DIPs wide and a top row `top` DIPs tall, at `dpi`. +pub(crate) fn nc_inset_pixels(inset: NcInset, leading: i32, top: i32, dpi: u32) -> [i32; 2] { + let pixels = |dips: i32| (dips.max(0) * dpi as i32 + 48) / 96; + match inset { + NcInset::Off => [0, 0], + NcInset::Left => [pixels(leading), 0], + NcInset::LeftAndTop => [pixels(leading), pixels(top)], + } +} + +/// The client rect, as left, top, right and bottom, with `left` and `top` pixels taken from it. +/// At least one pixel of width and height is always left. +pub(crate) fn shrink_client(rect: [i32; 4], left: i32, top: i32) -> [i32; 4] { + let [l, t, r, b] = rect; + let left = left.clamp(0, (r - l - 1).max(0)); + let top = top.clamp(0, (b - t - 1).max(0)); + [l + left, t + top, r, b] +} + +/// A client size in pixels as DIPs at `dpi`. +pub(crate) fn client_dips(width: i32, height: i32, dpi: u32) -> [i32; 2] { + let dips = |pixels: i32| (pixels.max(0) * 96 + dpi as i32 / 2) / dpi.max(1) as i32; + [dips(width), dips(height)] +} + +/// The bounds of the page view, in its parent's coordinates, for the panel Rivet placed in window +/// DIPs. `parent` is the window position of the page view's parent, and `bar` the height of the +/// bar row at the top of the panel. +pub(crate) fn page_view_rect(panel: Rect, parent: [i32; 2], bar: i32) -> [i32; 4] { + let bar = bar.clamp(0, (panel.height - 1).max(0)); + [ + panel.x - parent[0], + panel.y - parent[1] + bar, + panel.width.max(1), + (panel.height - bar).max(1), + ] +} + +/// The client inset experiment A applied to each window last, in pixels, so Rivet's visuals move +/// back by it. +static APPLIED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Remembers the inset applied to a window. Returns whether it changed. +pub(crate) fn remember_inset(window: isize, inset: [i32; 2]) -> bool { + let mut all = APPLIED.lock().unwrap_or_else(|error| error.into_inner()); + match all.iter_mut().find(|entry| entry.0 == window) { + Some(entry) => std::mem::replace(&mut entry.1, inset) != inset, + None => { + all.push((window, inset)); + inset != [0, 0] + } + } +} + +/// The inset experiment A applied to a window last, in pixels. +pub(crate) fn applied_inset(window: isize) -> [i32; 2] { + APPLIED + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .find(|entry| entry.0 == window) + .map_or([0, 0], |entry| entry.1) +} + +pub(crate) fn forget(window: isize) { + APPLIED + .lock() + .unwrap_or_else(|error| error.into_inner()) + .retain(|entry| entry.0 != window); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nfr3_layout_experiments_are_off_unless_switched_on() { + assert_eq!(parse_nccalcsize(None, false), NcInset::Off); + assert_eq!(parse_nccalcsize(Some(""), false), NcInset::Off); + assert_eq!(parse_nccalcsize(Some("0"), true), NcInset::Off); + assert_eq!(parse_nccalcsize(Some("1"), false), NcInset::Left); + assert_eq!(parse_nccalcsize(Some(" Left "), false), NcInset::Left); + assert_eq!(parse_nccalcsize(Some("2"), false), NcInset::LeftAndTop); + assert_eq!(parse_nccalcsize(None, true), NcInset::Left); + assert!(!parse_switch(None, false)); + assert!(!parse_switch(Some("yes please"), false)); + assert!(parse_switch(Some("1"), false)); + assert!(parse_switch(Some("TRUE"), false)); + assert!(parse_switch(None, true)); + assert!(!parse_switch(Some("off"), true)); + } + + #[test] + fn nfr3_client_area_experiment_gives_way_to_page_view_only() { + assert_eq!(effective_nccalcsize(NcInset::Left, true), NcInset::Off); + assert_eq!(effective_nccalcsize(NcInset::LeftAndTop, false), NcInset::LeftAndTop); + } + + #[test] + fn fr2_client_area_leaves_out_the_appbar_column_at_the_window_scale() { + assert_eq!(nc_inset_pixels(NcInset::Off, 268, 52, 144), [0, 0]); + assert_eq!(nc_inset_pixels(NcInset::Left, 268, 52, 96), [268, 0]); + assert_eq!(nc_inset_pixels(NcInset::Left, 268, 52, 144), [402, 0]); + assert_eq!(nc_inset_pixels(NcInset::LeftAndTop, 268, 52, 144), [402, 78]); + // A hidden appbar takes nothing. + assert_eq!(nc_inset_pixels(NcInset::LeftAndTop, 0, 0, 120), [0, 0]); + } + + #[test] + fn fr2_shrunk_client_area_keeps_one_pixel() { + assert_eq!(shrink_client([0, 0, 1600, 1000], 402, 78), [402, 78, 1600, 1000]); + assert_eq!(shrink_client([8, 8, 1608, 1008], 402, 0), [410, 8, 1608, 1008]); + assert_eq!(shrink_client([0, 0, 100, 50], 400, 400), [99, 49, 100, 50]); + assert_eq!(shrink_client([0, 0, 100, 50], -5, -5), [0, 0, 100, 50]); + } + + #[test] + fn fr12_client_pixels_become_dips_at_the_window_scale() { + assert_eq!(client_dips(1600, 1000, 96), [1600, 1000]); + assert_eq!(client_dips(2400, 1500, 144), [1600, 1000]); + assert_eq!(client_dips(2000, 1250, 120), [1600, 1000]); + } + + #[test] + fn fr12_page_view_sits_below_the_bar_inside_the_panel() { + let panel = Rect { + x: 268, + y: 8, + width: 1324, + height: 984, + }; + // A parent at the window's origin. + assert_eq!(page_view_rect(panel, [0, 0], 44), [268, 52, 1324, 940]); + // A parent that starts below the browser's own title row. + assert_eq!(page_view_rect(panel, [0, 32], 44), [268, 20, 1324, 940]); + // A bar taller than the panel leaves one DIP of page. + assert_eq!(page_view_rect(Rect { height: 10, ..panel }, [0, 0], 44)[3], 1); + } + + #[test] + fn fr2_applied_inset_is_remembered_per_window() { + let window = 0x7777_0001; + assert_eq!(applied_inset(window), [0, 0]); + assert!(remember_inset(window, [402, 0])); + assert!(!remember_inset(window, [402, 0])); + assert_eq!(applied_inset(window), [402, 0]); + forget(window); + assert_eq!(applied_inset(window), [0, 0]); + } +} diff --git a/rivet/runtime/windows/src/features/mod.rs b/rivet/runtime/windows/src/features/mod.rs index 495dc87..6d61336 100644 --- a/rivet/runtime/windows/src/features/mod.rs +++ b/rivet/runtime/windows/src/features/mod.rs @@ -10,6 +10,7 @@ pub(crate) mod dev_page; pub(crate) mod dev_tools; pub(crate) mod field_caret; pub(crate) mod frame_layout; +pub(crate) mod layout_experiments; pub(crate) mod link_preview; pub(crate) mod link_rules; pub(crate) mod link_tabs; diff --git a/rivet/runtime/windows/src/features/second_view.rs b/rivet/runtime/windows/src/features/second_view.rs index 64f5367..636bbc1 100644 --- a/rivet/runtime/windows/src/features/second_view.rs +++ b/rivet/runtime/windows/src/features/second_view.rs @@ -773,6 +773,27 @@ unsafe fn area_of(split: &Split) -> Option<[i32; 4]> { ); *FULL.lock().unwrap_or_else(|error| error.into_inner()) = now; } + // Experiment: the page area is the panel Rivet placed, not what the browser gave the page view. + if crate::features::layout_experiments::page_view_only() { + if let Some(panel) = crate::features::frame_layout::panel_bounds(split.window as HWND) { + let [ox, oy] = window_origin(split.main); + let parent = [ox - now[0], oy - now[1]]; + let full = crate::features::layout_experiments::page_view_rect(panel, parent, 0); + *FULL.lock().unwrap_or_else(|error| error.into_inner()) = full; + let container = word(split.main + offsets().0) + .filter(|parent| *parent != 0) + .map(|parent| bounds_of(parent)); + crate::trace::trace_changed( + "experiment page view area", + &format!( + "experiment page view only: panel {panel:?}, page view parent at {parent:?} \ + with bounds {container:?}, browser gave {now:?}, Rivet's area {full:?}, \ + bar row {}", + top_of(split.window) + ), + ); + } + } let full = *FULL.lock().unwrap_or_else(|error| error.into_inner()); let full = fitted(split.main, full); (full[2] > 0).then(|| below_bar(full, top_inset(split, full))) diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index 96dd628..88649e7 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -24,10 +24,10 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{ HTMINBUTTON, HTTOP, HTTOPLEFT, ICON_BIG, ICON_SMALL, IDC_SIZEWE, MSG, PM_REMOVE, SM_CXICON, SM_CXPADDEDBORDER, SM_CXSMICON, SM_CYSIZEFRAME, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WH_GETMESSAGE, WM_CAPTURECHANGED, WM_CLOSE, WM_DPICHANGED, - WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCDESTROY, WM_NCHITTEST, - WM_NCLBUTTONDBLCLK, WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_NCMOUSELEAVE, WM_NCMOUSEMOVE, - WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_NULL, WM_SETCURSOR, WM_SETICON, WM_SYSCOMMAND, - WM_WINDOWPOSCHANGED, WNDPROC, WS_THICKFRAME, + WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCCALCSIZE, WM_NCDESTROY, + WM_NCHITTEST, WM_NCLBUTTONDBLCLK, WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_NCMOUSELEAVE, + WM_NCMOUSEMOVE, WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_NULL, WM_SETCURSOR, WM_SETICON, + WM_SYSCOMMAND, WM_WINDOWPOSCHANGED, WNDPROC, WS_THICKFRAME, }; use super::appbar::Appbar; @@ -2015,6 +2015,26 @@ unsafe fn toggle_message() -> u32 { /// Lays the browser out again, now that the appbar's width or mode changed, and redraws. unsafe fn relayout(window: HWND) { + use crate::features::layout_experiments::{self, NcInset}; + // Experiment: Windows takes the appbar's column out of the client area again at its new width. + if attached(window) && layout_experiments::nccalcsize() != NcInset::Off { + SetWindowPos( + window, + std::ptr::null_mut(), + 0, + 0, + 0, + 0, + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ); + } + // Experiment: Rivet places the panel and the page view, the browser's layout is not asked. + if attached(window) && layout_experiments::page_view_only() { + place_panel_by_rivet(window); + follow_second_view(window); + update_appbar(window); + return; + } // The frame view lays out again on request, which also works for a maximized window. if frame_layout::relayout(window) { if is_waiting(window) { @@ -2820,7 +2840,20 @@ fn top_inset_extra(window: HWND) -> Option { /// have leaves the window as it is, and a failure of a feature the window cannot do without ends /// the attach, so the browser keeps working without Rivet. fn attach_steps() -> Vec> { + attach_steps_for(crate::features::layout_experiments::page_view_only()) +} + +/// The attach sequence. `page_view_only` is the experiment that leaves the browser's layout alone: +/// the frame view's functions are found but its client view placement is not replaced, and the +/// caption layout, caption height and top inset are not installed. Rivet places the panel and the +/// page view itself. +fn attach_steps_for(page_view_only: bool) -> Vec> { use crate::feature::{Feature, FeatureStep, OnFailure, Step}; + let frame_install: fn(&mut Attach) -> Result<(), String> = if page_view_only { + |_| unsafe { frame_layout::install_unpatched(reserved_width) } + } else { + |_| unsafe { frame_layout::install(reserved_width) } + }; let feature = |feature, needs, install, on_failure, skip_when_unavailable, log_failure| { Step::Feature(FeatureStep { feature, @@ -2831,11 +2864,11 @@ fn attach_steps() -> Vec> { log_failure, }) }; - vec![ + let mut steps = vec![ feature( Feature::FrameLayout, frame_layout::needs_layout, - |_| unsafe { frame_layout::install(reserved_width) }, + frame_install, OnFailure::Abort, false, Some("rivet: not attaching to this browser"), @@ -2912,6 +2945,11 @@ fn attach_steps() -> Vec> { if crate::trace::tracing() { crate::trace::trace_crashes(); } + crate::trace::trace(&format!( + "experiments: page view only {}, client area inset {:?}", + crate::features::layout_experiments::page_view_only(), + crate::features::layout_experiments::nccalcsize() + )); true }), Step::Setup(|_| unsafe { @@ -2986,9 +3024,131 @@ fn attach_steps() -> Vec> { SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, ); update_appbar(attach.window); + // Without the client view hook no browser layout tells Rivet where the panel is. + if crate::features::layout_experiments::page_view_only() { + place_panel_by_rivet(attach.window); + } true }), - ] + ]; + if page_view_only { + steps.retain(|step| { + !matches!( + step, + Step::Feature(step) if matches!( + step.feature, + Feature::CaptionLayout | Feature::CaptionHeight | Feature::TopInset + ) + ) + }); + } + steps +} + +/// Experiment: the panel of a window from its client area, placed by Rivet where the browser's +/// client view placement is not hooked. This also does what the hooked layout does for the window: +/// it records the layout's scale and lets a window that waits for its first layout show. +pub(crate) unsafe fn place_panel_by_rivet(window: HWND) { + if !attached(window) || IsIconic(window) != 0 { + return; + } + let mut client: RECT = std::mem::zeroed(); + GetClientRect(window, &mut client); + let [width, height] = + crate::features::layout_experiments::client_dips(client.right, client.bottom, dpi(window)); + if width <= 0 || height <= 0 { + return; + } + let bounds = frame_layout::Rect { + x: 0, + y: 0, + width, + height, + }; + let Some(reserved) = reserved_width(window, bounds) else { + return; + }; + let panel = frame_layout::rivet_panel(bounds, reserved); + crate::trace::trace_changed( + "experiment page view panel", + &format!( + "experiment page view only: client {}x{} px at {} dpi, panel {panel:?}", + client.right, + client.bottom, + dpi(window) + ), + ); + frame_layout::place_panel(window, panel); + crate::features::second_view::note_layout(); +} + +/// Experiment: the inset Windows took from a window's client area, in DIPs at the window's layout +/// scale. Zero unless the client area experiment runs. +pub(crate) fn client_inset_dips(window: HWND) -> [i32; 2] { + let [left, top] = crate::features::layout_experiments::applied_inset(window as isize); + if left == 0 && top == 0 { + return [0, 0]; + } + let dpi = unsafe { layout_dpi(window) }.max(96) as i32; + [(left * 96 + dpi / 2) / dpi, (top * 96 + dpi / 2) / dpi] +} + +/// Experiment: answers `WM_NCCALCSIZE` with the browser's client area less the appbar's column, and +/// less the top row when asked, and moves Rivet's visuals back by the same amount. +unsafe fn shrink_client_area(window: HWND, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + use crate::features::layout_experiments; + let result = call_browser(window, WM_NCCALCSIZE, wparam, lparam); + if wparam == 0 || lparam == 0 { + return result; + } + let inset = layout_experiments::nccalcsize(); + let leading = if framed(window) { + layout_of(window).leading() + } else { + 0 + }; + let top = crate::features::split::ROW_HEIGHT + frame_layout::PANEL_GAP; + let [left, top] = layout_experiments::nc_inset_pixels(inset, leading, top, dpi(window)); + // The first rect of `NCCALCSIZE_PARAMS` is the client rect the browser answered. + let rect = lparam as *mut RECT; + let before = [(*rect).left, (*rect).top, (*rect).right, (*rect).bottom]; + let after = layout_experiments::shrink_client(before, left, top); + (*rect).left = after[0]; + (*rect).top = after[1]; + let applied = [after[0] - before[0], after[1] - before[1]]; + let changed = layout_experiments::remember_inset(window as isize, applied); + crate::trace::trace_changed( + "experiment client area", + &format!( + "experiment client area: {inset:?} window {:#x} client {before:?} to {after:?}, \ + inset {applied:?} px at {} dpi, leading {leading} DIPs, changed {changed}", + window as usize, + dpi(window) + ), + ); + // A size message can arrive while the visuals are borrowed, so they are moved every time. + offset_visuals(window, applied); + result +} + +/// Experiment: moves the root of Rivet's visuals so they keep their place in the window while the +/// client area starts `inset` pixels further in. A visual left of or above the client area shows +/// only if the window's composition target draws outside the client area. +unsafe fn offset_visuals(window: HWND, inset: [i32; 2]) { + APPBARS.with(|appbars| { + if let Ok(appbars) = appbars.try_borrow() { + if let Some(appbar) = appbars.get(&(window as isize)) { + let done = appbar.offset_root(-inset[0] as f32, -inset[1] as f32); + crate::trace::trace_changed( + "experiment visuals", + &format!( + "experiment client area: Rivet's visuals moved by {:?} px: {done:?}", + [-inset[0], -inset[1]] + ), + ); + } + } + }); } unsafe fn create_appbar(window: HWND) { @@ -3557,6 +3717,13 @@ fn reserved_width(window: HWND, bounds: frame_layout::Rect) -> Option { } let leading = layout_of(window).leading(); LAID_LEADING.with(|all| all.borrow_mut().insert(window as isize, leading)); + // Where Windows already left the appbar's column out of the client area, the browser's + // layout reserves nothing more. + if crate::features::layout_experiments::nccalcsize() + != crate::features::layout_experiments::NcInset::Off + { + return Some(0); + } Some(leading) } } @@ -4202,8 +4369,18 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> } 0 } + WM_NCCALCSIZE + if attached(window) + && crate::features::layout_experiments::nccalcsize() + != crate::features::layout_experiments::NcInset::Off => + { + shrink_client_area(window, wparam, lparam) + } WM_WINDOWPOSCHANGED if attached(window) => { let result = call_browser(window, message, wparam, lparam); + if crate::features::layout_experiments::page_view_only() { + place_panel_by_rivet(window); + } // Every browser sends this on a resize, so the second view follows it on all of them. follow_second_view(window); update_appbar(window); @@ -4292,6 +4469,7 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> crate::features::page_links::forget(window); APPBAR_STATE.with(|states| states.borrow_mut().remove(&(window as isize))); frame_layout::forget_view(window); + crate::features::layout_experiments::forget(window as isize); crate::features::widgets::forget(window); crate::side_rail::forget(window); crate::features::mini_window::forget(window); @@ -4946,6 +5124,34 @@ mod tests { assert!(colour.expect("the frame colour step").skip_when_unavailable); } + #[test] + fn fr12_page_view_only_attaches_without_the_frame_layout_hooks() { + use crate::feature::{Feature, Step}; + let features = |steps: Vec>| -> Vec { + steps + .iter() + .filter_map(|step| match step { + Step::Feature(step) => Some(step.feature), + Step::Setup(_) => None, + }) + .collect() + }; + let hooked = [ + Feature::CaptionLayout, + Feature::CaptionHeight, + Feature::TopInset, + ]; + let today = features(super::attach_steps_for(false)); + let experiment = features(super::attach_steps_for(true)); + for feature in hooked { + assert!(today.contains(&feature)); + assert!(!experiment.contains(&feature)); + } + // The frame view's functions are still found, so a view's window can be told. + assert!(experiment.contains(&Feature::FrameLayout)); + assert_eq!(today.len(), experiment.len() + hooked.len()); + } + #[test] fn test_switches_are_read_from_the_browsers_own_profile() { let profile = rivet_core::paths::TestDir::new("rivet-own-debug"); diff --git a/rivet/runtime/windows/src/hooks/page_area.rs b/rivet/runtime/windows/src/hooks/page_area.rs index fa03af8..a2e233c 100644 --- a/rivet/runtime/windows/src/hooks/page_area.rs +++ b/rivet/runtime/windows/src/hooks/page_area.rs @@ -262,9 +262,26 @@ fn patched() -> bool { original() != 0 || crate::browsers::chromium::layout::app_layout_patched() } +/// Why the browser's layout is not patched in this process, when an experiment leaves it alone and +/// Rivet places the page view itself. +pub(crate) const LEFT_ALONE: &str = "the page view only experiment leaves the browser's layout alone"; + +fn left_alone() -> Result<(), String> { + left_alone_when(crate::features::layout_experiments::page_view_only()) +} + +fn left_alone_when(page_view_only: bool) -> Result<(), String> { + if page_view_only { + Err(LEFT_ALONE.into()) + } else { + Ok(()) + } +} + /// Patches the layout of the page area once per process, for a caller that asks for any window: /// the layout the row records, or else the app window's own. pub(crate) unsafe fn install() -> Result<(), String> { + left_alone()?; relied_on(false, old_layout(), install_tabbed(), || { crate::features::omnibox::install_app_layout() }) @@ -273,6 +290,7 @@ pub(crate) unsafe fn install() -> Result<(), String> { /// Patches the layout that lays out an app window, once per process. The tabbed layout is patched /// too where the row records it, and only an old-layout build needs it. pub(crate) unsafe fn install_for_app_window() -> Result<(), String> { + left_alone()?; relied_on(true, old_layout(), install_tabbed(), || { crate::features::omnibox::install_app_layout() }) @@ -458,6 +476,17 @@ mod tests { assert_eq!(relied_on(true, true, Ok(()), || Ok(())), Ok(())); } + #[test] + fn fr12_page_view_only_never_patches_the_page_area_layout() { + assert_eq!(left_alone_when(false), Ok(())); + assert_eq!(left_alone_when(true), Err(LEFT_ALONE.to_owned())); + // The address bar then moves the page view itself, on a build with the second view. + assert_eq!( + crate::features::address_bar::offset_for(left_alone_when(true), true), + crate::features::address_bar::Offset::PageView + ); + } + #[test] fn fr10_a_view_the_build_does_not_have_is_never_looked_up() { // A layout object whose first word is a pointer a lookup would otherwise take for a view. From 91a7860f9a25eb2e26d599f6352e71972e5c755f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:33:24 +0000 Subject: [PATCH 25/29] Publish: develop 46f4b91 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/core/src/lib.rs | 2 +- .../src/features/layout_experiments.rs | 53 +++++++++++++++++++ .../windows/src/features/second_view.rs | 7 +++ rivet/runtime/windows/src/frame.rs | 8 ++- 4 files changed, 67 insertions(+), 3 deletions(-) diff --git a/rivet/core/src/lib.rs b/rivet/core/src/lib.rs index af44a63..76e2f20 100644 --- a/rivet/core/src/lib.rs +++ b/rivet/core/src/lib.rs @@ -282,7 +282,7 @@ fn plan_launch(request: &LaunchRequest, controlled: bool) -> Result { arguments.push("--headless=new".to_owned()); diff --git a/rivet/runtime/windows/src/features/layout_experiments.rs b/rivet/runtime/windows/src/features/layout_experiments.rs index b2239d8..d771a11 100644 --- a/rivet/runtime/windows/src/features/layout_experiments.rs +++ b/rivet/runtime/windows/src/features/layout_experiments.rs @@ -172,12 +172,65 @@ pub(crate) fn forget(window: isize) { .lock() .unwrap_or_else(|error| error.into_inner()) .retain(|entry| entry.0 != window); + BROWSER_WIDTH + .lock() + .unwrap_or_else(|error| error.into_inner()) + .retain(|entry| entry.0 != window); +} + +/// The width the browser lays each window out in, in its own DIPs, read from a view that spans the +/// window. The browser picks its scale itself, which can differ from the one Windows reports for a +/// window off every monitor, so this width is what turns client pixels into the browser's DIPs. +static BROWSER_WIDTH: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Records the width of a view of the window that starts at its left edge. Returns whether it +/// changed. +pub(crate) fn note_browser_width(window: isize, view: [i32; 4]) -> bool { + if view[0] != 0 || view[2] <= 0 { + return false; + } + let mut all = BROWSER_WIDTH.lock().unwrap_or_else(|error| error.into_inner()); + match all.iter_mut().find(|entry| entry.0 == window) { + Some(entry) => std::mem::replace(&mut entry.1, view[2]) != view[2], + None => { + all.push((window, view[2])); + true + } + } +} + +/// The client size in the browser's DIPs: by the width the browser laid the window out in when it +/// is known, else at `dpi`. +pub(crate) fn browser_dips(window: isize, width: i32, height: i32, dpi: u32) -> [i32; 2] { + let known = BROWSER_WIDTH + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .find(|entry| entry.0 == window) + .map(|entry| entry.1); + match known { + Some(dips) if width > 0 => [dips, (height.max(0) as i64 * dips as i64 / width as i64) as i32], + _ => client_dips(width, height, dpi), + } } #[cfg(test)] mod tests { use super::*; + #[test] + fn fr12_client_pixels_follow_the_scale_the_browser_laid_out_at() { + let window = 0x5150; + // Before the browser laid anything out, the scale Windows reports is used. + assert_eq!(browser_dips(window, 1800, 1067, 192), [900, 534]); + // A view that does not start at the left edge says nothing of the window's width. + assert!(!note_browser_width(window, [276, 0, 616, 518])); + assert!(note_browser_width(window, [0, 0, 1440, 824])); + assert_eq!(browser_dips(window, 1800, 1067, 192), [1440, 853]); + forget(window); + assert_eq!(browser_dips(window, 1800, 1067, 192), [900, 534]); + } + #[test] fn nfr3_layout_experiments_are_off_unless_switched_on() { assert_eq!(parse_nccalcsize(None, false), NcInset::Off); diff --git a/rivet/runtime/windows/src/features/second_view.rs b/rivet/runtime/windows/src/features/second_view.rs index 636bbc1..5d5f813 100644 --- a/rivet/runtime/windows/src/features/second_view.rs +++ b/rivet/runtime/windows/src/features/second_view.rs @@ -783,6 +783,13 @@ unsafe fn area_of(split: &Split) -> Option<[i32; 4]> { let container = word(split.main + offsets().0) .filter(|parent| *parent != 0) .map(|parent| bounds_of(parent)); + // The page view's parent spans the window, so its width is the browser's own. + let noted = container.is_some_and(|bounds| { + crate::features::layout_experiments::note_browser_width(split.window, bounds) + }); + if noted { + crate::frame::place_panel_by_rivet(split.window as HWND); + } crate::trace::trace_changed( "experiment page view area", &format!( diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index 88649e7..bed055d 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -3054,8 +3054,12 @@ pub(crate) unsafe fn place_panel_by_rivet(window: HWND) { } let mut client: RECT = std::mem::zeroed(); GetClientRect(window, &mut client); - let [width, height] = - crate::features::layout_experiments::client_dips(client.right, client.bottom, dpi(window)); + let [width, height] = crate::features::layout_experiments::browser_dips( + window as isize, + client.right, + client.bottom, + dpi(window), + ); if width <= 0 || height <= 0 { return; } From 93952d90a2ccc90120bf00c0f849c782a596dc4f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:33:36 +0000 Subject: [PATCH 26/29] Publish: develop cef55e9 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/core/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rivet/core/src/lib.rs b/rivet/core/src/lib.rs index 76e2f20..af44a63 100644 --- a/rivet/core/src/lib.rs +++ b/rivet/core/src/lib.rs @@ -282,7 +282,7 @@ fn plan_launch(request: &LaunchRequest, controlled: bool) -> Result { arguments.push("--headless=new".to_owned()); From 82fecfde252a5133eda6b475a745b235c489ef40 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:42:20 +0000 Subject: [PATCH 27/29] Publish: develop c1866c9 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/runtime/windows/src/frame.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index bed055d..d688cff 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -3069,10 +3069,16 @@ pub(crate) unsafe fn place_panel_by_rivet(window: HWND) { width, height, }; - let Some(reserved) = reserved_width(window, bounds) else { - return; + // Without its sizing frame the window is fullscreen, and the page takes the whole window, as the + // browser's own layout gives it then. + let panel = if !framed(window) { + bounds + } else { + let Some(reserved) = reserved_width(window, bounds) else { + return; + }; + frame_layout::rivet_panel(bounds, reserved) }; - let panel = frame_layout::rivet_panel(bounds, reserved); crate::trace::trace_changed( "experiment page view panel", &format!( From dff947734b42e0423164e3ef90b218c4ecc17ec8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:52:52 +0000 Subject: [PATCH 28/29] Publish: develop c495799 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/row_features.rs | 59 +- rivet/platform/windows/src/row_port.rs | 28 +- rivet/platform/windows/src/row_recipe.rs | 55 +- rivet/runtime/windows/rows/table.json | 168 +---- rivet/runtime/windows/src/appbar.rs | 8 - rivet/runtime/windows/src/browser/mod.rs | 2 +- .../windows/src/browsers/chromium/layout.rs | 176 ------ .../windows/src/browsers/chromium/mod.rs | 2 - .../src/browsers/chromium/old_layout.rs | 150 ----- .../windows/src/browsers/chromium/split.rs | 165 ++--- rivet/runtime/windows/src/browsers/mod.rs | 13 - rivet/runtime/windows/src/builds/brave.rs | 123 ---- rivet/runtime/windows/src/builds/chrome.rs | 189 ------ rivet/runtime/windows/src/builds/edge.rs | 42 -- rivet/runtime/windows/src/builds/mod.rs | 111 +--- .../windows/src/builds/omnibox_rows.rs | 21 - rivet/runtime/windows/src/builds/samsung.rs | 28 +- rivet/runtime/windows/src/builds/tests.rs | 122 +--- rivet/runtime/windows/src/builds/whale.rs | 20 - rivet/runtime/windows/src/chromium/view.rs | 40 -- .../windows/src/chromium/window_views.rs | 176 +----- rivet/runtime/windows/src/feature.rs | 43 +- .../windows/src/features/address_bar.rs | 220 +------ .../windows/src/features/bubble_anchor.rs | 2 +- .../runtime/windows/src/features/dev_page.rs | 1 - .../windows/src/features/frame_layout.rs | 586 +----------------- .../src/features/layout_experiments.rs | 308 --------- .../windows/src/features/mini_window.rs | 6 - rivet/runtime/windows/src/features/mod.rs | 3 +- rivet/runtime/windows/src/features/omnibox.rs | 11 - .../runtime/windows/src/features/page_view.rs | 108 ++++ .../windows/src/features/pane_infobar.rs | 158 ----- .../windows/src/features/second_view.rs | 74 +-- .../windows/src/features/side_panel.rs | 264 +------- .../windows/src/features/sidebar_page.rs | 45 -- rivet/runtime/windows/src/features/split.rs | 26 +- rivet/runtime/windows/src/frame.rs | 320 ++-------- rivet/runtime/windows/src/hooks/mod.rs | 3 - rivet/runtime/windows/src/hooks/page_area.rs | 508 --------------- rivet/runtime/windows/src/lib.rs | 2 - rivet/runtime/windows/src/row_data.rs | 13 +- rivet/runtime/windows/src/side_rail.rs | 48 +- scripts/tests/layers.baseline | 34 +- 43 files changed, 440 insertions(+), 4041 deletions(-) delete mode 100644 rivet/runtime/windows/src/browsers/chromium/layout.rs delete mode 100644 rivet/runtime/windows/src/browsers/chromium/old_layout.rs delete mode 100644 rivet/runtime/windows/src/features/layout_experiments.rs create mode 100644 rivet/runtime/windows/src/features/page_view.rs delete mode 100644 rivet/runtime/windows/src/features/pane_infobar.rs delete mode 100644 rivet/runtime/windows/src/hooks/mod.rs delete mode 100644 rivet/runtime/windows/src/hooks/page_area.rs diff --git a/rivet/platform/windows/src/row_features.rs b/rivet/platform/windows/src/row_features.rs index 273db12..ecb334f 100644 --- a/rivet/platform/windows/src/row_features.rs +++ b/rivet/platform/windows/src/row_features.rs @@ -3,7 +3,7 @@ //! A row value that could not be read from its own build must never reach a browser. When it //! belongs to a feature the runtime can do without, the row turns that feature off and clears the //! value, and the rest of the row can still ship once its checks pass. A value of a part the -//! window cannot do without (the frame and the page area layout) has no switch here, so it still +//! window cannot do without (the frame) has no switch here, so it still //! stops the row and the browser opens with Rivet's held build. //! //! The switches are the ones the runtime already obeys: a section's `supported` flag, an optional @@ -79,20 +79,6 @@ pub const ROW_FEATURES: &[RowFeature] = &[ clear: Clear::Empty, checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], }, - RowFeature { - // Fields of the browser's layout object that only the Sidebar's part of the layout reads. - // The layout reads an absent field as no view. - name: "sidebar", - paths: &[ - "side_panel.side_panel", - "side_panel.side_panel_animation", - "side_panel.contents_outline", - "side_panel.vertical_tabs", - ], - off: &[Off::Flag("side_panel.supported")], - clear: Clear::Absent, - checks: &["sidebar", "sidebar-", "fullscreen-sidebar"], - }, RowFeature { // The Sidebar's own functions and class tables. Only `features/side_panel.rs` reads them, // and only once the Sidebar's targets are all recorded. @@ -165,17 +151,12 @@ pub const ROW_FEATURES: &[RowFeature] = &[ /// Values the runtime finds in the browser's own memory by Chromium's class names and the shape of /// the view tree, so a row needs none of them. Where a row has one, the runtime only compares it /// with what it found. A value no instruction of the new build gave is left out of the row rather -/// than carried from the prior build, and does not stop the row: the browser view, the area below -/// the top row and the view of the pages are the layout's views named `BrowserView`, -/// `MainBackgroundRegionView` and `MultiContentsView`; the frame view's field is the one that holds -/// that same browser view; and a view's widget is the one the root of its view tree names. A -/// runtime from before this cannot read a row without them, so it refuses the row and opens its -/// held build instead of guessing. +/// than carried from the prior build, and does not stop the row: the frame view's field is the one +/// that holds a view named `BrowserView`, and a view's widget is the one the root of its view tree +/// names. A runtime from before this cannot read a row without them, so it refuses the row and opens +/// its held build instead of guessing. pub const REFLECTED: &[&str] = &[ "layout.frame_browser_window_offset", - "side_panel.contents_container", - "side_panel.host_view", - "side_panel.page_area", "toolbar.get_widget_slot", ]; @@ -228,15 +209,6 @@ pub const UNUSED_WHEN: &[UnusedWhen] = &[ when: When::Recorded("tabs.tab_at"), why: "the build has its own GetWebContentsAt", }, - UnusedWhen { - paths: &[ - "side_panel.layout_vtable", - "side_panel.proposed_slot", - "side_panel.proposed", - ], - when: When::NotTrue("side_panel.old_layout"), - why: "a Rivet window is an app window, laid out by the app layout class, not the tabbed one", - }, ]; /// The field a value path names: `layout.frame_ids[2]` names `layout.frame_ids`. @@ -411,8 +383,8 @@ mod tests { feature_of("omnibox.match_size").unwrap().name, "address suggestions" ); - // The frame and the page area layout have no switch: the window cannot do without them. - for core in ["layout.view_bounds_offset", "side_panel.toolbar"] { + // The frame has no switch: the window cannot do without it. + for core in ["layout.view_bounds_offset", "layout.frame_vtable"] { assert!(feature_of(core).is_none(), "{core}"); assert!(!is_reflected(core), "{core}"); } @@ -474,23 +446,6 @@ mod tests { assert_eq!(excuses(&excused, "security-chip"), None); } - #[test] - fn nfr6_the_tabbed_layout_is_not_a_value_of_a_build_without_the_old_layout() { - let build = json!({"side_panel": {"old_layout": null, "proposed": "0x13c8310"}}); - for path in [ - "side_panel.layout_vtable", - "side_panel.proposed_slot", - "side_panel.proposed", - ] { - assert!(unused(&build, path).is_some(), "{path}"); - } - assert!(unused(&json!({"side_panel": {}}), "side_panel.proposed").is_some()); - // An old-layout build lays out every window with the class its row records. - let old = json!({"side_panel": {"old_layout": true, "proposed": "0x13c8310"}}); - assert!(unused(&old, "side_panel.proposed").is_none()); - assert!(unused(&old, "side_panel.layout_vtable").is_none()); - } - #[test] fn nfr6_a_switched_off_feature_excuses_only_its_own_checks() { let row = diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 8e702c2..eefc0dd 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -473,27 +473,11 @@ fn at_path<'a>(row: &'a Value, path: &str) -> &'a Value { /// `(vtable, slot, function)`: a function the runtime replaces in a table, and so a check the new /// module can answer on its own. A function listed twice settles a folded name. const VTABLE_SLOTS: &[(&str, &str, &str)] = &[ - ( - "side_panel.layout_vtable", - "side_panel.proposed_slot", - "side_panel.proposed", - ), ( "layout.frame_vtable", "layout.on_paint_slot", "layout.on_paint", ), - ( - "layout.frame_vtable", - "layout.top_inset_slot", - "layout.top_inset", - ), - ("layout.frame_vtable", "layout.layout_slot", "layout.layout"), - ( - "layout.caption_vtable", - "layout.caption_size_slot", - "layout.caption_size", - ), ( "layout.caption_vtable", "layout.caption_paint_slot", @@ -2186,27 +2170,25 @@ mod tests { #[test] fn nfr6_a_row_without_window_offsets_is_not_blocked() { - // Edge 157's row stopped on exactly these values. The runtime finds them by class name and - // the view tree, so the new row leaves them out and nothing holds it back. + // Edge 157's row stopped on values like these. The runtime finds them by class name and the + // view tree, so the new row leaves them out and nothing holds it back. let mut prior = prior_with_features(); prior["build"]["layout"] = json!({"frame_browser_window_offset": "0x3b0"}); - prior["build"]["side_panel"] = - json!({"host_view": "0x38", "page_area": "0x0", "contents_container": "0xd8"}); prior["build"]["toolbar"]["get_widget_slot"] = json!("0xa"); let code = new_code(); let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "2.0.0.1"); assert_eq!(report.review, Vec::::new()); assert!(report.carried.is_empty(), "{:?}", report.carried); - assert_eq!(report.reflected.len(), 5, "{:?}", report.reflected); + assert_eq!(report.reflected.len(), 2, "{:?}", report.reflected); let build = &row["build"]; assert!(build["layout"].get("frame_browser_window_offset").is_none()); - assert_eq!(build["side_panel"], json!({})); assert!(build["toolbar"].get("get_widget_slot").is_none()); // No feature went off for them. assert!(!report .switched_off .iter() - .any(|line| line.contains("side_panel.") || line.contains("get_widget_slot"))); + .any(|line| line.contains("frame_browser_window_offset") + || line.contains("get_widget_slot"))); } #[test] diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index 6131917..17fda5c 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -74,13 +74,6 @@ pub const FIELDS: &[Field] = &[ constructor: "app_window.web_view_ctor", }], }, - Field { - path: "side_panel.proposed_slot", - recipes: &[Recipe::Slot { - vtable: "side_panel.layout_vtable", - function: "side_panel.proposed", - }], - }, Field { path: "layout.on_paint_slot", recipes: &[Recipe::Slot { @@ -88,27 +81,6 @@ pub const FIELDS: &[Field] = &[ function: "layout.on_paint", }], }, - Field { - path: "layout.top_inset_slot", - recipes: &[Recipe::Slot { - vtable: "layout.frame_vtable", - function: "layout.top_inset", - }], - }, - Field { - path: "layout.layout_slot", - recipes: &[Recipe::Slot { - vtable: "layout.frame_vtable", - function: "layout.layout", - }], - }, - Field { - path: "layout.caption_size_slot", - recipes: &[Recipe::Slot { - vtable: "layout.caption_vtable", - function: "layout.caption_size", - }], - }, Field { path: "layout.caption_paint_slot", recipes: &[Recipe::Slot { @@ -129,7 +101,7 @@ pub enum Outcome { Failed(String), } -/// The value at a path such as `layout.top_inset_slot`. +/// The value at a path such as `layout.on_paint_slot`. fn at_path<'a>(row: &'a Value, path: &str) -> &'a Value { path.split('.').fold(row, |value, key| &value[key]) } @@ -533,18 +505,19 @@ mod tests { let pe = PeFile::parse(&bytes).unwrap(); let mut build = json!({ "layout": { - "frame_vtable": "0x108000", "top_inset": "0x101200", "top_inset_slot": 3, - "layout": "0x101100", "layout_slot": "0x1", + "frame_vtable": "0x108000", "on_paint": "0x101200", "on_paint_slot": 3, + "caption_vtable": "0x108000", "caption_paint": "0x101100", + "caption_paint_slot": "0x1", } }); let derived = derive_row(&mut build, &pe); - assert_eq!(build["layout"]["top_inset_slot"], 2); - assert_eq!(build["layout"]["layout_slot"], "0x1"); + assert_eq!(build["layout"]["on_paint_slot"], 2); + assert_eq!(build["layout"]["caption_paint_slot"], "0x1"); assert_eq!( derived.read, vec![ - "layout.top_inset_slot: 0x3 -> 0x2", - "layout.layout_slot: 0x1" + "layout.on_paint_slot: 0x3 -> 0x2", + "layout.caption_paint_slot: 0x1" ] ); assert!(derived.failed.is_empty()); @@ -585,20 +558,20 @@ mod tests { let build = json!({ "layout": { "frame_vtable": "0x108000", "caption_vtable": "0x108100", - "layout": "0x101100", "layout_slot": "0x1", + "on_paint": "0x101100", "on_paint_slot": "0x1", } }); // No value of a row has two recipes today, so the rule is checked on a field made here. let field = Field { - path: "layout.layout_slot", + path: "layout.on_paint_slot", recipes: &[ Recipe::Slot { vtable: "layout.frame_vtable", - function: "layout.layout", + function: "layout.on_paint", }, Recipe::Slot { vtable: "layout.caption_vtable", - function: "layout.layout", + function: "layout.on_paint", }, ], }; @@ -615,11 +588,11 @@ mod tests { let build = json!({ "version": [157, 0, 8103, 38], "tabs": {"browser_in_view": "0x558", "title": "0x00b77780", "groups": true}, - "layout": {"frame_ids": [0x141, 0x142], "caption_container_offset": "0x3c0"}, + "layout": {"frame_ids": [0x141, 0x142], "view_bounds_offset": "0x1c8"}, }); assert_eq!( without_recipe(&build), - vec!["layout.caption_container_offset", "layout.frame_ids"] + vec!["layout.frame_ids", "layout.view_bounds_offset"] ); } diff --git a/rivet/runtime/windows/rows/table.json b/rivet/runtime/windows/rows/table.json index 9fb549d..e1bf5f4 100644 --- a/rivet/runtime/windows/rows/table.json +++ b/rivet/runtime/windows/rows/table.json @@ -39,9 +39,7 @@ "41574156415541545657534881ecd0000000" ], "layout": { - "browser_view_view_vtable": "0xfce91b0", "browser_window_in_view": "0x1f0", - "caption_container_offset": "0x3c8", "caption_ink_ids": [ 1644, 1645, @@ -50,8 +48,6 @@ "caption_paint": "0x2162030", "caption_paint_prologue": "e90b000000cccccc", "caption_paint_slot": "0x72", - "caption_size": "0x2f78d50", - "caption_size_slot": "0x4a", "caption_vtable": "0xfd6f810", "corner_paint": "0xa27b3e0", "corner_paint_prologue": "4157415641554154", @@ -69,29 +65,10 @@ "frame_vtable": "0xfce1070", "get_color_provider": "0x47a0870", "get_color_provider_prologue": "56574883ec78", - "layout": "0x198b250", - "layout_immediately": "0x49713c0", - "layout_immediately_prologue": "415741564155415456575553", - "layout_prologue": "415656575553", - "layout_slot": "0x17", "on_paint": "0x14ebbc0", "on_paint_prologue": "4157415641554154", "on_paint_slot": "0x59", "provider_verified": true, - "set_bounds_rect": "0x49703b0", - "set_bounds_rect_prologue": "4157415641554154", - "set_layer": "0xf86250", - "set_layer_prologue": "56574883ec28", - "set_masks": "0x2fa9080", - "set_masks_prologue": "488b8970010000", - "set_opaque": "0xba1c00", - "set_opaque_prologue": "564883ec20", - "set_radius": "0x1c46820", - "set_radius_prologue": "5657534883ec30", - "stack_at_top": "0xaa90920", - "stack_at_top_prologue": "415741565657", - "top_inset": "0x198b7f0", - "top_inset_slot": "0x7f", "view_bounds_offset": "0x1c8" }, "module": "chrome.dll", @@ -148,9 +125,6 @@ }, "omnibox": { "allocate": "0x59fc230", - "app_layout_proposed": "0xa2752b0", - "app_layout_slot": "0x10", - "app_layout_vtable": "0xfc1d358", "browser_context": "0x55756e0", "classifier_for_profile": "0x2f82bf0", "classify": "0x63cd10", @@ -288,8 +262,6 @@ "browser_offset": "0x560", "browser_view_view_vtable": "0xfce91b0", "color_source": "0x98", - "contents_container": "0xb8", - "contents_outline": "0x58", "coordinator_browser": null, "coordinator_vtable": "0xfcc6688", "entry_count": 24, @@ -308,14 +280,6 @@ "get_color_provider": "0x1f3b9f0", "get_color_provider_prologue": "488b8998000000488b01488b4008", "hidden_entries": [], - "host_view": "0x38", - "layout_immediately": "0x49713c0", - "layout_immediately_prologue": "415741564155415456575553", - "layout_vtable": "0xfc1d598", - "old_layout": null, - "page_area": "0x50", - "proposed": "0x14131a0", - "proposed_slot": "0x10", "registry_end": null, "registry_entries": null, "registry_from": "0x2f0f660", @@ -323,15 +287,11 @@ "registry_in_coordinator": null, "show": "0x9705f80", "show_prologue": "41565657534883ec58", - "side_panel": "0xc0", - "side_panel_animation": "0xc8", "side_panel_vtable": "0xfcd4ef0", "source_in_widget": "0x48", "supported": true, "toggle": "0x970e610", - "toggle_prologue": "415741565657534883ec60", - "toolbar": "0x60", - "vertical_tabs": "0x80" + "toggle_prologue": "415741565657534883ec60" }, "split": { "active_member": "0x3c8", @@ -652,9 +612,7 @@ "41574156415541545657534881ecd0000000" ], "layout": { - "browser_view_view_vtable": "0xfce91b0", "browser_window_in_view": "0x1f0", - "caption_container_offset": "0x3c8", "caption_ink_ids": [ 1644, 1645, @@ -663,8 +621,6 @@ "caption_paint": "0x2161ff0", "caption_paint_prologue": "e90b000000cccccc", "caption_paint_slot": "0x72", - "caption_size": "0x2f78c50", - "caption_size_slot": "0x4a", "caption_vtable": "0xfd6f810", "corner_paint": "0xa27b230", "corner_paint_prologue": "4157415641554154", @@ -682,29 +638,10 @@ "frame_vtable": "0xfce1070", "get_color_provider": "0x47a0720", "get_color_provider_prologue": "56574883ec78", - "layout": "0x198b260", - "layout_immediately": "0x4971270", - "layout_immediately_prologue": "415741564155415456575553", - "layout_prologue": "415656575553", - "layout_slot": "0x17", "on_paint": "0x14ebbc0", "on_paint_prologue": "4157415641554154", "on_paint_slot": "0x59", "provider_verified": true, - "set_bounds_rect": "0x4970260", - "set_bounds_rect_prologue": "4157415641554154", - "set_layer": "0xf86230", - "set_layer_prologue": "56574883ec28", - "set_masks": "0x2fa8f80", - "set_masks_prologue": "488b8970010000", - "set_opaque": "0xba1c00", - "set_opaque_prologue": "564883ec20", - "set_radius": "0x1c46820", - "set_radius_prologue": "5657534883ec30", - "stack_at_top": "0xaa90770", - "stack_at_top_prologue": "415741565657", - "top_inset": "0x198b800", - "top_inset_slot": "0x7f", "view_bounds_offset": "0x1c8" }, "module": "chrome.dll", @@ -761,9 +698,6 @@ }, "omnibox": { "allocate": "0x59fc0f0", - "app_layout_proposed": "0xa275100", - "app_layout_slot": "0x10", - "app_layout_vtable": "0xfc1d358", "browser_context": "0x55755b0", "classifier_for_profile": "0x2f82af0", "classify": "0x63cd20", @@ -897,8 +831,6 @@ "browser_offset": "0x560", "browser_view_view_vtable": "0xfce91b0", "color_source": "0x98", - "contents_container": "0xb8", - "contents_outline": "0x58", "coordinator_browser": null, "coordinator_vtable": "0xfcc6688", "entry_count": 24, @@ -917,14 +849,6 @@ "get_color_provider": "0x1f3b9d0", "get_color_provider_prologue": "488b8998000000488b01488b4008", "hidden_entries": [], - "host_view": "0x38", - "layout_immediately": "0x4971270", - "layout_immediately_prologue": "415741564155415456575553", - "layout_vtable": "0xfc1d598", - "old_layout": null, - "page_area": "0x50", - "proposed": "0x1413190", - "proposed_slot": "0x10", "registry_end": null, "registry_entries": null, "registry_from": "0x2f0f560", @@ -932,15 +856,11 @@ "registry_in_coordinator": null, "show": "0x9705de0", "show_prologue": "41565657534883ec58", - "side_panel": "0xc0", - "side_panel_animation": "0xc8", "side_panel_vtable": "0xfcd4ef0", "source_in_widget": "0x48", "supported": true, "toggle": "0x970e470", - "toggle_prologue": "415741565657534883ec60", - "toolbar": "0x60", - "vertical_tabs": "0x80" + "toggle_prologue": "415741565657534883ec60" }, "split": { "active_member": "0x3c8", @@ -1261,9 +1181,7 @@ "41574156415541545657534881ecd0000000" ], "layout": { - "browser_view_view_vtable": "0x1016e590", "browser_window_in_view": "0x1f0", - "caption_container_offset": "0x3c0", "caption_ink_ids": [ 1651, 1652, @@ -1272,8 +1190,6 @@ "caption_paint": "0x1e38180", "caption_paint_prologue": "e90b000000cccccc", "caption_paint_slot": "0x71", - "caption_size": "0x3209710", - "caption_size_slot": "0x4a", "caption_vtable": "0x101e13f0", "corner_paint": "0xab94640", "corner_paint_prologue": "4157415641554154", @@ -1291,29 +1207,10 @@ "frame_vtable": "0x10174650", "get_color_provider": "0x4f8f620", "get_color_provider_prologue": "56574883ec78", - "layout": "0x1a63900", - "layout_immediately": "0x48c8d60", - "layout_immediately_prologue": "415741564155415456575553", - "layout_prologue": "415656575553", - "layout_slot": "0x17", "on_paint": "0x1617e40", "on_paint_prologue": "4157415641554154", "on_paint_slot": "0x59", "provider_verified": true, - "set_bounds_rect": "0x48c8050", - "set_bounds_rect_prologue": "4157415641554154", - "set_layer": "0x10066a0", - "set_layer_prologue": "56574883ec28", - "set_masks": "0x321d1f0", - "set_masks_prologue": "488b8970010000", - "set_opaque": "0x7e9970", - "set_opaque_prologue": "564883ec20", - "set_radius": "0x321d200", - "set_radius_prologue": "5657534883ec30", - "stack_at_top": "0xaf47650", - "stack_at_top_prologue": "415741565657", - "top_inset": "0xaad20d0", - "top_inset_slot": "0x7e", "view_bounds_offset": "0x1c8" }, "module": "chrome.dll", @@ -1370,9 +1267,6 @@ }, "omnibox": { "allocate": "0x5e75d10", - "app_layout_proposed": "0xab8f4c0", - "app_layout_slot": "0x10", - "app_layout_vtable": "0x100ad928", "browser_context": "0x585ff30", "classifier_for_profile": "0x28bb930", "classify": "0x532cd0", @@ -1506,8 +1400,6 @@ "browser_offset": "0x558", "browser_view_view_vtable": "0x1016e590", "color_source": "0x98", - "contents_container": "0xb8", - "contents_outline": "0x58", "coordinator_browser": null, "coordinator_vtable": "0x10134880", "entry_count": 23, @@ -1526,14 +1418,6 @@ "get_color_provider": "0x1e7f400", "get_color_provider_prologue": "488b8998000000488b01488b4008", "hidden_entries": [], - "host_view": "0x38", - "layout_immediately": "0x48c8d60", - "layout_immediately_prologue": "415741564155415456575553", - "layout_vtable": "0x100adb68", - "old_layout": null, - "page_area": "0x50", - "proposed": "0x12c36d0", - "proposed_slot": "0x10", "registry_end": null, "registry_entries": null, "registry_from": "0x3173f60", @@ -1541,15 +1425,11 @@ "registry_in_coordinator": null, "show": "0x9b4b110", "show_prologue": "41565657534883ec58", - "side_panel": "0xc0", - "side_panel_animation": "0xc8", "side_panel_vtable": "0x101407b0", "source_in_widget": "0x48", "supported": true, "toggle": "0x9b539f0", - "toggle_prologue": "415741565657534883ec60", - "toolbar": "0x60", - "vertical_tabs": "0x80" + "toggle_prologue": "415741565657534883ec60" }, "split": { "active_member": "0x3c0", @@ -1865,9 +1745,7 @@ }, "browser": "Microsoft Edge", "layout": { - "browser_view_view_vtable": "0x11940340", "browser_window_in_view": "0x1f8", - "caption_container_offset": "0x440", "caption_ink_ids": [ 1644, 1645, @@ -1876,8 +1754,6 @@ "caption_paint": "0x2d4ec50", "caption_paint_prologue": "e901000000cc4157", "caption_paint_slot": "0x7f", - "caption_size": "0xa7f61e0", - "caption_size_slot": "0x56", "caption_vtable": "0x118faca0", "corner_paint": "0xa6734d0", "corner_paint_prologue": "4157415641554154", @@ -1896,29 +1772,10 @@ "frame_vtable": "0x1185ff40", "get_color_provider": "0x1030e30", "get_color_provider_prologue": "4883ec28488b", - "layout": "0x29655e0", - "layout_immediately": "0x1072f40", - "layout_immediately_prologue": "565755534883ec584889ce48", - "layout_prologue": "564883ec4048", - "layout_slot": "0x18", "on_paint": "0x2b714d0", "on_paint_prologue": "56574883ec384889", "on_paint_slot": "0x65", "provider_verified": true, - "set_bounds_rect": "0x1050418", - "set_bounds_rect_prologue": "4157415641554154", - "set_layer": "0x279f578", - "set_layer_prologue": "56574883ec28", - "set_masks": "0x309f47c", - "set_masks_prologue": "488b8970010000", - "set_opaque": "0x1068d5e", - "set_opaque_prologue": "564883ec20", - "set_radius": "0x2ddb43e", - "set_radius_prologue": "5657534883ec30", - "stack_at_top": "0xb41dd9e", - "stack_at_top_prologue": "415656575348", - "top_inset": "0x3402f60", - "top_inset_slot": "0xa4", "view_bounds_offset": "0x1c8" }, "module": "msedge.dll", @@ -1975,9 +1832,6 @@ }, "omnibox": { "allocate": "0x370aec0", - "app_layout_proposed": "0xa660c30", - "app_layout_slot": "0x10", - "app_layout_vtable": "0x11736770", "browser_context": "0x1192390", "classifier_for_profile": "0x2ca1bda", "classify": "0x29684b6", @@ -2093,8 +1947,6 @@ "browser_offset": "0x618", "browser_view_view_vtable": "0x11940340", "color_source": "0x98", - "contents_container": "0xd8", - "contents_outline": "0x7fff0000", "coordinator_vtable": "0x117a07a0", "entry_count": 25, "entry_id_to_string": "0x29aa2c8", @@ -2112,27 +1964,15 @@ "hidden_entries": [ 0 ], - "host_view": "0x38", - "layout_immediately": "0x1072f40", - "layout_immediately_prologue": "565755534883ec584889ce488b05eeb01813", - "layout_vtable": "0x7fff0000", - "old_layout": true, - "page_area": "0x0", - "proposed": "0x28fbbb0", - "proposed_slot": "0x4", "registry_from": "0x2ae9fc2", "registry_from_prologue": "4881c1b0000000", "show": "0x940bc60", "show_prologue": "41565657534883ec584489cb", - "side_panel": "0xb8", - "side_panel_animation": "0x7fff0000", "side_panel_vtable": "0x11815ce0", "source_in_widget": "0x48", "supported": false, "toggle": "0x935b830", - "toggle_prologue": "415741565657534883ec604489c3", - "toolbar": "0x7fff0000", - "vertical_tabs": "0x7fff0000" + "toggle_prologue": "415741565657534883ec604489c3" }, "split": { "active_member": "0x420", diff --git a/rivet/runtime/windows/src/appbar.rs b/rivet/runtime/windows/src/appbar.rs index 4b2ad8e..961bf07 100644 --- a/rivet/runtime/windows/src/appbar.rs +++ b/rivet/runtime/windows/src/appbar.rs @@ -600,14 +600,6 @@ impl Appbar { } } - /// Experiment: moves every Rivet visual of the window by `x` and `y` physical pixels, so they keep - /// their place in the window while the client area starts further in. - pub(crate) unsafe fn offset_root(&self, x: f32, y: f32) -> Result<()> { - self.root.SetOffsetX2(x)?; - self.root.SetOffsetY2(y)?; - self.device.Commit() - } - fn scene(&self) -> Scene<'_> { Scene { tabs: &self.tabs, diff --git a/rivet/runtime/windows/src/browser/mod.rs b/rivet/runtime/windows/src/browser/mod.rs index 355e20b..8f08553 100644 --- a/rivet/runtime/windows/src/browser/mod.rs +++ b/rivet/runtime/windows/src/browser/mod.rs @@ -23,7 +23,7 @@ //! | E. New, close, select and restore a tab | tabs, control, tab_list | command ids and DevTools | //! | F. Tab order and groups | tabs, tab_list | build values, reflection to read | //! | G. Split view and the second page view | split, split_grid, second_view | build values, reflection for bounds | -//! | H. Infobars per pane | pane_infobar | reflection | +//! | H. Infobars per pane | none: the browser's infobar stays with the page view | reflection | //! | I. Mini window out and back | mini_window | command id out, build values back | //! | J. App window without a tab strip | app_window | build values | //! | K. Address suggestions | omnibox | build values | diff --git a/rivet/runtime/windows/src/browsers/chromium/layout.rs b/rivet/runtime/windows/src/browsers/chromium/layout.rs deleted file mode 100644 index b45cae6..0000000 --- a/rivet/runtime/windows/src/browsers/chromium/layout.rs +++ /dev/null @@ -1,176 +0,0 @@ -//! Chrome, Brave and the browsers that follow them ask `BrowserViewTabbedLayoutImpl` for a map of -//! view to bounds and then apply it. The map is the place to change where the page goes: a view's -//! entry is edited before the browser applies it, so nothing is laid out twice. -use std::ffi::c_void; - -use crate::chromium::image; -use crate::chromium::memory::readable; -use crate::features::frame_layout; -use crate::hooks::page_area::{self, LayoutBounds}; - -type ProposedLayout = - unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void) -> *mut c_void; - -/// The bounds Chrome's layout gave one view, from the layout map's red-black tree. The map keeps -/// its root at +0x20, nodes hold left at +0, right at +8, the view at +0x20 and the bounds as -/// four ints at +0x28. -unsafe fn bounds_of(map: *const c_void, view: usize) -> Option<*mut [i32; 4]> { - let mut node = *(map.cast::().add(0x20) as *const usize); - while readable(node, 0x38) { - let key = *((node + 0x20) as *const usize); - if key == view { - return Some((node + 0x28) as *mut [i32; 4]); - } - node = *((node + if view < key { 0 } else { 8 }) as *const usize); - } - None -} - -/// The map one run of the browser's layout produced. -struct Map { - out: *mut c_void, -} - -impl LayoutBounds for Map { - unsafe fn of(&mut self, view: usize) -> Option<*mut [i32; 4]> { - bounds_of(self.out, view) - } - - unsafe fn dump(&self, this: *const c_void, trace: &dyn Fn(&str)) { - dump_node( - this, - *(self.out.cast::().add(0x20) as *const usize), - 0, - trace, - ); - } - - unsafe fn views(&self) -> Vec { - let mut found = Vec::new(); - let mut stack = vec![(*(self.out.cast::().add(0x20) as *const usize), 0usize)]; - while let Some((node, depth)) = stack.pop() { - if depth > 40 || found.len() > 256 || !readable(node, 0x38) { - continue; - } - found.push(*((node + 0x20) as *const usize)); - stack.push((*(node as *const usize), depth + 1)); - stack.push((*((node + 8) as *const usize), depth + 1)); - } - found - } -} - -/// Traces every view the layout placed, with the layout field that holds it. -unsafe fn dump_node(this: *const c_void, node: usize, depth: usize, trace: &dyn Fn(&str)) { - if depth > 40 || !readable(node, 0x38) { - return; - } - dump_node(this, *(node as *const usize), depth + 1, trace); - let view = *((node + 0x20) as *const usize); - let field = (0..0x600usize) - .step_by(8) - .find(|offset| *(this.cast::().add(*offset) as *const usize) == view); - let bounds = *((node + 0x28) as *const [i32; 4]); - let flags = *((node + 0x38) as *const u16); - trace(&format!( - "layout view {view:x} vt {:x} field {field:x?} bounds {bounds:?} flags {flags:#x}", - (*(view as *const usize)).wrapping_sub(image::recorded().map_or(0, |image| image.base)) - )); - dump_node(this, *((node + 8) as *const usize), depth + 1, trace); -} - -/// Takes the place of `CalculateProposedLayout`. -pub(crate) unsafe extern "system" fn proposed_layout( - this: *mut c_void, - out: *mut c_void, - params: *const c_void, -) -> *mut c_void { - let original: ProposedLayout = std::mem::transmute(page_area::original()); - let result = original(this, out, params); - // The layout keeps the view it lays out in `BrowserViewLayoutViews::browser_view`, found by - // the class name of the view it holds. - let Some(host_field) = crate::chromium::window_views::host_field(this as usize) else { - return result; - }; - let host = *(this.cast::().add(host_field) as *const usize); - crate::trace::trace_changed( - "layout hook", - &format!( - "layout hook: host {host:x} window {}", - frame_layout::hwnd_of_view(host as *const c_void).is_some() - ), - ); - if let Some(window) = frame_layout::hwnd_of_view(host as *const c_void) { - page_area::run(this, host, window, &mut Map { out }); - } - result -} - -static APP_ORIGINAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// Whether the app window's layout is patched in this process. -pub(crate) fn app_layout_patched() -> bool { - APP_ORIGINAL.load(std::sync::atomic::Ordering::Acquire) != 0 -} - -/// Takes the place of `BrowserViewAppLayoutImpl::CalculateProposedLayout`, the layout of an app -/// window, which keeps its views where the tabbed layout keeps them. -unsafe extern "system" fn app_proposed_layout( - this: *mut c_void, - out: *mut c_void, - params: *const c_void, -) -> *mut c_void { - let original: ProposedLayout = - std::mem::transmute(APP_ORIGINAL.load(std::sync::atomic::Ordering::Acquire)); - let result = original(this, out, params); - // The layout keeps the view it lays out in `BrowserViewLayoutViews::browser_view`, found by - // the class name of the view it holds. - let Some(host_field) = crate::chromium::window_views::host_field(this as usize) else { - return result; - }; - let host = *(this.cast::().add(host_field) as *const usize); - crate::trace::trace_changed( - "layout hook", - &format!( - "layout hook: host {host:x} window {}", - frame_layout::hwnd_of_view(host as *const c_void).is_some() - ), - ); - if let Some(window) = frame_layout::hwnd_of_view(host as *const c_void) { - page_area::run(this, host, window, &mut Map { out }); - } - result -} - -/// Patches the app window's layout once: slot `slot` of the vtable at `vtable` must point at -/// `proposed`, or nothing is changed. -pub(crate) unsafe fn install_app_layout( - vtable: usize, - slot: usize, - proposed: usize, -) -> Result<(), String> { - use std::sync::atomic::Ordering; - if APP_ORIGINAL.load(Ordering::Acquire) != 0 { - return Ok(()); - } - let image = image::recorded().ok_or("this browser build is not recorded")?; - let slot_rva = vtable + slot * 8; - if !image.points_to(slot_rva, proposed) { - return Err("the app window's layout is not where the record says".into()); - } - let at = (image.base + slot_rva) as *mut usize; - let mut previous: windows_sys::Win32::System::Memory::PAGE_PROTECTION_FLAGS = 0; - if windows_sys::Win32::System::Memory::VirtualProtect( - at.cast(), - 8, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - &mut previous, - ) == 0 - { - return Err("could not unprotect the app window's layout".into()); - } - APP_ORIGINAL.store(at.read(), Ordering::Release); - at.write(app_proposed_layout as *const () as usize); - windows_sys::Win32::System::Memory::VirtualProtect(at.cast(), 8, previous, &mut previous); - Ok(()) -} diff --git a/rivet/runtime/windows/src/browsers/chromium/mod.rs b/rivet/runtime/windows/src/browsers/chromium/mod.rs index 597092f..7582d52 100644 --- a/rivet/runtime/windows/src/browsers/chromium/mod.rs +++ b/rivet/runtime/windows/src/browsers/chromium/mod.rs @@ -1,4 +1,2 @@ pub(crate) mod commands; -pub(crate) mod layout; -pub(crate) mod old_layout; pub(crate) mod split; diff --git a/rivet/runtime/windows/src/browsers/chromium/old_layout.rs b/rivet/runtime/windows/src/browsers/chromium/old_layout.rs deleted file mode 100644 index 8342e6f..0000000 --- a/rivet/runtime/windows/src/browsers/chromium/old_layout.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Some builds lay their browser view out with Chromium's older layout manager. That one sets each -//! view's bounds as it goes and keeps no map of them, so Rivet lets it finish and then moves the views it -//! changed with `View::SetBoundsRect`, as the browser itself would. -use std::ffi::c_void; - -use crate::chromium::image; -use crate::chromium::memory::readable; -use crate::features::frame_layout; -use crate::hooks::page_area::{self, LayoutBounds}; - -type Layout = unsafe extern "system" fn(*mut c_void, *mut c_void); -type SetBoundsRect = unsafe extern "system" fn(*mut c_void, *const [i32; 4]); - -/// A view's bounds as the browser left them, and as the steps of the page area want them. -struct Edit { - view: usize, - before: [i32; 4], - wanted: [i32; 4], -} - -/// The views one run of the layout touched. The boxes keep the bounds where a step's pointer to -/// them stays valid while more views are added. -#[derive(Default)] -#[allow( - clippy::vec_box, - reason = "each edit must keep its address while more are added" -)] -struct Views { - edits: Vec>, -} - -impl Views { - /// The views a step moved. A view left as the browser had it is not set again. - fn changed(&self) -> impl Iterator { - self.edits - .iter() - .map(|edit| &**edit) - .filter(|edit| edit.wanted != edit.before) - } -} - -impl LayoutBounds for Views { - unsafe fn of(&mut self, view: usize) -> Option<*mut [i32; 4]> { - let at = view.wrapping_add(crate::builds::get().layout.view_bounds_offset); - if view == 0 || !readable(at, 16) { - return None; - } - if let Some(edit) = self.edits.iter_mut().find(|edit| edit.view == view) { - return Some(&mut edit.wanted); - } - let bounds = *(at as *const [i32; 4]); - self.edits.push(Box::new(Edit { - view, - before: bounds, - wanted: bounds, - })); - self.edits - .last_mut() - .map(|edit| &mut edit.wanted as *mut [i32; 4]) - } - - unsafe fn commit(&mut self) { - let Some(image) = image::recorded() else { - return; - }; - let set: SetBoundsRect = - std::mem::transmute(image.base + crate::builds::get().layout.set_bounds_rect); - for edit in self.changed() { - set(edit.view as *mut c_void, &edit.wanted); - } - } - - unsafe fn dump(&self, this: *const c_void, trace: &dyn Fn(&str)) { - let base = image::recorded().map_or(0, |image| image.base); - let size = image::recorded().map_or(0, |image| image.size); - let offset = crate::builds::get().layout.view_bounds_offset; - for field in (0x30..0x300usize).step_by(8) { - let view = *(this.cast::().add(field) as *const usize); - if !readable(view, offset + 16) { - continue; - } - let vtable = *(view as *const usize); - if vtable < base || vtable >= base + size { - continue; - } - let bounds = *((view + offset) as *const [i32; 4]); - let parent = *((view + crate::chromium::view::View::PARENT) as *const usize); - trace(&format!( - "layout view {view:x} vt {:x} field {field:#x} bounds {bounds:?} parent {parent:x}", - vtable - base - )); - } - } -} - -/// Takes the place of `BrowserViewLayoutImplOld::Layout`. -pub(crate) unsafe extern "system" fn old_layout(this: *mut c_void, host: *mut c_void) { - let original: Layout = std::mem::transmute(page_area::original()); - original(this, host); - if let Some(window) = frame_layout::hwnd_of_view(host) { - page_area::run(this, host as usize, window, &mut Views::default()); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A view in plain memory with its bounds where the row says views keep them. - fn view(bounds: [i32; 4]) -> Vec { - let mut memory = vec![0u8; 0x400]; - let at = crate::builds::get().layout.view_bounds_offset; - for (index, value) in bounds.into_iter().enumerate() { - memory[at + index * 4..at + index * 4 + 4].copy_from_slice(&value.to_le_bytes()); - } - memory - } - - #[test] - fn fr10_old_layout_hands_a_step_the_views_own_bounds_and_remembers_what_it_changed() { - let (page, panel) = (view([0, 44, 1164, 793]), view([0, 0, 0, 0])); - let (page_at, panel_at) = (page.as_ptr() as usize, panel.as_ptr() as usize); - let mut views = Views::default(); - unsafe { - let bounds = views.of(page_at).expect("a readable view has bounds"); - assert_eq!(*bounds, [0, 44, 1164, 793]); - (*bounds)[2] -= 40; - // The same view gives the same bounds again, with the step's change in them. - assert_eq!(*views.of(page_at).unwrap(), [0, 44, 1124, 793]); - // A view that is only read is not set again. - assert_eq!(*views.of(panel_at).unwrap(), [0, 0, 0, 0]); - assert_eq!(views.edits.len(), 2); - } - let moved: Vec<_> = views - .changed() - .map(|edit| (edit.view, edit.wanted)) - .collect(); - assert_eq!(moved, [(page_at, [0, 44, 1124, 793])]); - } - - #[test] - fn fr10_old_layout_has_no_bounds_for_a_view_it_does_not_have() { - let mut views = Views::default(); - unsafe { - assert!(views.of(0).is_none(), "an empty field of the layout object"); - assert!(views.of(0x10).is_none(), "an address that is not mapped"); - } - assert!(views.edits.is_empty()); - } -} diff --git a/rivet/runtime/windows/src/browsers/chromium/split.rs b/rivet/runtime/windows/src/browsers/chromium/split.rs index 41c042f..166683f 100644 --- a/rivet/runtime/windows/src/browsers/chromium/split.rs +++ b/rivet/runtime/windows/src/browsers/chromium/split.rs @@ -5,8 +5,7 @@ use crate::builds::Build; use crate::feature::{available_here, Needs}; use crate::features::frame_layout::Rect; use crate::features::split::{ - caption_over, client_right, fill_area, in_a_line, row_buttons, row_top, Pane, RowButton, - RELAYOUT_MESSAGE, ROW_HEIGHT, + caption_over, client_right, in_a_line, row_top, Pane, RELAYOUT_MESSAGE, ROW_HEIGHT, }; use crate::targets::Target; use std::ffi::c_void; @@ -77,20 +76,6 @@ pub(crate) fn needs(build: &Build) -> Needs { ) } -/// The part of the page area layout that belongs to split view: the pages of a split fill the area -/// the Sidebar left, and the toolbar follows the active page. -pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { - let row = &crate::builds::get().side_panel; - if let (Some(toolbar), Some(contents)) = (area.bounds(row.toolbar), area.contents()) { - if area.rail == 0 && active_is_split(area.window) { - if let Some(page) = area.page() { - fill_area(&mut *contents, &*page); - } - } - fit_toolbar(area.window, &mut *toolbar, &*contents); - } -} - /// Whether the loaded build's row has split view. fn checked() -> bool { static CHECKED: OnceLock = OnceLock::new(); @@ -487,7 +472,7 @@ unsafe extern "system" fn calculate_layout( } // A tab dragged onto a single page needs the page area before any split exists. if let Some(window) = crate::features::frame_layout::hwnd_of_view(view) { - crate::hooks::page_area::remember_own_area(window, view as usize); + remember_own_area(window, view as usize); } return result; } @@ -538,7 +523,7 @@ unsafe extern "system" fn calculate_layout( request_relayout(view as usize); } if let Some(window) = crate::features::frame_layout::hwnd_of_view(view) { - crate::hooks::page_area::remember_own_area(window, view as usize); + remember_own_area(window, view as usize); } splits.push(( widget, @@ -695,24 +680,49 @@ unsafe fn request_relayout(view: usize) { windows_sys::Win32::UI::WindowsAndMessaging::PostMessageW(window as _, message, 0, 0); } -/// The bounds of the pages' area as the browser's last layout left them, by window. The area's -/// vertical extent is `page_geometry`'s, and its horizontal one is here because the area starts -/// after the appbar. -static CONTENTS: Mutex> = Mutex::new(Vec::new()); +/// The page area of each window as the split view's own bounds in the window, as left, top, right +/// and bottom, from the last layout of the split view. +static OWN_AREAS: Mutex> = Mutex::new(Vec::new()); + +/// The position of `view` in its window, summing the bounds of the view and its ancestors. +unsafe fn window_position(view: usize) -> [i32; 2] { + let offset = crate::builds::get().layout.view_bounds_offset; + let Some(parent) = crate::chromium::view::View::parent_offset(offset) else { + return [0, 0]; + }; + let (mut x, mut y, mut at) = (0, 0, view); + for _ in 0..16 { + if at == 0 { + break; + } + let bounds = *((at + offset) as *const [i32; 4]); + x += bounds[0]; + y += bounds[1]; + at = *((at + parent) as *const usize); + } + [x, y] +} + +/// Keeps the split view's own bounds in the window as the window's page area. +unsafe fn remember_own_area(window: HWND, view: usize) { + let [x, y] = window_position(view); + let bounds = *((view + crate::builds::get().layout.view_bounds_offset) as *const [i32; 4]); + let area = [x, y, x + bounds[2], y + bounds[3]]; + let mut all = OWN_AREAS.lock().unwrap_or_else(|error| error.into_inner()); + match all.iter_mut().find(|(key, _)| *key == window as isize) { + Some(entry) => entry.1 = area, + None => all.push((window as isize, area)), + } +} /// The page area of a window as left, top, right and bottom in device-independent pixels. pub unsafe fn page_area(window: HWND) -> Option<[i32; 4]> { - let Some(geometry) = crate::hooks::page_area::page_geometry(window) else { - return crate::hooks::page_area::own_area(window); - }; - let contents = CONTENTS + OWN_AREAS .lock() .unwrap_or_else(|error| error.into_inner()) .iter() .find(|(key, _)| *key == window as isize) - .map(|(_, bounds)| *bounds)?; - let top = geometry.top - crate::hooks::page_area::area_top(window)? + contents[1]; - Some([contents[0], top, contents[0] + contents[2], geometry.bottom]) + .map(|(_, area)| *area) } /// The tabs of the split the active tab is in, in strip order, which is the order of its pages. @@ -739,17 +749,10 @@ unsafe fn split_tabs(window: HWND) -> Vec { } /// The pages of the window's split, or none when the active tab is not in one. pub unsafe fn panes(window: HWND) -> Vec { - let (area, view_top) = match ( - page_area(window), - crate::hooks::page_area::page_geometry(window) - .zip(crate::hooks::page_area::area_top(window)), - ) { - (Some(area), Some((geometry, top))) => (area, geometry.top - top), - _ => match crate::hooks::page_area::own_area(window) { - Some(area) => (area, area[1] - ROW_HEIGHT), - None => return Vec::new(), - }, + let Some(area) = page_area(window) else { + return Vec::new(); }; + let view_top = area[1] - ROW_HEIGHT; let tabs = split_tabs(window); if tabs.len() < 2 { return Vec::new(); @@ -790,77 +793,6 @@ pub unsafe fn panes(window: HWND) -> Vec { .collect() } -/// Narrows the browser's top row to the address of the focused page of a split, so the browser's -/// own address bar, with its completion and editing, sits where that page's address is. The rest -/// of every row is drawn by Rivet. `contents` are the bounds of the pages in the same coordinates. -pub unsafe fn fit_toolbar(window: HWND, toolbar: &mut [i32; 4], contents: &[i32; 4]) { - { - let mut all = CONTENTS.lock().unwrap_or_else(|error| error.into_inner()); - match all.iter_mut().find(|(key, _)| *key == window as isize) { - Some(entry) => entry.1 = *contents, - None => all.push((window as isize, *contents)), - } - } - let leave = || { - ADDRESS_ONLY - .lock() - .unwrap_or_else(|error| error.into_inner()) - .retain(|(key, _)| *key != window as isize); - }; - let splits = SPLITS.lock().unwrap_or_else(|error| error.into_inner()); - let Some((_, split)) = splits.iter().find(|(_, split)| { - crate::features::frame_layout::hwnd_of_view(split.view as *const c_void) - .is_some_and(|found| found as isize == window as isize) - }) else { - return leave(); - }; - if split.rects.len() < 2 || !in_a_line(&split.rects) || !active_is_split(window) { - return leave(); - } - let active = (*((split.view + bv().active_member) as *const i32)).max(0) as usize; - let Some(pane) = split.rects.get(active) else { - return leave(); - }; - let window_right = client_right(window); - let on_top = pane.y == split.rects[0].y; - let caption = if on_top { - caption_over(window_right, contents[0] + pane.x + pane.width) - } else { - 0.0 - }; - let buttons = row_buttons(pane.width as f32, active == 0, caption); - // The browser clips its top row to the strip above the pages, so only a page whose row is that - // strip can show the browser's address bar. The row of a lower page draws its address itself. - let address = buttons - .iter() - .find(|button| button.0 == RowButton::Address) - .filter(|_| on_top); - let place = address_in_row( - toolbar[0], - contents[0] + pane.x, - address.map(|(_, x, width)| (*x, *width)), - ); - let mut all = ADDRESS_ONLY - .lock() - .unwrap_or_else(|error| error.into_inner()); - match all.iter_mut().find(|(key, _)| *key == window as isize) { - Some(entry) => entry.1 = place, - None => all.push((window as isize, place)), - } -} - -/// Where the address goes inside the browser's top row in a split, as its left edge and width. The -/// row itself keeps its full width: Rivet's rows cover it except at the focused page's address and -/// behind the caption buttons, which are the browser's, and without it the browser's own frame colour -/// shows behind those buttons. -fn address_in_row(row_left: i32, page_left: i32, address: Option<(f32, f32)>) -> (i32, i32) { - match address { - Some((x, width)) => (page_left - row_left + x as i32, width as i32), - // No room for an address: a sliver of it that shows nothing. - None => (page_left - row_left, 1), - } -} - /// Rivet's panel look for the pages of a split: Chrome's outline goes. pub unsafe fn install_panels() -> Result<(), String> { if !checked() { @@ -951,10 +883,6 @@ impl crate::browsers::SplitBackend for TabModelSplit { page_area(window) } - unsafe fn on_page_area(&self, area: &mut crate::hooks::page_area::PageArea) { - on_page_area(area) - } - fn address_follows_page(&self) -> bool { address_follows_page() } @@ -962,14 +890,7 @@ impl crate::browsers::SplitBackend for TabModelSplit { #[cfg(test)] mod tests { - use super::{address_in_row, index_vector, narrow_gap, tab_indices, SPLIT_INSETS}; - - #[test] - fn fr9_address_sits_inside_the_full_top_row_at_the_focused_page() { - assert_eq!(address_in_row(267, 267, Some((145.0, 300.0))), (145, 300)); - assert_eq!(address_in_row(267, 854, Some((145.0, 300.0))), (732, 300)); - assert_eq!(address_in_row(267, 854, None), (587, 1)); - } + use super::{index_vector, narrow_gap, tab_indices, SPLIT_INSETS}; #[test] fn fr9_split_outer_edges_match_the_single_page() { diff --git a/rivet/runtime/windows/src/browsers/mod.rs b/rivet/runtime/windows/src/browsers/mod.rs index ebb4fdb..1e3fcc2 100644 --- a/rivet/runtime/windows/src/browsers/mod.rs +++ b/rivet/runtime/windows/src/browsers/mod.rs @@ -18,17 +18,6 @@ fn own_toolbar() -> bool { *OWN.get_or_init(|| crate::builds::get().toolbar.skip.contains("toolbar")) } -/// The function that takes the place of the browser's layout of its window, so the page area can -/// change where the page goes. Chromium lays out in two ways, and the row says which one the -/// build's slot holds. -pub(crate) fn layout_hook() -> usize { - if crate::builds::get().side_panel.old_layout == Some(true) { - chromium::old_layout::old_layout as *const () as usize - } else { - chromium::layout::proposed_layout as *const () as usize - } -} - /// The key of the Rivet window a view of the browser belongs to, or none when the window is not one /// of Rivet's. Views are asked from inside the browser's layout, which runs on the UI thread. pub(crate) unsafe fn rivet_owner(view: *mut std::ffi::c_void) -> Option { @@ -62,8 +51,6 @@ pub(crate) trait SplitBackend: Sync { unsafe fn panes(&self, window: HWND) -> Vec; /// The area the pages fill, as left, top, right and bottom. unsafe fn page_area(&self, window: HWND) -> Option<[i32; 4]>; - /// What the page area layout does for a split. - unsafe fn on_page_area(&self, _area: &mut crate::hooks::page_area::PageArea) {} /// Whether the browser's own address follows the focused page. fn address_follows_page(&self) -> bool; /// The title and address of a page of the split that is no tab of the strip. diff --git a/rivet/runtime/windows/src/builds/brave.rs b/rivet/runtime/windows/src/builds/brave.rs index 2d61e51..ddb9c25 100644 --- a/rivet/runtime/windows/src/builds/brave.rs +++ b/rivet/runtime/windows/src/builds/brave.rs @@ -187,28 +187,12 @@ pub static BRAVE: Build = Build { }, // Only the browser's layout, which the pages of a split need. The Sidebar stays off. side_panel: SidePanel { - layout_vtable: ABSENT, - proposed_slot: 16, - proposed: ABSENT, - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x003E5B50, // ?LayoutImmediately@View@views - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, - ], ..UNCHECKED_SIDEPANEL }, layout: Layout { @@ -226,36 +210,11 @@ pub static BRAVE: Build = Build { corner_paint: 0x0B762730, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_vtable: 0x111E7580, // ??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@ - caption_size_slot: 74, - caption_size: 0x03A4ABD0, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 114, caption_paint: 0x02EBEF10, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - top_inset_slot: 127, - top_inset: ABSENT, - layout_slot: 23, - layout: 0x039F55C0, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - layout_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x40], - set_bounds_rect: 0x06008490, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - caption_container_offset: 0x3C8, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x1112C600, // the browser view vtable frame_vtable: ABSENT, - layout_immediately: 0x003E5B50, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x58, 0x48, 0x89, 0xCE, - ], - set_layer: 0x0087C150, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28], - set_radius: 0x01B50760, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30], - set_masks: 0x02EF7E10, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8B, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0BF3E520, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x02322E10, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x67D, 0x67E, 0x67F], @@ -515,28 +474,12 @@ pub static BRAVE_63: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x11056600, // ??_7BrowserViewTabbedLayoutImpl@@6B@, found statically and unverified - proposed_slot: 16, - proposed: 0x038CA250, // ?CalculateProposedLayout@BrowserViewTabbedLayoutImpl, slot 16, found statically and unverified - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x05EE76D0, // ?LayoutImmediately@View@views - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, - ], event_handler_for_point: 0x018960D0, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -554,36 +497,11 @@ pub static BRAVE_63: Build = Build { corner_paint: 0x0B71E3A0, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_vtable: 0x111A54C0, // ??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@ - caption_size_slot: 74, - caption_size: 0x03A60970, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 114, caption_paint: 0x020F21D0, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], - top_inset_slot: 127, - top_inset: 0x02465480, // ?GetTopInset@BrowserFrameViewWin, slot 127, found statically and unverified - layout_slot: 23, - layout: 0x03A0BCD0, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - layout_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x40], - set_bounds_rect: 0x05EE66C0, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - caption_container_offset: 0x3C8, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x110EA540, // the browser view vtable frame_vtable: 0x110ED840, // ??_7BrowserFrameViewWin@@6BLayerDelegate@ui@@@, found statically and unverified - layout_immediately: 0x05EE76D0, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, - ], - set_layer: 0x00852850, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28], - set_radius: 0x01B70D50, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30], - set_masks: 0x02F42E30, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8B, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0BEFA460, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x0244FE30, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x67D, 0x67E, 0x67F], @@ -876,28 +794,12 @@ pub static BRAVE_157_55: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x114E49D8, // ??_7BrowserViewTabbedLayoutImpl@@6B@, found statically and unverified - proposed_slot: 16, - proposed: 0x03B5F310, // ?CalculateProposedLayout@BrowserViewTabbedLayoutImpl, slot 16, found statically and unverified - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x05E85780, // ?LayoutImmediately@View@views - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, - ], event_handler_for_point: 0x0152B340, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -915,36 +817,11 @@ pub static BRAVE_157_55: Build = Build { corner_paint: 0x0C083EC0, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], caption_vtable: 0x11644170, // ??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@ - caption_size_slot: 74, - caption_size: 0x03E5AC90, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 113, caption_paint: 0x01D8BBD0, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], - top_inset_slot: 126, - top_inset: 0x02360D60, // ?GetTopInset@BrowserFrameViewWin, slot 127, found statically and unverified - layout_slot: 23, - layout: 0x03DFF0D0, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - layout_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x40], - set_bounds_rect: 0x05E84A70, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - caption_container_offset: 0x3C0, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x11598D50, // the browser view vtable frame_vtable: 0x1159C030, // ??_7BrowserFrameViewWin@@6BLayerDelegate@ui@@@, found statically and unverified - layout_immediately: 0x05E85780, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, - ], - set_layer: 0x00817D20, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28], - set_radius: 0x0315EF10, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30], - set_masks: 0x0315EF00, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8B, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0C3D6D80, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x0080EA30, // ?SetFillsBoundsOpaquely@Layer@ui@@UEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1F0, caption_ink_ids: &[0x684, 0x685, 0x686], diff --git a/rivet/runtime/windows/src/builds/chrome.rs b/rivet/runtime/windows/src/builds/chrome.rs index b73a9af..35a3b39 100644 --- a/rivet/runtime/windows/src/builds/chrome.rs +++ b/rivet/runtime/windows/src/builds/chrome.rs @@ -251,28 +251,12 @@ pub static CHROME: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x0FDB_0278, // .weak.??_7BrowserViewTabbedLayoutImpl@@6B@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplate@ - proposed_slot: 16, - proposed: 0x0104_8AB0, // ?CalculateProposedLayout@BrowserViewTabbedLayoutImpl@@MEBA?AUProposedLayout@BrowserViewLayoutImpl@@A - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x04BE_C780, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], event_handler_for_point: 0x007C_6530, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -285,39 +269,14 @@ pub static CHROME: Build = Build { corner_vtable: 0x0FEC_AFC8, // .weak.??_7CustomFloatingCorner@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi corner_paint: 0x0A4C_73A0, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z caption_vtable: 0x0FF0_25C8, // .weak.??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi - caption_size_slot: 74, - caption_size: 0x0313_2D90, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 114, caption_paint: 0x0313_32A0, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z - top_inset_slot: 127, - top_inset: 0x0A40_33E0, // ?GetTopInset@BrowserFrameViewWin@@UEBAH_N@Z - layout_slot: 23, - layout: 0x017A_E5E0, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - set_bounds_rect: 0x04F4_2540, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - caption_container_offset: 0x3C8, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x0FE7_BF68, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat frame_vtable: 0x0FE7_3E28, // .weak.??_7BrowserFrameViewWin@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromis - layout_immediately: 0x04BE_C780, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - set_layer: 0x00F0_5F10, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xec, 0x28], - set_radius: 0x01D3_AB80, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x30], - set_masks: 0x0316_7C40, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8b, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0ACC_8FD0, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x020A_FEF0, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xec, 0x20], on_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], draw_color_prologue: &[0x48, 0x83, 0xec, 0x38, 0x48, 0x8b], get_color_provider_prologue: &[0x56, 0x57, 0x48, 0x83, 0xec, 0x78], corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], @@ -608,28 +567,12 @@ pub static CHROME_156_74: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x0FC2_2820, // .weak.??_7BrowserViewTabbedLayoutImpl@@6B@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplate@ - proposed_slot: 16, - proposed: 0x012B_2170, // ?CalculateProposedLayout@BrowserViewTabbedLayoutImpl@@MEBA?AUProposedLayout@BrowserViewLayoutImpl@@A - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x003E_BA00, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x58, 0x48, 0x89, 0xCE, 0x48, - ], event_handler_for_point: 0x00BA_AC10, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -642,39 +585,14 @@ pub static CHROME_156_74: Build = Build { corner_vtable: 0x0FD3_D2D0, // .weak.??_7CustomFloatingCorner@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi corner_paint: 0x0A28_63E0, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z caption_vtable: 0x0FD7_48D0, // .weak.??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi - caption_size_slot: 74, - caption_size: 0x02F1_FA20, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 114, caption_paint: 0x02F2_0040, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z - top_inset_slot: 127, - top_inset: 0x0184_E3A0, // ?GetTopInset@BrowserFrameViewWin@@UEBAH_N@Z - layout_slot: 23, - layout: 0x0184_DD70, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - set_bounds_rect: 0x04A5_2AF0, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - caption_container_offset: 0x3C8, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x0FCE_E270, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat frame_vtable: 0x0FCE_6130, // .weak.??_7BrowserFrameViewWin@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromis - layout_immediately: 0x003E_BA00, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x58, 0x48, 0x89, 0xCE, 0x48, - ], - set_layer: 0x00F2_86B0, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xec, 0x28], - set_radius: 0x01C0_25E0, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x30], - set_masks: 0x02F5_4C40, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8b, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0AA9_B0A0, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x01D7_6D40, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xec, 0x20], on_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], draw_color_prologue: &[0x48, 0x83, 0xec, 0x38, 0x48, 0x8b], get_color_provider_prologue: &[0x48, 0x83, 0xEC, 0x28, 0x48, 0x8B], corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], @@ -968,28 +886,12 @@ pub static CHROME_156_80: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x0FC1_D598, // .weak.??_7BrowserViewTabbedLayoutImpl@@6B@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplate@ - proposed_slot: 16, - proposed: 0x0141_3500, // ?CalculateProposedLayout@BrowserViewTabbedLayoutImpl@@MEBA?AUProposedLayout@BrowserViewLayoutImpl@@A - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x0497_1310, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], event_handler_for_point: 0x0196_7ED0, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -1002,39 +904,14 @@ pub static CHROME_156_80: Build = Build { corner_vtable: 0x0FD3_8210, // .weak.??_7CustomFloatingCorner@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi corner_paint: 0x0A27_B230, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z caption_vtable: 0x0FD6_F810, // .weak.??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi - caption_size_slot: 74, - caption_size: 0x02F7_9030, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 114, caption_paint: 0x0216_2380, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z - top_inset_slot: 127, - top_inset: 0x0198_BB60, // ?GetTopInset@BrowserFrameViewWin@@UEBAH_N@Z - layout_slot: 23, - layout: 0x0198_B5C0, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - set_bounds_rect: 0x0497_0300, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - caption_container_offset: 0x3C8, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x0FCE_91B0, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat frame_vtable: 0x0FCE_1070, // .weak.??_7BrowserFrameViewWin@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromis - layout_immediately: 0x0497_1310, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - set_layer: 0x00F8_65B0, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xec, 0x28], - set_radius: 0x01C4_6BA0, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x30], - set_masks: 0x02FA_9360, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8b, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0AA9_0760, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x00BA_1BC0, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xec, 0x20], on_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], draw_color_prologue: &[0x48, 0x83, 0xec, 0x38, 0x48, 0x8b], get_color_provider_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x78], corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], frame_browser_window_offset: Some(0x340), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], @@ -1360,28 +1237,12 @@ pub static CHROME_157_38: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x100A_DB68, // .weak.??_7BrowserViewTabbedLayoutImpl@@6B@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplate@ - proposed_slot: 16, - proposed: 0x012C_3340, // ?CalculateProposedLayout@BrowserViewTabbedLayoutImpl@@MEBA?AUProposedLayout@BrowserViewLayoutImpl@@A - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0x50), - contents_container: Some(0xb8), - vertical_tabs: 0x80, - toolbar: 0x60, - contents_outline: 0x58, - side_panel: 0xc0, - side_panel_animation: 0xc8, - layout_immediately: 0x048C_8EC0, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], event_handler_for_point: 0x0163_4870, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -1394,39 +1255,14 @@ pub static CHROME_157_38: Build = Build { corner_vtable: 0x101A_C8F0, // .weak.??_7CustomFloatingCorner@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi corner_paint: 0x0AB9_47C0, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z caption_vtable: 0x101E_13F0, // .weak.??_7WindowsCaptionButton@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromi - caption_size_slot: 74, - caption_size: 0x0320_9420, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 113, caption_paint: 0x01E3_7DF0, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z - top_inset_slot: 126, - top_inset: 0x0AAD_2250, // ?GetTopInset@BrowserFrameViewWin@@UEBAH_N@Z - layout_slot: 23, - layout: 0x01A6_3550, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - set_bounds_rect: 0x048C_81B0, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - caption_container_offset: 0x3C0, view_bounds_offset: 0x1C8, - browser_view_view_vtable: 0x1016_E590, // .weak.??_7BrowserView@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromiseTemplat frame_vtable: 0x1017_4650, // .weak.??_7BrowserFrameViewWin@@6BLayerDelegate@ui@@@.default.?RejectPromiseOnDestruction@?$CdmPromis - layout_immediately: 0x048C_8EC0, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - set_layer: 0x0100_6330, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28], - set_radius: 0x0321_CF10, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30], - set_masks: 0x0321_CF00, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8B, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0AF4_77D0, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_opaque: 0x007E_9970, // ?SetFillsBoundsOpaquely@Layer@ui@@UEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], on_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], draw_color_prologue: &[0x48, 0x83, 0xEC, 0x38, 0x48, 0x8B], get_color_provider_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x78], corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - layout_prologue: &[0x41, 0x56, 0x56, 0x57, 0x55, 0x53], - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], @@ -1463,39 +1299,14 @@ pub static CHROME_150: Build = Build { corner_vtable: 0xef34798, corner_paint: 0xe451e40, caption_vtable: 0xef54f58, - caption_size_slot: 74, - caption_size: 0x322fdb0, caption_paint_slot: 114, caption_paint: 0x1d823e0, - top_inset_slot: 127, - top_inset: 0xe5435a0, - layout_slot: 23, - layout: 0x17e4cd0, - set_bounds_rect: 0x44cff90, - caption_container_offset: 0x3c0, view_bounds_offset: 0x1c0, - browser_view_view_vtable: 0xeeaecd8, frame_vtable: 0xef32f18, - layout_immediately: 0x44d1380, - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], - set_layer: 0xd28650, - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28], - set_radius: 0x2c89450, - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30], - set_masks: 0x2c893c0, - set_masks_prologue: &[0x48, 0x8B, 0x89, 0xC8, 0x01, 0x00, 0x00], - stack_at_top: 0x9baf850, - stack_at_top_prologue: &[0x4C, 0x8B, 0x41, 0x30, 0x48, 0x8B], - set_opaque: 0x126da80, - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], on_paint_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28, 0x48, 0x89], draw_color_prologue: &[0x48, 0x83, 0xEC, 0x38, 0x48, 0x8B], get_color_provider_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x68], corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - layout_prologue: &[0x41, 0x57, 0x41, 0x56, 0x56, 0x57], - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x1f0, caption_paint_prologue: &[0xE9, 0x0B, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC], diff --git a/rivet/runtime/windows/src/builds/edge.rs b/rivet/runtime/windows/src/builds/edge.rs index f53e1cf..c7a32ba 100644 --- a/rivet/runtime/windows/src/builds/edge.rs +++ b/rivet/runtime/windows/src/builds/edge.rs @@ -255,29 +255,12 @@ pub static EDGE: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: ABSENT, - proposed_slot: 4, - proposed: 0x028C7270, // ?Layout@BrowserViewLayoutImplOld@@UEAAXPEAVView@views@@@Z - old_layout: Some(true), registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x38), - page_area: Some(0), - contents_container: Some(0xd8), - vertical_tabs: ABSENT, - toolbar: ABSENT, // the pages of a split fit their toolbar in Chrome's layout only - contents_outline: ABSENT, - side_panel: 0xb8, // ??_7SidePanel@@6BLayerDelegate@ui@@@ - side_panel_animation: ABSENT, - layout_immediately: 0x01044270, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x58, 0x48, 0x89, 0xCE, 0x48, 0x8B, 0x05, - 0xBE, 0xFD, 0x1A, 0x13, - ], event_handler_for_point: 0x0109FB78, // ?GetEventHandlerForPoint@View@views@@QEAAPEAV12@AEBVPoint@gfx@@@Z }, layout: Layout { @@ -290,39 +273,14 @@ pub static EDGE: Build = Build { corner_vtable: 0x118B7ED8, // CustomFloatingCorner vtable corner_paint: 0x0A66B240, // ?OnPaint@CustomFloatingCorner@@UEAAXPEAVCanvas@gfx@@@Z caption_vtable: 0x118F2478, // WindowsCaptionButton vtable - caption_size_slot: 86, - caption_size: 0x0A7EDBF0, // ?CalculatePreferredSize@WindowsCaptionButton@@UEBA?AVSize@gfx@@AEBVSizeBounds@views@@@Z caption_paint_slot: 127, caption_paint: 0x02D1ECF0, // ?PaintButtonContents@WindowsCaptionButton@@UEAAXPEAVCanvas@gfx@@@Z - top_inset_slot: 164, - top_inset: 0x033CA100, // ?GetTopInset@BrowserFrameViewWin@@UEBAH_N@Z - layout_slot: 24, - layout: 0x02930FA0, // ?Layout@BrowserFrameViewWin@@MEAAXV?$NonCopyablePassKey@VView@views@@@base@@@Z - set_bounds_rect: 0x01021E78, // ?SetBoundsRect@View@views@@QEAAXAEBVRect@gfx@@@Z - caption_container_offset: 0x440, // caption_button_container_, read by CaptionButtonsRegionWidth view_bounds_offset: 0x1C8, // views::View::bounds_, unchanged - browser_view_view_vtable: 0x11937B18, // BrowserView View vtable frame_vtable: 0x11857718, // the frame view vtable - layout_immediately: 0x01044270, // ?LayoutImmediately@View@views@@AEAAXXZ - layout_immediately_prologue: &[ - 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x58, 0x48, 0x89, 0xCE, 0x48, - ], - set_layer: 0x02782F98, // ?SetPaintToLayer@View@views@@QEAAXW4LayerType@ui@@@Z - set_layer_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x28], - set_radius: 0x02DA71BE, // ?SetRoundedCornerRadius@Layer@ui@@QEAAXAEBVRoundedCornersF@gfx@@@Z - set_radius_prologue: &[0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x30], - set_masks: 0x0306E54C, // ?SetMasksToBounds@Layer@ui@@QEAAX_N@Z - set_masks_prologue: &[0x48, 0x8B, 0x89, 0x70, 0x01, 0x00, 0x00], - stack_at_top: 0x0B415B2E, // ?StackAtTop@Layer@ui@@QEAAXPEAV12@@Z - stack_at_top_prologue: &[0x41, 0x56, 0x56, 0x57, 0x53, 0x48], - set_opaque: 0x0103A07E, // ?SetFillsBoundsOpaquely@Layer@ui@@QEAAX_N@Z - set_opaque_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x20], on_paint_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x38, 0x48, 0x89], draw_color_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x38], get_color_provider_prologue: &[0x48, 0x83, 0xEC, 0x28, 0x48, 0x8B], corner_paint_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], - layout_prologue: &[0x56, 0x48, 0x83, 0xEC, 0x40, 0x48], - set_bounds_rect_prologue: &[0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54], frame_browser_window_offset: Some(0x3B0), // frame view member that holds the BrowserWindow subobject, read by GetBrowserView browser_window_in_view: 0x1F8, // BrowserWindow subobject distance from the BrowserView, read by GetBrowserView caption_paint_prologue: &[0xE9, 0x01, 0x00, 0x00, 0x00, 0xCC, 0x41, 0x57], diff --git a/rivet/runtime/windows/src/builds/mod.rs b/rivet/runtime/windows/src/builds/mod.rs index 1f0cbdf..b4d1342 100644 --- a/rivet/runtime/windows/src/builds/mod.rs +++ b/rivet/runtime/windows/src/builds/mod.rs @@ -107,11 +107,6 @@ pub struct Omnibox { pub allocate: usize, pub match_contents: usize, pub match_description: usize, - /// The vtable of `BrowserViewAppLayoutImpl`, the slot of its `CalculateProposedLayout` and that - /// function, which lays out an app window. - pub app_layout_vtable: usize, - pub app_layout_slot: usize, - pub app_layout_proposed: usize, /// The first bytes of every function above, compared with the loaded module before any call. pub signatures: &'static [(usize, &'static [u8])], } @@ -404,14 +399,6 @@ pub struct SidePanel { /// `ThemeSource::GenerateColorsCss(out, provider, url, flag, flag)`, which writes the style sheet. pub generate_colors_css: usize, pub generate_colors_css_prologue: &'static [u8], - /// `BrowserViewTabbedLayoutImpl::CalculateProposedLayout`, slot 16 of its vtable. It fills a - /// `std::map` of view to bounds that the layout then applies. - pub layout_vtable: usize, - pub proposed_slot: usize, - pub proposed: usize, - /// The slot holds Chromium's older `BrowserViewLayoutImplOld::Layout` in place of - /// `CalculateProposedLayout`, so the layout hook sets bounds after the browser's layout runs. - pub old_layout: Option, /// The registry keeps its entries as begin and end pointers at +0x38 and +0x40, where newer /// builds keep a pointer and a count. pub registry_end: Option, @@ -427,25 +414,6 @@ pub struct SidePanel { /// The build's show by id stops the browser for an extension's entry, which then opens with /// toggle and its key. pub extensions_by_toggle: Option, - /// The layout object keeps the host view at +0x38, the contents container at +0xb8, the side - /// panel at +0xc0 and the content shown while the side panel animates at +0xc8. The host view, - /// the page area and the contents container are also found by the class names of the views - /// they hold, and a row value only confirms them; `None` when the row does not have one. - pub host_view: Option, - /// The view behind the whole area below the top row, which the rail shares the height of. - pub page_area: Option, - pub contents_container: Option, - /// The browser's vertical tab list, which lies left of the page. - pub vertical_tabs: usize, - /// The browser's top row: toolbar, address bar and the buttons around it. - pub toolbar: usize, - /// The view that draws the outline around the contents, which has the contents' bounds. - pub contents_outline: usize, - pub side_panel: usize, - pub side_panel_animation: usize, - /// `views::View::DeprecatedLayoutImmediately`. - pub layout_immediately: usize, - pub layout_immediately_prologue: &'static [u8], /// `views::View::GetEventHandlerForPoint`, which the click diagnostic calls. pub event_handler_for_point: usize, } @@ -478,56 +446,22 @@ pub struct Layout { /// wedge is painted with Rivet's frame colour instead of Chrome's blue. pub corner_vtable: usize, pub corner_paint: usize, - /// Experiment, Chrome 156.0.8078.48 only: `WindowsCaptionButton::CalculatePreferredSize` in the - /// caption button's vtable. Rivet windows get caption buttons as tall as the shell study's top - /// row, so the native buttons sit centred in it. + /// `WindowsCaptionButton::PaintButtonContents` in the caption button's vtable, which paints the + /// native caption buttons with the window's colours. pub caption_vtable: usize, - pub caption_size_slot: usize, - pub caption_size: usize, pub caption_paint_slot: usize, pub caption_paint: usize, - /// Experiment, Chrome 156.0.8078.48 only: `BrowserFrameViewWin::GetTopInset` in the frame view's - /// vtable. It is the height of the browser's own title bar, which also sizes the caption buttons. - pub top_inset_slot: usize, - pub top_inset: usize, - /// Experiment, Chrome 156.0.8078.48 only: `BrowserFrameViewWin::Layout` in the frame view's - /// vtable. It sizes the caption button container from the tab strip, not from the title bar - /// height, so the container is resized once the browser's own layout is done. - pub layout_slot: usize, - pub layout: usize, - /// `views::View::SetBoundsRect`, and where a frame view keeps its caption button container and a - /// view keeps its bounds. - pub set_bounds_rect: usize, - pub caption_container_offset: usize, + /// Where a view keeps its bounds. pub view_bounds_offset: usize, - /// The vtable of the `views::View` part of `BrowserView`, which sits behind other base classes. - pub browser_view_view_vtable: usize, /// The `views::View` vtable of the frame view the browser window uses. pub frame_vtable: usize, - /// `views::View::DeprecatedLayoutImmediately` and its first instructions. - pub layout_immediately: usize, - pub layout_immediately_prologue: &'static [u8], - /// Layer helpers of the panel clip: `View::SetPaintToLayer`, `Layer::SetRoundedCornerRadius`, -/// `Layer::SetMasksToBounds`, `Layer::StackAtTop` and `Layer::SetFillsBoundsOpaquely`. - pub set_layer: usize, - pub set_layer_prologue: &'static [u8], - pub set_radius: usize, - pub set_radius_prologue: &'static [u8], - pub set_masks: usize, - pub set_masks_prologue: &'static [u8], - pub stack_at_top: usize, - pub stack_at_top_prologue: &'static [u8], - pub set_opaque: usize, - pub set_opaque_prologue: &'static [u8], pub on_paint_prologue: &'static [u8], pub draw_color_prologue: &'static [u8], pub get_color_provider_prologue: &'static [u8], pub corner_paint_prologue: &'static [u8], - pub layout_prologue: &'static [u8], - pub set_bounds_rect_prologue: &'static [u8], /// `BrowserFrameViewWin` holds the `BrowserView`'s `BrowserWindow` subobject here, and the /// subobject lies this many bytes after the start of the `BrowserView`. The field is also found - /// as the one that holds the view the layout lays out, and a row value only confirms it. + /// as the one that holds the browser view, and a row value only confirms it. pub frame_browser_window_offset: Option, pub browser_window_in_view: usize, pub caption_paint_prologue: &'static [u8], @@ -682,26 +616,12 @@ const UNCHECKED_SIDEPANEL: SidePanel = SidePanel { color_source: 0, generate_colors_css: ABSENT, generate_colors_css_prologue: &[0], - layout_vtable: ABSENT, - proposed_slot: 0, - proposed: ABSENT, - old_layout: None, registry_end: None, registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: None, - page_area: None, - contents_container: None, - vertical_tabs: 0, - toolbar: 0, - contents_outline: 0, - side_panel: 0, - side_panel_animation: 0, - layout_immediately: ABSENT, - layout_immediately_prologue: &[0], event_handler_for_point: ABSENT, }; @@ -716,37 +636,14 @@ const UNCHECKED_LAYOUT: Layout = Layout { corner_vtable: ABSENT, corner_paint: ABSENT, caption_vtable: ABSENT, - caption_size_slot: 0, - caption_size: ABSENT, caption_paint_slot: 0, caption_paint: ABSENT, - top_inset_slot: 0, - top_inset: ABSENT, - layout_slot: 0, - layout: ABSENT, - set_bounds_rect: ABSENT, - caption_container_offset: 0, view_bounds_offset: 0, - browser_view_view_vtable: ABSENT, frame_vtable: ABSENT, - layout_immediately: ABSENT, - layout_immediately_prologue: &[0], - set_layer: ABSENT, - set_layer_prologue: &[0], - set_radius: ABSENT, - set_radius_prologue: &[0], - set_masks: ABSENT, - set_masks_prologue: &[0], - stack_at_top: ABSENT, - stack_at_top_prologue: &[0], - set_opaque: ABSENT, - set_opaque_prologue: &[0], on_paint_prologue: &[0], draw_color_prologue: &[0], get_color_provider_prologue: &[0], corner_paint_prologue: &[0], - layout_prologue: &[0], - set_bounds_rect_prologue: &[0], frame_browser_window_offset: None, browser_window_in_view: 0, caption_paint_prologue: &[0], diff --git a/rivet/runtime/windows/src/builds/omnibox_rows.rs b/rivet/runtime/windows/src/builds/omnibox_rows.rs index dd11d6a..9189a2a 100644 --- a/rivet/runtime/windows/src/builds/omnibox_rows.rs +++ b/rivet/runtime/windows/src/builds/omnibox_rows.rs @@ -33,9 +33,6 @@ pub(super) const OMNIBOX_CHROME_156_74: Omnibox = Omnibox { allocate: 0x05A1_E310, match_contents: 0x2A0, match_description: 0x2D0, - app_layout_vtable: 0x0FC2_25E0, - app_layout_slot: 16, - app_layout_proposed: 0x0A28_0200, signatures: &[ (0x04DA_2510, &[0x48, 0x89, 0xC8, 0xC3]), ( @@ -165,9 +162,6 @@ pub(super) const OMNIBOX_CHROME_156_80: Omnibox = Omnibox { allocate: 0x059F_C170, match_contents: 0x2A0, match_description: 0x2D0, - app_layout_vtable: 0x0FC1_D358, - app_layout_slot: 16, - app_layout_proposed: 0x0A27_5100, signatures: &[ (0x04BC_8250, &[0x48, 0x89, 0xC8, 0xC3]), ( @@ -299,9 +293,6 @@ pub(super) const OMNIBOX_CHROME_157_38: Omnibox = Omnibox { allocate: 0x05E7_5E90, match_contents: 0x2A0, match_description: 0x2D0, - app_layout_vtable: 0x100A_D928, - app_layout_slot: 16, - app_layout_proposed: 0x0AB8_F640, signatures: &[ (0x04FC_8630, &[0x48, 0x89, 0xC8, 0xC3]), ( @@ -432,9 +423,6 @@ pub(super) const OMNIBOX_BRAVE_63: Omnibox = Omnibox { allocate: 0x06F4_DE00, match_contents: 0x2A0, match_description: 0x2D0, - app_layout_vtable: 0x1105_67A0, - app_layout_slot: 16, - app_layout_proposed: 0x0B71_A730, signatures: &[ (0x0613_B670, &[0x48, 0x89, 0xC8, 0xC3]), ( @@ -565,9 +553,6 @@ pub(super) const OMNIBOX_BRAVE_157_55: Omnibox = Omnibox { allocate: 0x073F_5220, match_contents: 0x2A0, match_description: 0x2D0, - app_layout_vtable: 0x114E_4B78, - app_layout_slot: 16, - app_layout_proposed: 0x0C08_0160, signatures: &[ (0x0658_9680, &[0x48, 0x89, 0xC8, 0xC3]), ( @@ -698,9 +683,6 @@ pub(super) const OMNIBOX_WHALE_57: Omnibox = Omnibox { allocate: 0x03E4_AB40, match_contents: 0x2D8, match_description: 0x308, - app_layout_vtable: 0x0F9F_BBF8, - app_layout_slot: 15, - app_layout_proposed: 0x0E6A_8BD0, signatures: &[ (0x005D_5480, &[0x48, 0x89, 0xC8, 0xC3]), ( @@ -835,9 +817,6 @@ pub(super) const OMNIBOX_SAMSUNG_29: Omnibox = Omnibox { allocate: 0x0558_41C8, match_contents: 0x2D0, match_description: 0x300, - app_layout_vtable: 0, - app_layout_slot: 0, - app_layout_proposed: 0, signatures: &[ (0x04D1_1D20, &[0x48, 0x89, 0xC8, 0xC3]), ( diff --git a/rivet/runtime/windows/src/builds/samsung.rs b/rivet/runtime/windows/src/builds/samsung.rs index 1b8cf3b..e2a951a 100644 --- a/rivet/runtime/windows/src/builds/samsung.rs +++ b/rivet/runtime/windows/src/builds/samsung.rs @@ -328,43 +328,21 @@ pub static SAMSUNG: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x0E18_0BE0, - proposed_slot: 3, - proposed: 0x013C_8310, - old_layout: Some(true), registry_end: Some(true), registry_in_coordinator: Some(0x30), registry_entries: Some(0x48), coordinator_browser: Some(0x28), entry_key_size: Some(0x48), extensions_by_toggle: Some(true), - host_view: Some(0x30), - page_area: Some(ABSENT), - contents_container: Some(0x80), - vertical_tabs: ABSENT, - toolbar: 0x70, - contents_outline: ABSENT, - side_panel: 0x98, - side_panel_animation: ABSENT, - layout_immediately: 0x047C_B9E0, - layout_immediately_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, 0x48, 0x81, - 0xEC, 0x98, 0x00, 0x00, 0x00, 0x48, 0x89, 0xCE, - ], event_handler_for_point: ABSENT, }, - // The frame paint and the top inset are not recorded: nothing shows that this build's functions in - // those vtable slots are Chromium's, and its frame vtable does not have Chromium's layout. + // The frame paint is not recorded: nothing shows that this build's function in that vtable slot + // is Chromium's, and its frame vtable does not have Chromium's layout. layout: Layout { // The browser view's `views::View` lies this far inside the object `GetBrowserViewForNativeWindow` // answers, read from the parent of its children. browser_window_in_view: 0x1F8, - // `views::View::SetBoundsRect` and where a view keeps its bounds, which the older layout's - // page area sets after the browser's layout ran. - set_bounds_rect: 0x047C_EA60, - set_bounds_rect_prologue: &[ - 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, - ], + // Where a view keeps its bounds. view_bounds_offset: 0x1C0, ..UNCHECKED_LAYOUT }, diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index 1a03c23..0be0e74 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -200,7 +200,6 @@ fn nfr3_whale_maps_only_the_frame_hooks() { // Hooks without a verified address are absent, so their checks fail. assert_eq!(WHALE.layout.corner_paint, ABSENT); assert_eq!(WHALE.layout.caption_paint, ABSENT); - assert_eq!(WHALE.layout.layout, ABSENT); assert_eq!( ( WHALE.layout.frame_browser_window_offset, @@ -211,14 +210,14 @@ fn nfr3_whale_maps_only_the_frame_hooks() { } #[test] -fn fr2_whale_records_chromium_s_frame_paint_and_top_inset() { - // Rivet's frame on Whale needs Chromium's `BrowserFrameViewWin` paint and top inset. +fn fr2_whale_records_chromium_s_frame_paint() { + // Rivet's frame on Whale needs Chromium's `BrowserFrameViewWin` paint. let layout = &WHALE.layout; assert_eq!( - (layout.frame_vtable, layout.on_paint, layout.top_inset), - (0x0FB1_7440, 0x0253_D0E0, 0x0E7B_4500) + (layout.frame_vtable, layout.on_paint), + (0x0FB1_7440, 0x0253_D0E0) ); - assert_eq!((layout.on_paint_slot, layout.top_inset_slot), (89, 127)); + assert_eq!(layout.on_paint_slot, 89); assert!(layout.on_paint_prologue.len() >= 12); let Ok(file) = std::fs::read(WHALE_DLL) else { return; @@ -227,16 +226,11 @@ fn fr2_whale_records_chromium_s_frame_paint_and_top_inset() { file_bytes(&file, layout.on_paint, layout.on_paint_prologue.len()).as_deref(), Some(layout.on_paint_prologue) ); - // The vtable slots hold the two functions. - for (slot, function) in [ - (layout.on_paint_slot, layout.on_paint), - (layout.top_inset_slot, layout.top_inset), - ] { - let entry = file_bytes(&file, layout.frame_vtable + slot * 8, 8) - .expect("the vtable is in the file"); - let pointer = u64::from_le_bytes(entry.try_into().unwrap()) as usize; - assert_eq!(pointer - 0x1_8000_0000, function); - } + // The vtable slot holds the paint function. + let entry = file_bytes(&file, layout.frame_vtable + layout.on_paint_slot * 8, 8) + .expect("the vtable is in the file"); + let pointer = u64::from_le_bytes(entry.try_into().unwrap()) as usize; + assert_eq!(pointer - 0x1_8000_0000, layout.on_paint); } /// The chrome.dll of a Brave row, when that version is the one installed. @@ -263,22 +257,14 @@ fn check_brave_frame_hooks(brave: &Build) { && brave.navigation.supported ); assert!(!brave.split.supported); - // The .62 row records no frame paint or top inset. The .63 row records Chromium's own. + // The .62 row records no frame paint. The .63 row records Chromium's own. if brave.version == BRAVE.version { assert_eq!( - ( - brave.layout.frame_vtable, - brave.layout.on_paint, - brave.layout.top_inset - ), - (ABSENT, ABSENT, ABSENT) + (brave.layout.frame_vtable, brave.layout.on_paint), + (ABSENT, ABSENT) ); } else { - assert!( - brave.layout.frame_vtable != ABSENT - && brave.layout.on_paint != ABSENT - && brave.layout.top_inset != ABSENT - ); + assert!(brave.layout.frame_vtable != ABSENT && brave.layout.on_paint != ABSENT); } let Some(file) = brave_dll(brave) else { return; @@ -301,42 +287,6 @@ fn check_brave_frame_hooks(brave: &Build) { layout.caption_paint, layout.caption_paint_prologue, ), - ("frame layout", layout.layout, layout.layout_prologue), - ( - "set bounds", - layout.set_bounds_rect, - layout.set_bounds_rect_prologue, - ), - ( - "layout immediately", - layout.layout_immediately, - layout.layout_immediately_prologue, - ), - ( - "paint to layer", - layout.set_layer, - layout.set_layer_prologue, - ), - ( - "rounded corners", - layout.set_radius, - layout.set_radius_prologue, - ), - ( - "masks to bounds", - layout.set_masks, - layout.set_masks_prologue, - ), - ( - "stack at top", - layout.stack_at_top, - layout.stack_at_top_prologue, - ), - ( - "fills opaquely", - layout.set_opaque, - layout.set_opaque_prologue, - ), ] { assert_eq!( file_bytes(&file, rva, prologue.len()).as_deref(), @@ -364,12 +314,6 @@ fn check_brave_frame_hooks(brave: &Build) { layout.on_paint_slot, layout.corner_paint, ), - ( - "caption size", - layout.caption_vtable, - layout.caption_size_slot, - layout.caption_size, - ), ( "caption paint", layout.caption_vtable, @@ -413,11 +357,6 @@ fn check_side_panel_hooks(file: &[u8], row: &SidePanel, name: &str) { row.generate_colors_css, row.generate_colors_css_prologue, ), - ( - "layout immediately", - row.layout_immediately, - row.layout_immediately_prologue, - ), ] { assert_eq!( file_bytes(file, rva, prologue.len()).as_deref(), @@ -429,8 +368,7 @@ fn check_side_panel_hooks(file: &[u8], row: &SidePanel, name: &str) { file_bytes(file, rva, 8) .map(|bytes| u64::from_le_bytes(bytes.try_into().unwrap()) as usize - image_base) }; - // The coordinator's vtable holds Show in slot 2 and Toggle in slot 5, and the layout vtable - // holds the function Rivet replaces in the slot the row names. + // The coordinator's vtable holds Show in slot 2 and Toggle in slot 5. if row.coordinator_vtable != ABSENT { assert_eq!( pointer(row.coordinator_vtable + 2 * 8), @@ -443,13 +381,6 @@ fn check_side_panel_hooks(file: &[u8], row: &SidePanel, name: &str) { "toggle slot of {name}" ); } - if row.layout_vtable != ABSENT { - assert_eq!( - pointer(row.layout_vtable + row.proposed_slot * 8), - Some(row.proposed), - "layout slot of {name}" - ); - } // Both views start with their own vtable, which the objects are found by. assert!( pointer(row.side_panel_vtable).is_some() && pointer(row.browser_view_view_vtable).is_some() @@ -458,7 +389,7 @@ fn check_side_panel_hooks(file: &[u8], row: &SidePanel, name: &str) { #[test] fn fr10_brave_63_side_panel_row_matches_the_installed_build() { - // The .63 row records Chromium's coordinator, toggle and page layout. The Sidebar stays off + // The .63 row records Chromium's coordinator and toggle. The Sidebar stays off // until it is driven. assert!(!BRAVE_63.side_panel.supported && !BRAVE.side_panel.supported); assert_eq!( @@ -481,8 +412,6 @@ fn fr10_edge_side_panel_row_matches_the_installed_build() { !row.supported, "Edge's only registered panel cannot be opened" ); - // The Edge row's layout function is slot 4 of its layout vtable. - assert_eq!(row.proposed_slot, 4); assert_eq!(row.hidden_entries, &[0]); let Ok(file) = std::fs::read( r"C:\Program Files (x86)\Microsoft\Edge\Application\156.0.4314.50\msedge.dll", @@ -508,10 +437,9 @@ fn nfr3_samsung_frame_and_tab_hooks_match_the_installed_build() { && !SAMSUNG.tabs.groups && !SAMSUNG.split.supported ); - // Nothing outside Chromium is recorded for the frame: no paint, no colours and no top inset. + // Nothing outside Chromium is recorded for the frame: no paint and no colours. for rva in [ SAMSUNG.layout.on_paint, - SAMSUNG.layout.top_inset, SAMSUNG.layout.corner_paint, SAMSUNG.layout.caption_paint, ] { @@ -1008,12 +936,7 @@ fn nfr3_chromium_157_rows_record_the_members_that_moved() { Some(0x338), "{name}" ); - assert_eq!(build.layout.caption_container_offset, 0x3C0, "{name}"); - assert_eq!( - (build.layout.top_inset_slot, build.layout.caption_paint_slot), - (126, 113), - "{name}" - ); + assert_eq!(build.layout.caption_paint_slot, 113, "{name}"); assert_eq!(build.omnibox.as_ref().unwrap().match_size, 0x690, "{name}"); let split = &build.split; assert_eq!( @@ -1355,8 +1278,8 @@ fn fr12_edge_58_whale_57_and_samsung_29_record_the_page_view_bounds_slot() { #[test] fn fr12_edge_58_and_whale_57_record_the_page_view_that_moves_below_the_bar() { - // Neither build records the Sidebar's layout, so the bar's row is kept free by moving the page - // view, which needs the second view's constructor, its allocation and `AddChildViewAt`. + // The bar's row is kept free by moving the page view, which needs the second view's + // constructor, its allocation and `AddChildViewAt`. let table: serde_json::Value = serde_json::from_str(CHECKED_IN).expect("the checked-in table is JSON"); let edge = table["rows"] @@ -1368,10 +1291,6 @@ fn fr12_edge_58_and_whale_57_record_the_page_view_that_moves_below_the_bar() { }) }) .expect("the table holds a row for Edge 156.0.4314.58"); - assert_eq!( - edge["build"]["side_panel"]["layout_vtable"], - format!("{ABSENT:#x}") - ); for name in ["operator_new", "web_view_ctor", "add_child", "set_contents"] { assert!( edge["build"]["app_window"][name].is_string(), @@ -1380,7 +1299,6 @@ fn fr12_edge_58_and_whale_57_record_the_page_view_that_moves_below_the_bar() { } let whale = &super::whale::WHALE; assert_eq!(whale.version, [5, 39, 412, 57]); - assert_eq!(whale.side_panel.layout_vtable, 0x0F9F_BB38); let row = whale .app_window .as_ref() diff --git a/rivet/runtime/windows/src/builds/whale.rs b/rivet/runtime/windows/src/builds/whale.rs index 5c9711a..e84c9b5 100644 --- a/rivet/runtime/windows/src/builds/whale.rs +++ b/rivet/runtime/windows/src/builds/whale.rs @@ -334,28 +334,12 @@ pub static WHALE: Build = Build { generate_colors_css_prologue: &[ 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x55, 0x53, ], - layout_vtable: 0x0F9F_BB38, - proposed_slot: 15, - proposed: 0x0252_E780, - old_layout: None, registry_end: Some(true), registry_in_coordinator: None, registry_entries: None, coordinator_browser: None, entry_key_size: None, extensions_by_toggle: None, - host_view: Some(0x20), - page_area: Some(0x28), - contents_container: Some(0x90), - vertical_tabs: 0x60, - toolbar: 0x40, - contents_outline: 0x38, - side_panel: 0xA0, - side_panel_animation: 0xA8, - layout_immediately: 0x08F7_CD40, - layout_immediately_prologue: &[ - 0x56, 0x57, 0x55, 0x53, 0x48, 0x83, 0xEC, 0x58, 0x48, 0x89, 0xCE, - ], event_handler_for_point: 0x08F8_1F60, }, layout: Layout { @@ -374,14 +358,10 @@ pub static WHALE: Build = Build { draw_color: 0x9bc45b0, draw_color_prologue: &[0x56, 0x57, 0x48, 0x83, 0xEC, 0x38], frame_ids: &[0x13C, 0x13D, 0x140, 321, 0x144], - top_inset_slot: 127, - top_inset: 0x0E7B_4500, frame_vtable: 0x0FB1_7440, // Slot 74 of this caption vtable reads members Chromium's `WindowsCaptionButton` does not // have, so the caption buttons' size is the browser's own and stays out. caption_vtable: 0xfb15d60, - caption_size_slot: 74, - caption_size: ABSENT, frame_browser_window_offset: Some(0x338), browser_window_in_view: 0x210, view_bounds_offset: 0x1C0, diff --git a/rivet/runtime/windows/src/chromium/view.rs b/rivet/runtime/windows/src/chromium/view.rs index 49621fd..b6c7734 100644 --- a/rivet/runtime/windows/src/chromium/view.rs +++ b/rivet/runtime/windows/src/chromium/view.rs @@ -12,9 +12,6 @@ pub(crate) struct View(usize); impl View { /// Where a view keeps its parent. pub(crate) const PARENT: usize = 0x198; - /// Where a Chromium 156 view keeps its bounds in its parent, for the tests of the typed reads. - #[cfg(test)] - pub(crate) const BOUNDS: usize = 0x1C8; /// Where a view keeps its parent, from where its build keeps the bounds. In `views::View` the /// parent pointer lies 0x30 before the bounds: `parent_`, the `children_` vector, two flags and @@ -30,49 +27,12 @@ impl View { pub(crate) const fn children_offset(parent_offset: usize) -> usize { parent_offset + 8 } - - pub(crate) const fn at(address: usize) -> Self { - Self(address) - } - - /// The address of the parent kept at `offset`, or zero for a root. - pub(crate) unsafe fn parent_address(self, offset: usize) -> usize { - *((self.0 + offset) as *const usize) - } - - /// x, y, width and height in the parent, kept at `offset`. - pub(crate) unsafe fn bounds(self, offset: usize) -> [i32; 4] { - *((self.0 + offset) as *const [i32; 4]) - } } #[cfg(test)] mod tests { use super::*; - /// Two fake views in plain memory: a child inside a parent. - #[test] - fn nfr3_a_view_reads_its_parent_and_bounds_at_the_recorded_offsets() { - let mut parent = vec![0u8; 0x300]; - let mut child = vec![0u8; 0x300]; - let parent_at = parent.as_mut_ptr() as usize; - child[View::PARENT..View::PARENT + 8].copy_from_slice(&parent_at.to_le_bytes()); - for (index, value) in [10i32, 20, 300, 40].into_iter().enumerate() { - child[View::BOUNDS + index * 4..View::BOUNDS + index * 4 + 4] - .copy_from_slice(&value.to_le_bytes()); - } - for (index, value) in [5i32, 6, 900, 800].into_iter().enumerate() { - parent[View::BOUNDS + index * 4..View::BOUNDS + index * 4 + 4] - .copy_from_slice(&value.to_le_bytes()); - } - let view = View::at(child.as_ptr() as usize); - unsafe { - assert_eq!(view.bounds(View::BOUNDS), [10, 20, 300, 40]); - assert_eq!(view.parent_address(View::PARENT), parent_at); - assert_eq!(View::at(parent_at).parent_address(View::PARENT), 0); - } - } - #[test] fn nfr3_a_views_parent_lies_0x30_before_its_bounds() { // Chrome 156 and later, Brave and Edge record their bounds at 0x1C8: the parent at 0x198. diff --git a/rivet/runtime/windows/src/chromium/window_views.rs b/rivet/runtime/windows/src/chromium/window_views.rs index 50c3c42..b4366d1 100644 --- a/rivet/runtime/windows/src/chromium/window_views.rs +++ b/rivet/runtime/windows/src/chromium/window_views.rs @@ -3,15 +3,9 @@ //! //! Each path below follows public Chromium source: //! -//! - `BrowserViewLayout` keeps the views it lays out in `BrowserViewLayoutViews views_` -//! (`chrome/browser/ui/views/frame/layout/browser_view_layout.h`). Its `browser_view` is the -//! `BrowserView` as a `views::View`, `main_background_region` is a `MainBackgroundRegionView` and -//! `multi_contents_view` is a `MultiContentsView`. `BrowserView::BrowserView` adds both of the -//! latter with `AddChildView` (`browser_view.cc`), so each names the browser view as its parent. -//! The layout's fields are found by the class names of the views they point at. //! - `BrowserFrameView` keeps the browser view in `views::ViewTracker browser_view_` -//! (`browser_frame_view.h`), which holds the `BrowserView`'s `views::View`: the view the layout -//! lays out. The frame view's field is the one that holds the same view. +//! (`browser_frame_view.h`), which holds the `BrowserView`'s `views::View`. The frame view's field +//! is the one that holds a view named `BrowserView` whose children all name it as their parent. //! - A view's widget is what `View::GetWidget` returns: the root view's `widget_`, a //! `raw_ptr` of `views::internal::RootView` (`ui/views/widget/root_view.h`). The root //! view is reached through `View::parent_` until it is null. `Widget` owns the root view in @@ -31,11 +25,7 @@ pub(crate) trait Memory { } pub(crate) const BROWSER_VIEW: &str = "BrowserView"; -pub(crate) const MAIN_BACKGROUND_REGION: &str = "MainBackgroundRegionView"; -pub(crate) const MULTI_CONTENTS: &str = "MultiContentsView"; -/// How far into a layout object its view fields are looked for. -const LAYOUT_REACH: usize = 0x400; /// How far into a frame view, a root view or a widget a field is looked for. const OBJECT_REACH: usize = 0x1000; /// How many parents a view may have before the walk to its root gives up. @@ -75,44 +65,8 @@ pub(crate) fn fields_naming( found } -/// The fields of a browser layout object, as offsets into it. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub(crate) struct LayoutFields { - /// The fields that hold the `BrowserView`, the view the layout lays out. - pub host: Vec, - /// The fields that hold the `MainBackgroundRegionView`, the area below the top row. - pub page_area: Vec, - /// The fields that hold the `MultiContentsView`, which holds the pages. - pub contents: Vec, -} - -/// The view fields of the layout object at `layout`. With the parent field known, a page area or -/// contents view counts only when it names the browser view as its parent, as `AddChildView` left -/// it. `None` when no field holds a browser view. -pub(crate) fn layout_fields( - memory: &M, - layout: usize, - parent: Option, -) -> Option { - let anything = |_: usize| true; - let (host, view) = fields_naming(memory, layout, LAYOUT_REACH, BROWSER_VIEW, &anything)?; - let child_of_host = |child: usize| match parent { - Some(parent) => memory.word(child + parent) == Some(view), - None => true, - }; - let child = |class: &str| { - fields_naming(memory, layout, LAYOUT_REACH, class, &child_of_host) - .map_or_else(Vec::new, |(fields, _)| fields) - }; - Some(LayoutFields { - host, - page_area: child(MAIN_BACKGROUND_REGION), - contents: child(MULTI_CONTENTS), - }) -} - -/// The fields of the frame view at `frame` that hold its browser view. When the layout already -/// gave the browser view, the field must hold that one; otherwise every view in the browser view's +/// The fields of the frame view at `frame` that hold its browser view. When the browser view is +/// already known, the field must hold that one; otherwise every view in the browser view's /// own list of children must name it as their parent, which tells a view's own address from a /// pointer into another part of the object. pub(crate) fn frame_fields( @@ -341,23 +295,8 @@ impl Slot { } } } - - fn known(&self, row: Option) -> Option { - match self - .value - .lock() - .unwrap_or_else(|error| error.into_inner()) - .0 - { - Settled::Known(known) => known, - Settled::Unknown => row, - } - } } -static HOST: Slot = Slot::new(); -static PAGE_AREA: Slot = Slot::new(); -static CONTENTS: Slot = Slot::new(); static FRAME: Slot = Slot::new(); /// A row value that is recorded: an offset the build has, not the absent marker. @@ -365,51 +304,7 @@ fn recorded(value: Option) -> Option { value.filter(|value| *value != crate::builds::ABSENT) } -fn side_panel_row() -> &'static crate::builds::SidePanel { - &crate::builds::get().side_panel -} - -/// Settles the view fields of the browser layout object at `layout`, which the layout hook hands -/// over, and returns the field that holds the view it lays out. Reads memory only. -pub(crate) unsafe fn host_field(layout: usize) -> Option { - let row = side_panel_row(); - let mut found: Option = None; - let mut fields = || { - if found.is_none() { - found = live().and_then(|live| layout_fields(live, layout, parent_field())); - } - found.clone() - }; - let host = HOST.get(recorded(row.host_view), || fields().map(|found| found.host)); - PAGE_AREA.get(recorded(row.page_area), || { - fields() - .map(|found| found.page_area) - .filter(|fields| !fields.is_empty()) - }); - CONTENTS.get(recorded(row.contents_container), || { - fields() - .map(|found| found.contents) - .filter(|fields| !fields.is_empty()) - }); - host -} - -/// The layout object's field that holds the area below the top row, or `ABSENT`. -pub(crate) fn page_area_field() -> usize { - PAGE_AREA - .known(recorded(side_panel_row().page_area)) - .unwrap_or(crate::builds::ABSENT) -} - -/// The layout object's field that holds the view of the pages, or `ABSENT`. -pub(crate) fn contents_field() -> usize { - CONTENTS - .known(recorded(side_panel_row().contents_container)) - .unwrap_or(crate::builds::ABSENT) -} - -/// The browser view the frame view at `frame` holds, the same view the browser's layout lays out. -/// `host` is that view when the layout already ran for the window. +/// The browser view the frame view at `frame` holds. `host` is that view when it is already known. pub(crate) unsafe fn frame_browser_view(frame: usize, host: Option) -> Option { let row = recorded(crate::builds::get().layout.frame_browser_window_offset); let field = FRAME.get(row, || { @@ -418,6 +313,31 @@ pub(crate) unsafe fn frame_browser_view(frame: usize, host: Option) -> Op live()?.word(frame + field).filter(|view| *view != 0) } +/// The frame view of `window`, from its live view tree: the browser view the view walk reaches from +/// the window's own `HWNDMessageHandler`, and the sibling of it that is named as a frame view. Only a +/// walk that already ran for this build is followed, so no caller pays the walk's budget. Reads +/// memory only. +pub(crate) unsafe fn frame_view_of(window: windows_sys::Win32::Foundation::HWND) -> Option { + use windows_sys::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, GWLP_USERDATA}; + let (live, build) = (live()?, fingerprint()?); + crate::chromium::reflect::walked_fields(build)?; + let handler = GetWindowLongPtrW(window, GWLP_USERDATA) as usize; + let (found, _) = crate::chromium::reflect::find_cached( + &live.ranges, + handler, + std::time::Duration::ZERO, + build, + ) + .ok()?; + crate::chromium::live_tables::frame_view(live, found.browser_view?, found.parent) +} + +/// The browser view the frame view of `window` holds, found from the live view tree as +/// `frame_view_of` finds the frame view. +pub(crate) unsafe fn browser_view_of(window: windows_sys::Win32::Foundation::HWND) -> Option { + frame_browser_view(frame_view_of(window)?, None) +} + /// Starts the view walk of `reflect` from `window`'s own `HWNDMessageHandler`, once per process, on /// a worker thread: it only reads memory, and its result is kept by build fingerprint for /// `walked_view_fields`. @@ -643,42 +563,6 @@ mod tests { memory } - #[test] - fn nfr6_the_side_panel_views_are_found_by_class_name() { - // Chrome 157 keeps them at 0x38, 0x50 and 0xb8; Edge has its own fields between them. - for (host, page_area, contents) in [(0x38, 0x50, 0xB8), (0x38, 0x58, 0xD8)] { - let memory = window(host, page_area, contents); - let fields = layout_fields(&memory, LAYOUT, Some(PARENT)).expect("a browser view"); - assert_eq!(fields.host, [host]); - assert_eq!(fields.page_area, [page_area]); - assert_eq!(fields.contents, [contents]); - } - } - - #[test] - fn nfr6_a_layout_view_that_is_not_the_browser_views_child_is_not_taken() { - let mut memory = window(0x38, 0x50, 0xB8); - memory.set(CONTENTS + PARENT, OTHER); - let fields = layout_fields(&memory, LAYOUT, Some(PARENT)).unwrap(); - assert!(fields.contents.is_empty()); - assert_eq!(fields.page_area, [0x50]); - // A layout with no browser view has no fields at all. - let mut bare = Words::default(); - bare.set(LAYOUT + 0x38, PAGE_AREA); - bare.name(PAGE_AREA, "MainBackgroundRegionView"); - assert_eq!(layout_fields(&bare, LAYOUT, Some(PARENT)), None); - } - - #[test] - fn nfr6_two_different_views_of_one_class_leave_the_field_unknown() { - let mut memory = window(0x38, 0x50, 0xB8); - memory.set(LAYOUT + 0x100, OTHER); - memory.name(OTHER, "MultiContentsView"); - memory.set(OTHER + PARENT, BROWSER); - let fields = layout_fields(&memory, LAYOUT, Some(PARENT)).unwrap(); - assert!(fields.contents.is_empty()); - } - #[test] fn nfr6_the_frame_view_field_is_the_one_holding_the_browser_view() { let memory = window(0x38, 0x50, 0xB8); diff --git a/rivet/runtime/windows/src/feature.rs b/rivet/runtime/windows/src/feature.rs index 902925e..ae858d0 100644 --- a/rivet/runtime/windows/src/feature.rs +++ b/rivet/runtime/windows/src/feature.rs @@ -20,12 +20,6 @@ pub(crate) enum Feature { FrameColour, /// Caption buttons are painted in the window's colours. CaptionPaint, - /// Caption buttons sit in the panel's top row. - CaptionLayout, - /// The height of the top row. - CaptionHeight, - /// The space above the top row. - TopInset, /// Pages of a split view are panels. Split, /// The layout of the pages of a split view. @@ -38,9 +32,6 @@ impl Feature { Feature::FrameLayout => "frame_layout", Feature::FrameColour => "frame_colour", Feature::CaptionPaint => "caption_paint", - Feature::CaptionLayout => "caption_layout", - Feature::CaptionHeight => "caption_height", - Feature::TopInset => "top_inset", Feature::Split => "split", Feature::SplitLayout => "split_layout", } @@ -351,13 +342,12 @@ mod tests { type NeedsOf = fn(&Build) -> Needs; - fn all_needs() -> [(Feature, NeedsOf); 5] { + fn all_needs() -> [(Feature, NeedsOf); 4] { use crate::features::{frame_layout, split}; [ (Feature::FrameLayout, frame_layout::needs_layout), (Feature::FrameColour, frame_layout::needs_colour), (Feature::CaptionPaint, frame_layout::needs_caption_paint), - (Feature::CaptionLayout, frame_layout::needs_caption_layout), (Feature::Split, split::needs), ] } @@ -373,31 +363,16 @@ mod tests { /// What each row offers, as the attach of that browser was seen to install it. #[test] fn nfr3_each_row_offers_the_features_its_browser_installs() { - let chromium = [ - "frame_layout", - "frame_colour", - "caption_paint", - "caption_layout", - "split", - ]; + let chromium = ["frame_layout", "frame_colour", "caption_paint", "split"]; assert_eq!(names(&builds::CHROME), chromium); assert_eq!( names(&builds::BRAVE), - [ - "frame_layout", - "caption_paint", - "caption_layout" - ] + ["frame_layout", "caption_paint"] ); assert_eq!(names(&builds::EDGE), chromium); assert_eq!( names(&builds::CHROME_150), - [ - "frame_layout", - "frame_colour", - "caption_paint", - "caption_layout" - ] + ["frame_layout", "frame_colour", "caption_paint"] ); assert_eq!(names(&builds::WHALE), ["frame_layout", "frame_colour"]); assert_eq!(names(&builds::SAMSUNG), ["frame_layout"]); @@ -445,7 +420,7 @@ mod tests { OnFailure::Abort, ), step( - Feature::CaptionHeight, + Feature::CaptionPaint, left_out, |ran| { let _: () = ran.push("caption"); @@ -465,7 +440,7 @@ mod tests { OnFailure::Continue, ), step( - Feature::TopInset, + Feature::SplitLayout, nothing, |ran| { let _: () = ran.push("inset"); @@ -478,14 +453,14 @@ mod tests { assert!(unsafe { run(&steps, &mut ran, |_| {}) }); assert_eq!(ran, ["layout", "caption", "split", "inset"]); assert_eq!( - outcome(Feature::CaptionHeight), + outcome(Feature::CaptionPaint), Some(Outcome::NotInThisBuild("the row leaves it out".to_owned())) ); assert_eq!( outcome(Feature::Split), Some(Outcome::Failed("it failed".to_owned())) ); - assert_eq!(outcome(Feature::TopInset), Some(Outcome::Installed)); + assert_eq!(outcome(Feature::SplitLayout), Some(Outcome::Installed)); let steps = vec![ step( @@ -500,7 +475,7 @@ mod tests { OnFailure::Abort, ), step( - Feature::CaptionHeight, + Feature::CaptionPaint, nothing, |ran| { let _: () = ran.push("caption"); diff --git a/rivet/runtime/windows/src/features/address_bar.rs b/rivet/runtime/windows/src/features/address_bar.rs index 303b598..a8c37b4 100644 --- a/rivet/runtime/windows/src/features/address_bar.rs +++ b/rivet/runtime/windows/src/features/address_bar.rs @@ -413,116 +413,6 @@ unsafe fn dev_reserve(window: HWND) -> f32 { } } -/// Moves the page below the bar. The browser lays the page out at the top of its panel, since an app -/// window has no toolbar there. -pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { - // The second view moves the page instead where the browser's layout could not be patched. - if !BY_LAYOUT.load(std::sync::atomic::Ordering::Acquire) || !shown_in(area.window) { - return; - } - let row = &crate::builds::get().side_panel; - let Some(contents) = area.contents() else { - crate::trace::trace_changed( - "bar layout", - "address bar: the layout has no page container", - ); - return; - }; - // An app window's top container holds the browser's title row, which Rivet's bar replaces. When - // it sits right on top of the page, the page takes its place and it keeps no height. - if let Some(toolbar) = area - .bounds(row.toolbar) - .filter(|toolbar| *toolbar != contents) - { - let between: Vec<_> = area - .all_bounds() - .into_iter() - .map(|(_, b)| b) - .filter(|b| *b != toolbar && *b != contents) - .collect(); - let views: Vec<[i32; 4]> = between.iter().map(|b| **b).collect(); - if let Some((top, page, moved)) = page_over_top_row(*toolbar, *contents, &views) { - *toolbar = top; - *contents = page; - for (bounds, view) in between.into_iter().zip(moved) { - *bounds = view; - } - } - } - let before = *contents; - // A bar the browser keeps right above the page, like the infobar of a tab, moves down with it. - // Left where it was, it sits under the address bar and leaves an empty strip above the page. - for (_, bounds) in area.all_bounds() { - if bounds != contents && rides_above_page(*bounds, before) { - (*bounds)[1] += ROW_HEIGHT; - } - } - let contents = &mut *contents; - contents[1] += ROW_HEIGHT; - contents[3] = (contents[3] - ROW_HEIGHT).max(1); - crate::trace::trace_changed( - "bar layout", - &format!("address bar: layout page {before:?} to {contents:?}"), - ); -} - -/// The top row, the page and the views that moved with them. -pub(crate) type TopRowMove = ([i32; 4], [i32; 4], Vec<[i32; 4]>); - -/// The top row, the page and the other views after the page takes the place of a top row above -/// it. The row keeps its place with no height. Views between the row and the page, such as an -/// infobar, move up with the page, and the page grows up by the row's height. -pub(crate) fn page_over_top_row( - top: [i32; 4], - contents: [i32; 4], - views: &[[i32; 4]], -) -> Option { - let bottom = top[1] + top[3]; - let across = |v: [i32; 4]| v[0] < contents[0] + contents[2] && v[0] + v[2] > contents[0]; - if top[3] <= 0 || bottom > contents[1] || !across(top) { - return None; - } - let between = - |v: [i32; 4]| v[3] > 0 && v[1] >= bottom && v[1] + v[3] <= contents[1] && across(v); - // The row must reach the page, directly or through the views between them. - let covered = views - .iter() - .filter(|v| between(**v)) - .map(|v| v[3]) - .sum::(); - if bottom + covered != contents[1] { - return None; - } - let shift = top[3]; - let moved = views - .iter() - .map(|v| { - if between(*v) { - [v[0], v[1] - shift, v[2], v[3]] - } else { - *v - } - }) - .collect(); - let [x, y, width, height] = contents; - Some(( - [top[0], top[1], top[2], 0], - [x, y - shift, width, height + shift], - moved, - )) -} - -/// Whether a view the browser laid out sits right on top of the page and across it, so it moves -/// down with the page below the bar. -pub(crate) fn rides_above_page(view: [i32; 4], contents: [i32; 4]) -> bool { - let [x, y, width, height] = view; - height > 0 - && height < contents[3] - && y + height == contents[1] - && x < contents[0] + contents[2] - && x + width > contents[0] -} - /// The active page's title and address. The visible address is what the page shows now, including /// a navigation that has not committed yet. unsafe fn page_text(window: HWND) -> (String, String) { @@ -532,33 +422,14 @@ unsafe fn page_text(window: HWND) -> (String, String) { .unwrap_or_default() } -/// How the page moves below the bar in this build. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum Offset { - /// The browser's own layout of the page area is patched and leaves the bar's row free. - Layout, - /// Rivet's second view keeps the row free by moving the window's page view, which needs no - /// record of the browser's layout object. - PageView, - /// Neither is recorded, so the bar covers the top of the page. - None(String), -} - -/// Picks how the page moves below the bar: the patched layout when it installed, else the page -/// view, which every build that records the second view can move. -pub(crate) fn offset_for(layout: Result<(), String>, second_view: bool) -> Offset { - match layout { - Ok(()) => Offset::Layout, - Err(_) if second_view => Offset::PageView, - Err(error) => Offset::None(error), - } +/// Why the page cannot move below the bar in a build, or nothing when Rivet's second view moves +/// the window's page view there. +pub(crate) fn page_view_missing(second_view: bool) -> Option<&'static str> { + (!second_view).then_some("this browser build records no second view to move the page view") } -/// Set once the patched layout moves the page, so only one mechanism ever leaves the row free. -static BY_LAYOUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Patches the browser's layout of the page area once, then asks the window to lay out again, so the -/// page moves below the bar. A build without the layout's record moves the page view instead. +/// Moves the window's page view below the bar once. A build without the second view keeps the page +/// where the browser put it, and the trace says why. unsafe fn ensure_layout(window: HWND) { thread_local! { static DONE: RefCell> = RefCell::new(std::collections::HashSet::new()); @@ -566,28 +437,13 @@ unsafe fn ensure_layout(window: HWND) { if !DONE.with(|done| done.borrow_mut().insert(window as isize)) { return; } - let installed = crate::hooks::page_area::install_for_app_window(); - let reason = installed.as_ref().err().cloned().unwrap_or_default(); - match offset_for(installed, crate::features::second_view::available()) { - Offset::Layout => { - crate::trace::trace("address bar: the browser's layout moves the page below the bar"); - BY_LAYOUT.store(true, std::sync::atomic::Ordering::Release); - let name: Vec = crate::features::split::RELAYOUT_MESSAGE - .encode_utf16() - .chain(Some(0)) - .collect(); - let message = - windows_sys::Win32::UI::WindowsAndMessaging::RegisterWindowMessageW(name.as_ptr()); - PostMessageW(window, message, 0, 0); - } - Offset::PageView => { - crate::trace::trace(&format!( - "address bar: the page view moves below the bar ({reason})" - )); + match page_view_missing(crate::features::second_view::available()) { + None => { + crate::trace::trace("address bar: the page view moves below the bar"); crate::features::second_view::set_top(window, ROW_HEIGHT); } - Offset::None(error) => crate::trace::trace(&format!( - "address bar: the page cannot move below the bar: {error}" + Some(reason) => crate::trace::trace(&format!( + "address bar: the page cannot move below the bar: {reason}" )), } } @@ -1960,56 +1816,10 @@ mod tests { } #[test] - fn fr12_a_bar_right_above_the_page_moves_below_the_address_bar_with_it() { - // Brave's first tab shows an infobar right above the page. Only the page moved, so the - // infobar sat under the address bar and an empty band of the bar's height was left above - // the page, which put the first pane of a split below the second. - let contents = [0, 56, 1164, 708]; - assert!(rides_above_page([0, 0, 1164, 56], contents)); - // The page itself, a view beside it and a view that ends above it stay. - assert!(!rides_above_page(contents, contents)); - assert!(!rides_above_page([1164, 0, 40, 56], contents)); - assert!(!rides_above_page([0, 0, 1164, 40], contents)); - assert!(!rides_above_page([0, 56, 1164, 0], contents)); - } - - #[test] - fn fr12_page_sits_directly_below_the_bar_where_the_browser_kept_a_title_row() { - // Chrome's app window keeps a 23 DIP top container above the page once its client view - // reaches the window's top edge. Rivet's bar replaces it, so the page takes its place. - let (top, page, _) = page_over_top_row([0, 0, 1164, 23], [0, 23, 1164, 815], &[]).unwrap(); - assert_eq!(top, [0, 0, 1164, 0]); - assert_eq!(page, [0, 0, 1164, 838]); - // A top row that does not reach the page is left alone. - assert_eq!( - page_over_top_row([0, 0, 1164, 20], [0, 23, 1164, 815], &[]), - None - ); - // Brave's notice bar between the row and the page moves up with the page. - let (_, page, moved) = page_over_top_row( - [0, 0, 1164, 23], - [0, 79, 1164, 759], - &[[0, 23, 1164, 56], [1164, 0, 40, 9]], - ) - .unwrap(); - assert_eq!(page, [0, 56, 1164, 782]); - assert_eq!(moved, vec![[0, 0, 1164, 56], [1164, 0, 40, 9]]); - } - - #[test] - fn fr12_the_page_moves_below_the_bar_without_a_sidebar_layout_row() { - // Edge 156.0.4314.58 and Whale 5.39.412.57 record no Sidebar layout, but both record the - // second view, which moves the page view itself. - let missing = - || Err("this browser build has no recorded layout for the Sidebar".to_string()); - assert_eq!(offset_for(missing(), true), Offset::PageView); - assert_eq!( - offset_for(Ok(()), true), - Offset::Layout, - "a patched layout is used first" - ); - assert_eq!(offset_for(Ok(()), false), Offset::Layout); - assert!(matches!(offset_for(missing(), false), Offset::None(_))); + fn fr12_the_page_moves_below_the_bar_only_by_its_page_view() { + // The browser's layout is never patched, so the second view is the only way down. + assert_eq!(page_view_missing(true), None); + assert!(page_view_missing(false).is_some_and(|reason| reason.contains("second view"))); } #[test] diff --git a/rivet/runtime/windows/src/features/bubble_anchor.rs b/rivet/runtime/windows/src/features/bubble_anchor.rs index 8773090..ddd2060 100644 --- a/rivet/runtime/windows/src/features/bubble_anchor.rs +++ b/rivet/runtime/windows/src/features/bubble_anchor.rs @@ -340,7 +340,7 @@ unsafe extern "system" fn get_anchor_rect( crate::frame::layout_dpi(window) )); // Where Chromium itself puts the same rows, beside the place derived from the monitor. - let view = crate::features::frame_layout::frame_view(window).unwrap_or(0); + let view = crate::chromium::window_views::frame_view_of(window).unwrap_or(0); let own = crate::chromium::screen::origin(view).map(|origin| { let own = client.map(|rect| at_origin(origin, rect)); let off = largest_difference(&own, &[page, address, chip]); diff --git a/rivet/runtime/windows/src/features/dev_page.rs b/rivet/runtime/windows/src/features/dev_page.rs index 084df23..4e41e2d 100644 --- a/rivet/runtime/windows/src/features/dev_page.rs +++ b/rivet/runtime/windows/src/features/dev_page.rs @@ -39,7 +39,6 @@ pub(crate) unsafe fn toggle_dev_mode(window: HWND) -> bool { "developer mode of window {:#x} is {on}", window as usize )); - crate::hooks::page_area::relayout(window); windows_sys::Win32::Graphics::Gdi::InvalidateRect(window, std::ptr::null(), 0); crate::frame::update_appbar(window); true diff --git a/rivet/runtime/windows/src/features/frame_layout.rs b/rivet/runtime/windows/src/features/frame_layout.rs index 06fd4b5..5c1131a 100644 --- a/rivet/runtime/windows/src/features/frame_layout.rs +++ b/rivet/runtime/windows/src/features/frame_layout.rs @@ -1,12 +1,11 @@ -//! Makes Chromium's own frame layout leave room for the Rivet appbar. +//! The panel of a Rivet window and the frame view functions it needs from the browser. //! -//! Chromium's Windows browser frame asks its frame view where the client view goes. Rivet -//! replaces that one virtual function in the frame view's vtable. For windows that carry a Rivet -//! appbar it moves the client view right by the appbar width. Chromium then lays out, paints, -//! hit-tests and positions menus, IME windows and accessibility bounds for the narrower view -//! itself, so nothing has to be translated after the fact. +//! Rivet leaves Chromium's own frame layout alone. It works out the page panel of each window from +//! the window's client area and the appbar's width, and records it here for every surface that +//! sits on the panel. The frame view's functions are only found, so a view's window can be told, +//! and the frame paint takes the window's colours. //! -//! The vtable layout is private to each Chromium build. Rivet only patches builds whose module +//! The vtable layout is private to each Chromium build. Rivet only attaches to builds whose module //! contents match an entry of the supported-build table exactly, and leaves every other build //! untouched. @@ -93,42 +92,6 @@ pub(crate) fn needs_caption_paint(build: &Build) -> Needs { ) } -/// What the place of the caption buttons needs from the browser. -pub(crate) fn needs_caption_layout(build: &Build) -> Needs { - let row = &build.layout; - Needs::targets(vec![ - Target::new("frame view layout", row.layout, row.layout_prologue), - Target::new( - "set bounds rect", - row.set_bounds_rect, - row.set_bounds_rect_prologue, - ), - Target::new("set paint to layer", row.set_layer, row.set_layer_prologue), - Target::new( - "set rounded corners", - row.set_radius, - row.set_radius_prologue, - ), - Target::new("set masks", row.set_masks, row.set_masks_prologue), - Target::new("stack at top", row.stack_at_top, row.stack_at_top_prologue), - Target::new("set opaque", row.set_opaque, row.set_opaque_prologue), - ]) -} - -/// What the height of the caption buttons needs from the browser. -pub(crate) fn needs_caption_height(build: &Build) -> Needs { - Needs::targets(vec![Target::new( - "caption button size", - build.layout.caption_size, - &[], - )]) -} - -/// What the space above the top row needs from the browser. -pub(crate) fn needs_top_inset(build: &Build) -> Needs { - Needs::targets(vec![Target::new("top inset", build.layout.top_inset, &[])]) -} - /// The frame view's class table: the row's, read again from the window's live frame view. fn frame_table() -> usize { use crate::chromium::live_tables; @@ -147,15 +110,6 @@ fn corner_table() -> usize { live_tables::table(bv().corner_vtable, live_tables::found().corner) } -/// The browser view's class table, settled with the live browser view's as `frame_table` is. -fn browser_view_table() -> usize { - use crate::chromium::live_tables; - live_tables::table( - bv().browser_view_view_vtable, - live_tables::found().browser_view, - ) -} - fn recorded_image() -> Result { image::recorded().ok_or_else(|| "this browser build is not supported yet".to_owned()) } @@ -203,9 +157,6 @@ pub fn reserve_leading(bounds: Rect, reserved: i32) -> Rect { } } -/// Experiment: whether the page is laid out as the shell study's panel, below a taller top row -/// and inside a gap on the right and the bottom. -pub static PANEL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// How much taller the top row is than the browser's title bar, and the gap, in DIPs. pub const PANEL_TOP: i32 = 12; pub const PANEL_GAP: i32 = 8; @@ -219,9 +170,9 @@ fn inset_panel(bounds: Rect) -> Rect { } } -/// The panel of a Rivet window from the client view bounds the browser chose. The browser keeps a -/// title bar above its client view, which a Rivet window does not have: Rivet's bar is the -/// panel's own top row. So the client view reaches the window's top edge before the gap is taken. +/// The panel of a Rivet window from the client view bounds. The browser keeps a title bar above its +/// client view, which a Rivet window does not have: Rivet's bar is the panel's own top row. So the +/// client view reaches the window's top edge before the gap is taken. fn panel_from_client(bounds: Rect) -> Rect { inset_panel(lifted_client(bounds)) } @@ -235,41 +186,10 @@ fn lifted_client(bounds: Rect) -> Rect { } } -/// The one offset in `fields` that holds `wanted`, read as rects at 4 byte steps. None when no -/// field or more than one holds it, since then the cached area cannot be told apart. -fn sole_rect_offset(fields: &[i32], wanted: Rect) -> Option { - let wanted = [wanted.x, wanted.y, wanted.width, wanted.height]; - let mut found = (0..fields.len().saturating_sub(3)).filter(|at| fields[*at..*at + 4] == wanted); - let first = found.next()?; - found.next().is_none().then_some(first * 4) -} - -/// Chromium's frame view keeps the client area it laid out and hands it to the browser view's -/// layout as the visual client area, which must contain the browser view. Rivet lifts the client -/// view to the window's top edge, so the kept area is lifted with it, or the browser stops on that -/// check. The area is the frame view's one field equal to the bounds it reported. -unsafe fn lift_cached_client_area(view: *const c_void, browser_chose: Rect) { - const SPAN: usize = 0x500; - if browser_chose.y <= 0 || !crate::chromium::memory::readable(view as usize, SPAN) { - return; - } - let fields = std::slice::from_raw_parts(view.cast::(), SPAN / 4); - if let Some(offset) = sole_rect_offset(fields, browser_chose) { - *(view.cast::().add(offset) as *mut Rect) = lifted_client(browser_chose); - } -} - -type ClientViewBounds = unsafe extern "system" fn(*const c_void, *mut Rect) -> *mut Rect; type HwndForView = unsafe extern "system" fn(*const c_void) -> HWND; -/// Decides the width to reserve for a window from the client-view bounds the browser chose, or -/// returns `None` when the window carries no Rivet appbar. -pub type Reserve = fn(HWND, Rect) -> Option; - struct Hook { - original: ClientViewBounds, hwnd_for_view: HwndForView, - reserved: Reserve, } static HOOK: OnceLock> = OnceLock::new(); @@ -481,42 +401,10 @@ pub unsafe fn install_frame_paint(paint: Paint) -> Result<(), String> { /// Decides the title bar colour of a window as `0xAARRGGBB`, or `None` to keep the browser's. pub type Paint = fn(HWND) -> Option; -unsafe extern "system" fn client_view_bounds(view: *const c_void, out: *mut Rect) -> *mut Rect { - let Some(Ok(hook)) = HOOK.get() else { - unreachable!("the vtable is only patched after the hook is stored"); - }; - let result = (hook.original)(view, out); - if let Some(reserved) = (hook.reserved)((hook.hwnd_for_view)(view), *out) { - let browser_chose = *out; - *out = reserve_leading(*out, reserved); - if PANEL.load(std::sync::atomic::Ordering::Relaxed) { - *out = panel_from_client(*out); - lift_cached_client_area(view, browser_chose); - } - let window = (hook.hwnd_for_view)(view); - // With the client area shrunk by Windows, Rivet still draws in the coordinates of the - // whole window, so the panel it records moves back by the inset. - let shift = crate::frame::client_inset_dips(window); - let recorded = shifted(*out, shift); - if shift != [0, 0] { - crate::trace::trace_changed( - "experiment client view", - &format!( - "experiment client area: the browser chose client view {browser_chose:?}, \ - panel {:?} in the client, {recorded:?} in the window", - *out - ), - ); - } - record_panel(window, recorded); - } - result -} - -/// The page panel each window's browser last laid out, in device-independent pixels of the frame +/// The page panel Rivet last placed for each window, in device-independent pixels of the frame /// view. Rivet cuts its ground's hole to exactly this. static PANELS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); -/// Called with a window whose panel changed, from inside the browser's layout. +/// Called with a window whose panel changed. static PANEL_CHANGED: OnceLock = OnceLock::new(); pub fn on_panel_change(notify: fn(HWND)) { @@ -539,27 +427,18 @@ fn record_panel(window: HWND, panel: Rect) { } } -/// `bounds` moved by `shift` DIPs. -fn shifted(bounds: Rect, shift: [i32; 2]) -> Rect { - Rect { - x: bounds.x + shift[0], - y: bounds.y + shift[1], - ..bounds - } -} - -/// The panel of a Rivet window from its client area alone, as the browser's layout would place it -/// with the client view hook: `reserved` DIPs at the left, then the panel's gap. +/// The panel of a Rivet window from its client area alone: `reserved` DIPs at the left, then the +/// panel's gap. pub fn rivet_panel(client: Rect, reserved: i32) -> Rect { panel_from_client(reserve_leading(client, reserved)) } -/// Records a panel Rivet placed itself, where the browser's layout is not hooked. +/// Records a panel Rivet placed. pub fn place_panel(window: HWND, panel: Rect) { record_panel(window, panel); } -/// The page panel the browser laid out for a window, once it has laid the window out. +/// The page panel Rivet placed for a window, once it has placed one. pub fn panel_bounds(window: HWND) -> Option { PANELS .lock() @@ -569,25 +448,17 @@ pub fn panel_bounds(window: HWND) -> Option { .map(|entry| entry.1) } -/// Installs the layout hook once per browser process. Returns why it cannot when the build is +/// Finds the build's frame view functions once per browser process, so a view's window can be +/// told. The client view placement stays the browser's. Returns why it cannot when the build is /// not recognised, so Rivet refuses to attach rather than guess. -pub unsafe fn install(reserved: Reserve) -> Result<(), String> { - HOOK.get_or_init(|| patch(reserved, true)) +pub unsafe fn install() -> Result<(), String> { + HOOK.get_or_init(|| find()) .as_ref() .map(|_| ()) .map_err(Clone::clone) } -/// Experiment: finds the build's frame view functions as `install` does, so a view's window can be -/// told, but leaves the client view placement to the browser. Rivet then places the panel itself. -pub unsafe fn install_unpatched(reserved: Reserve) -> Result<(), String> { - HOOK.get_or_init(|| patch(reserved, false)) - .as_ref() - .map(|_| ()) - .map_err(Clone::clone) -} - -unsafe fn patch(reserved: Reserve, replace_slot: bool) -> Result { +unsafe fn find() -> Result { log(&format!("rivet: {}", crate::builds::table_note())); crate::trace::trace(&format!("build table: {}", crate::builds::table_note())); let (build, image) = crate::builds::frame_rows() @@ -600,39 +471,15 @@ unsafe fn patch(reserved: Reserve, replace_slot: bool) -> Result { matches(&image, build).then_some((build, image)) }) .ok_or("this browser build is not supported yet")?; - let base = image.base; - let slot_rva = build.frame_view_vtable as usize + build.client_view_slot as usize * 8; - let slot = image - .at(slot_rva, 8) - .ok_or("recorded slot outside the image")? as *mut usize; - let hook = Hook { - original: std::mem::transmute::(slot.read()), - hwnd_for_view: std::mem::transmute::( - base + build.hwnd_for_view as usize, - ), - reserved, - }; - if !replace_slot { - log(&format!( - "rivet: {} {} keeps its own client view placement", - build.browser, build.version - )); - crate::trace::trace("experiment page view only: the client view placement is not replaced"); - return Ok(hook); - } - // Layout runs on this UI thread only, so no call can reach the new slot before HOOK holds - // this value. - let mut previous: PAGE_PROTECTION_FLAGS = 0; - if VirtualProtect(slot.cast(), 8, PAGE_READWRITE, &mut previous) == 0 { - return Err("could not unprotect the frame view vtable".into()); - } - slot.write(client_view_bounds as *const () as usize); - VirtualProtect(slot.cast(), 8, previous, &mut previous); log(&format!( - "rivet: laying out {} {}", + "rivet: attaching to {} {}, which keeps its own client view placement", build.browser, build.version )); - Ok(hook) + Ok(Hook { + hwnd_for_view: std::mem::transmute::( + image.base + build.hwnd_for_view as usize, + ), + }) } fn wide(value: &str) -> Vec { @@ -644,8 +491,9 @@ fn log(message: &str) { unsafe { windows_sys::Win32::System::Diagnostics::Debug::OutputDebugStringW(text.as_ptr()) }; } -/// Checks that the loaded module is the recorded build: the vtable slot must still point at the -/// recorded function, and the helper must start with the recorded instructions. +/// Checks that the loaded module is the recorded build: the frame view's client view slot must +/// still point at the recorded function, and the helper must start with the recorded +/// instructions. unsafe fn matches(image: &Image, build: &ChromeBuild) -> bool { let Some(expected) = chrome_build::hex(&build.hwnd_for_view_prologue) else { return false; @@ -668,43 +516,6 @@ fn parse_version(text: &str) -> Option<[u16; 4]> { mod tests { use super::*; - #[test] - fn fr12_native_caption_buttons_give_way_to_rivets_own() { - // The container keeps its right edge but has no size, so nothing of it paints or answers. - assert_eq!(hidden_caption_bounds([900, 0, 138, 32]), [1038, 0, 0, 0]); - } - - #[test] - fn fr12_top_inset_is_the_panel_gap_for_rivet_windows_only() { - // Chrome, Brave, Whale, Samsung and Edge each answer differently; a Rivet window always - // gets the panel's top gap, so the bar sits at the same place on every browser. - for original in [6, 26, 32, 41] { - assert_eq!(panel_top_inset(original, Some(PANEL_GAP)), PANEL_GAP); - } - // Another window of the same browser keeps the browser's answer. - assert_eq!(panel_top_inset(6, None), 6); - } - - #[test] - fn fr12_lifted_panel_keeps_the_browser_view_inside_the_kept_client_area() { - // Chromium checks that its kept client area contains the browser view, so the area is - // lifted with the panel and found only where a single field holds it. - let chose = Rect { - x: 0, - y: 30, - width: 1600, - height: 970, - }; - let mut fields = vec![0i32; 64]; - fields[20..24].copy_from_slice(&[0, 30, 1600, 970]); - assert_eq!(sole_rect_offset(&fields, chose), Some(80)); - let lifted = lifted_client(chose); - let panel = panel_from_client(reserve_leading(chose, 268)); - assert!(lifted.y <= panel.y && panel.y + panel.height <= lifted.y + lifted.height); - fields[40..44].copy_from_slice(&[0, 30, 1600, 970]); - assert_eq!(sole_rect_offset(&fields, chose), None); - } - #[test] fn fr12_panel_starts_at_the_mockup_top_inset() { // Whatever top the browser kept for its title bar, the panel starts one gap below the @@ -729,9 +540,9 @@ mod tests { } #[test] - fn fr12_panel_placed_by_rivet_matches_the_hooked_layout() { - // The browser's client view reaches the window's top edge once lifted, so the panel Rivet - // works out from the client area is the one the hook makes of any title row height. + fn fr12_panel_placed_by_rivet_ignores_the_browsers_title_row() { + // The client view reaches the window's top edge once lifted, so the panel Rivet works out + // from the client area is the same for any title row height the browser keeps. let client = Rect { x: 0, y: 0, @@ -760,35 +571,11 @@ mod tests { ); } - #[test] - fn fr2_panel_in_a_shrunk_client_area_is_recorded_in_window_coordinates() { - let panel = Rect { - x: 0, - y: 8, - width: 1324, - height: 984, - }; - assert_eq!(shifted(panel, [0, 0]), panel); - assert_eq!( - shifted(panel, [268, 52]), - Rect { - x: 268, - y: 60, - ..panel - } - ); - } - #[test] fn fr12_caption_ink_is_independent_of_window_activation() { assert_eq!(caption_ink(), 0xff1a_1a1a); } - #[test] - fn fr2_panel_clips_each_corner_at_twelve_dips() { - assert_eq!(panel_radii(), [12.0; 4]); - } - #[test] fn fr12_panel_reserves_the_frame_gap() { assert_eq!( @@ -838,12 +625,6 @@ mod tests { } } -type PreferredSize = - unsafe extern "system" fn(*const c_void, *mut [i32; 2], *const c_void) -> *mut [i32; 2]; -/// Decides the caption button height of a window in DIPs, or `None` to keep the browser's. -pub type CaptionHeight = fn(HWND) -> Option; -static CAPTION: OnceLock<(PreferredSize, CaptionHeight)> = OnceLock::new(); - static CAPTION_PAINT_HOOK: OnceLock<(OnPaint, GetProvider)> = OnceLock::new(); fn caption_ink() -> u32 { @@ -915,193 +696,7 @@ pub unsafe fn install_caption_paint() -> Result<(), String> { ) } -unsafe extern "system" fn caption_size( - button: *const c_void, - out: *mut [i32; 2], - bounds: *const c_void, -) -> *mut [i32; 2] { - let (original, height) = CAPTION.get().expect("patched after it is stored"); - let result = original(button, out, bounds); - if let Some(Ok(hook)) = HOOK.get() { - if let Some(height) = height((hook.hwnd_for_view)(button)) { - (*out)[1] = height; - } - } - result -} - -pub unsafe fn install_caption_height(height: CaptionHeight) -> Result<(), String> { - if CAPTION.get().is_some() { - return Ok(()); - } - let image = recorded_image()?; - let slot_rva = caption_table() + bv().caption_size_slot * 8; - if !image.points_to(slot_rva, bv().caption_size) { - return Err("this browser build has no recorded caption button size".into()); - } - let _ = CAPTION.set(( - std::mem::transmute::(image.base + bv().caption_size), - height, - )); - replace_vtable_slot( - &image, - slot_rva, - bv().caption_size, - caption_size as *const () as usize, - "caption button vtable", - ) -} - -type TopInset = unsafe extern "system" fn(*const c_void, bool) -> i32; -/// Extra title bar height in DIPs for a window, or `None` to keep the browser's. -pub type ExtraTop = fn(HWND) -> Option; -static TOP: OnceLock<(TopInset, ExtraTop)> = OnceLock::new(); - -unsafe extern "system" fn top_inset(view: *const c_void, restored: bool) -> i32 { - let (original, extra) = TOP.get().expect("patched after it is stored"); - let inset = original(view, restored); - if crate::trace::tracing() { - crate::trace::trace(&format!("top inset original {inset} restored {restored}")); - } - match HOOK.get() { - Some(Ok(hook)) => panel_top_inset(inset, extra((hook.hwnd_for_view)(view))), - _ => inset, - } -} - -/// The top inset of a window: the browser's own, or for a Rivet window the top of its panel. Each -/// browser keeps a title bar of its own height, so a Rivet window takes a fixed value instead of -/// adding to it, and the browser's top elements begin at the panel's top edge. -fn panel_top_inset(original: i32, target: Option) -> i32 { - target.unwrap_or(original) -} - -pub unsafe fn install_top_inset(extra: ExtraTop) -> Result<(), String> { - if TOP.get().is_some() { - return Ok(()); - } - let image = recorded_image()?; - let slot_rva = frame_table() + bv().top_inset_slot * 8; - if !image.points_to(slot_rva, bv().top_inset) { - return Err("this browser build has no recorded top inset".into()); - } - let _ = TOP.set(( - std::mem::transmute::(image.base + bv().top_inset), - extra, - )); - replace_vtable_slot( - &image, - slot_rva, - bv().top_inset, - top_inset as *const () as usize, - "frame view vtable", - ) -} - -type Layout = unsafe extern "system" fn(*mut c_void); -type SetBoundsRect = unsafe extern "system" fn(*mut c_void, *const [i32; 4]); -static LAYOUT_HOOK: OnceLock<(Layout, SetBoundsRect, CaptionHeight)> = OnceLock::new(); -type SetPaintToLayer = unsafe extern "system" fn(*mut c_void, i32); -type SetRadius = unsafe extern "system" fn(*mut c_void, *const [f32; 4]); -type SetMasks = unsafe extern "system" fn(*mut c_void, bool); -type StackAtTop = unsafe extern "system" fn(*mut c_void, *mut c_void); -type SetOpaque = unsafe extern "system" fn(*mut c_void, bool); -static SET_OPAQUE: OnceLock = OnceLock::new(); -static STACK_AT_TOP: OnceLock = OnceLock::new(); -static PANEL_LAYER: OnceLock<(SetPaintToLayer, SetRadius, SetMasks)> = OnceLock::new(); - -fn panel_radii() -> [f32; 4] { - [12.0; 4] -} - -unsafe fn clip_panel(frame: *mut c_void) { - let Some((set_layer, set_radius, set_masks)) = PANEL_LAYER.get() else { - return; - }; - // The frame view keeps BrowserView's BrowserWindow subobject in its tracker of the browser view. - let Some(browser_window) = - crate::chromium::window_views::frame_browser_view(frame as usize, None) - .map(|view| view as *mut u8) - else { - return; - }; - let browser = browser_window - .sub(bv().browser_window_in_view) - .cast::(); - let Some(image) = image::recorded() else { - return; - }; - let base = image.base; - let Some(index) = (0..0x100).find(|index| *browser.add(*index) == base + browser_view_table()) - else { - return; - }; - let view = browser.add(index).cast::(); - // `views::View` keeps its `ui::Layer` at +0x20. - let layer_of = || *(view.cast::().add(0x20) as *const *mut c_void); - if layer_of().is_null() { - set_layer(view, 1); - } - let layer = layer_of(); - if !layer.is_null() { - set_masks(layer, true); - set_radius(layer, &panel_radii()); - } -} - -/// Gives `view` its own layer and stacks it above its siblings' layers, so it paints over a -/// sibling it overlaps, such as the page. Views order layers by tree position, so a later layout -/// can undo it and the caller repeats it after each layout. -pub unsafe fn raise_view(view: *mut c_void) { - let Some((set_layer, _, _)) = PANEL_LAYER.get() else { - if crate::features::layout_experiments::page_view_only() { - crate::trace::trace_changed( - "experiment raise", - "experiment page view only: no layer helpers, the side panel is not raised", - ); - } - return; - }; - let Some(stack_at_top) = STACK_AT_TOP.get() else { - return; - }; - let layer_of = || *(view.cast::().add(0x20) as *const *mut c_void); - if layer_of().is_null() { - set_layer(view, 1); - } - let layer = layer_of(); - if layer.is_null() { - return; - } - let parent = *(layer.cast::().add(0x20) as *const *mut c_void); - if !parent.is_null() { - stack_at_top(parent, layer); - } -} - -/// The native caption container of a Rivet window: no size, at its right edge. Rivet draws its own -/// minimize, maximize and close buttons in its bar, so the browser's must neither paint over the -/// panel nor take clicks. -fn hidden_caption_bounds(bounds: [i32; 4]) -> [i32; 4] { - [bounds[0] + bounds[2], 0, 0, 0] -} - -/// The frame view each window last laid out, so Rivet can ask for a layout when the space it -/// reserves changes. Chromium only lays out again on its own when the window's size changes, and -/// a maximized window cannot be resized to make it. -static FRAME_VIEWS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -fn remember_view(window: HWND, view: *mut c_void) { - let mut views = FRAME_VIEWS - .lock() - .unwrap_or_else(|error| error.into_inner()); - match views.iter_mut().find(|entry| entry.0 == window as isize) { - Some(entry) => entry.1 = view as usize, - None => views.push((window as isize, view as usize)), - } -} - -/// The window a view belongs to, once the layout hook is installed. +/// The window a view belongs to, once the frame view's functions are found. pub unsafe fn hwnd_of_view(view: *const c_void) -> Option { match HOOK.get() { Some(Ok(hook)) => Some((hook.hwnd_for_view)(view)), @@ -1109,125 +704,12 @@ pub unsafe fn hwnd_of_view(view: *const c_void) -> Option { } } -/// The frame view a window last laid out, if any. -pub fn frame_view(window: HWND) -> Option { - FRAME_VIEWS - .lock() - .unwrap_or_else(|error| error.into_inner()) - .iter() - .find(|entry| entry.0 == window as isize) - .map(|entry| entry.1) -} - -/// Forgets a window that is going away, so its view is never used again. +/// Forgets a window that is going away, so its panel is never used again. pub fn forget_view(window: HWND) { PANELS .lock() .unwrap_or_else(|error| error.into_inner()) .retain(|entry| entry.0 != window as isize); - FRAME_VIEWS - .lock() - .unwrap_or_else(|error| error.into_inner()) - .retain(|entry| entry.0 != window as isize); -} - -/// Lays the window's frame out again. Returns false when the window has not been laid out yet. -pub unsafe fn relayout(window: HWND) -> bool { - let view = FRAME_VIEWS - .lock() - .unwrap_or_else(|error| error.into_inner()) - .iter() - .find(|entry| entry.0 == window as isize) - .map(|entry| entry.1); - match view { - Some(view) => { - let Some(image) = image::recorded() else { - return false; - }; - let base = image.base; - // `views::View::DeprecatedLayoutImmediately` does the bookkeeping around a layout - // and then runs the view's own `Layout`, which is this hook. The wanted bytes are - // its first instructions in this build. - if !image.has(bv().layout_immediately, bv().layout_immediately_prologue) { - return false; - } - let layout_immediately: unsafe extern "system" fn(*mut c_void) = - std::mem::transmute(base + bv().layout_immediately); - layout_immediately(view as *mut c_void); - true - } - None => false, - } -} - -unsafe extern "system" fn frame_layout(view: *mut c_void) { - let (original, set_bounds, height) = LAYOUT_HOOK.get().expect("patched after it is stored"); - original(view); - crate::features::second_view::note_layout(); - let Some(Ok(hook)) = HOOK.get() else { return }; - remember_view((hook.hwnd_for_view)(view), view); - if height((hook.hwnd_for_view)(view)).is_none() { - return; - } - clip_panel(view); - let container = *(view.cast::().add(bv().caption_container_offset) as *const *mut c_void); - if container.is_null() { - return; - } - let bounds = *(container.cast::().add(bv().view_bounds_offset) as *const [i32; 4]); - let wanted = hidden_caption_bounds(bounds); - if wanted != bounds { - set_bounds(container, &wanted); - } -} - -/// Makes the caption button container of a window reach `height` DIPs from the top of the frame. -pub unsafe fn install_caption_layout(height: CaptionHeight) -> Result<(), String> { - if LAYOUT_HOOK.get().is_some() { - return Ok(()); - } - let image = recorded_image()?; - let slot_rva = frame_table() + bv().layout_slot * 8; - if !image.points_to(slot_rva, bv().layout) { - return Err("this browser build has no recorded frame layout".into()); - } - if !image.has(bv().layout, bv().layout_prologue) - || !image.has(bv().set_bounds_rect, bv().set_bounds_rect_prologue) - { - return Err("this browser build has no recorded caption layout helpers".into()); - } - if !image.has(bv().set_layer, bv().set_layer_prologue) - || !image.has(bv().set_radius, bv().set_radius_prologue) - || !image.has(bv().set_masks, bv().set_masks_prologue) - || !image.has(bv().stack_at_top, bv().stack_at_top_prologue) - || !image.has(bv().set_opaque, bv().set_opaque_prologue) - { - return Err("this browser build has no recorded panel layer helpers".into()); - } - let base = image.base; - let _ = SET_OPAQUE.set(std::mem::transmute::( - base + bv().set_opaque, - )); - let _ = STACK_AT_TOP.set(std::mem::transmute::( - base + bv().stack_at_top, - )); - let _ = PANEL_LAYER.set(( - std::mem::transmute::(base + bv().set_layer), - std::mem::transmute::(base + bv().set_radius), - std::mem::transmute::(base + bv().set_masks), - )); - let _ = LAYOUT_HOOK.set(( - std::mem::transmute::(base + bv().layout), - std::mem::transmute::(base + bv().set_bounds_rect), - height, - )); - replace_vtable_slot( - &image, - slot_rva, - bv().layout, - frame_layout as *const () as usize, - "frame view vtable", - ) } #[cfg(test)] diff --git a/rivet/runtime/windows/src/features/layout_experiments.rs b/rivet/runtime/windows/src/features/layout_experiments.rs deleted file mode 100644 index d771a11..0000000 --- a/rivet/runtime/windows/src/features/layout_experiments.rs +++ /dev/null @@ -1,308 +0,0 @@ -//! Two experiments that leave room for Rivet's surfaces without hooking the browser's layout. -//! -//! Both are off unless switched on for the browser process. A switch is an environment variable -//! the browser process inherits, or a flag file of the same name in the debug folder. Each is read -//! once per process, so a change needs a new browser process. -//! -//! - `RIVET_EXPERIMENT_NCCALCSIZE`: the window procedure answers `WM_NCCALCSIZE` with a client -//! area that leaves out the appbar's column (`1`), or the column and the top row (`2`). The -//! browser then lays itself out in the smaller client area, and the frame layout hook reserves -//! nothing. Rivet's visuals move by the same amount the other way, which shows whether a visual -//! of the window's composition target can still draw outside the client area. -//! - `RIVET_EXPERIMENT_PAGE_VIEW_ONLY`: the frame view's client view placement is not replaced, -//! the caption layout, caption height and top inset are not installed and the page area layout -//! is not patched. Rivet works out the panel from the client area itself and places the window's -//! page view, and the pages of a grid, inside it. -//! -//! When both are on, only the page view experiment runs, since it already places every page. - -use std::sync::OnceLock; - -use crate::features::frame_layout::Rect; - -/// The environment variable and flag file name of experiment A. -pub(crate) const NCCALCSIZE: &str = "RIVET_EXPERIMENT_NCCALCSIZE"; -/// The environment variable and flag file name of experiment B. -pub(crate) const PAGE_VIEW_ONLY: &str = "RIVET_EXPERIMENT_PAGE_VIEW_ONLY"; - -/// What experiment A takes out of the client area. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum NcInset { - Off, - /// The appbar's column at the left. - Left, - /// The appbar's column and the top row. - LeftAndTop, -} - -/// Experiment A from the variable's value and whether its flag file exists. A flag file alone -/// means the column only. -pub(crate) fn parse_nccalcsize(value: Option<&str>, flag: bool) -> NcInset { - let value = value.map(|value| value.trim().to_ascii_lowercase()); - match value.as_deref() { - Some("1" | "left" | "on" | "true") => NcInset::Left, - Some("2" | "top" | "left+top") => NcInset::LeftAndTop, - Some("0" | "off" | "false") => NcInset::Off, - _ if flag => NcInset::Left, - _ => NcInset::Off, - } -} - -/// An on or off switch from the variable's value and whether its flag file exists. -pub(crate) fn parse_switch(value: Option<&str>, flag: bool) -> bool { - let value = value.map(|value| value.trim().to_ascii_lowercase()); - match value.as_deref() { - Some("1" | "on" | "true") => true, - Some("0" | "off" | "false") => false, - _ => flag, - } -} - -/// Experiment A gives way to experiment B, which places every page itself. -pub(crate) fn effective_nccalcsize(inset: NcInset, page_view_only: bool) -> NcInset { - if page_view_only { - NcInset::Off - } else { - inset - } -} - -fn flag_exists(name: &str) -> bool { - crate::frame::debug_directory() - .is_some_and(|dir| dir.join(format!("{name}.flag")).exists()) -} - -fn variable(name: &str) -> Option { - std::env::var(name).ok() -} - -/// Experiment B, read once per process. -pub(crate) fn page_view_only() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| { - let on = parse_switch( - variable(PAGE_VIEW_ONLY).as_deref(), - flag_exists(PAGE_VIEW_ONLY), - ); - crate::trace::trace(&format!("experiment: page view only {on}")); - on - }) -} - -/// Experiment A, read once per process. -pub(crate) fn nccalcsize() -> NcInset { - static INSET: OnceLock = OnceLock::new(); - *INSET.get_or_init(|| { - let inset = effective_nccalcsize( - parse_nccalcsize(variable(NCCALCSIZE).as_deref(), flag_exists(NCCALCSIZE)), - page_view_only(), - ); - crate::trace::trace(&format!("experiment: client area inset {inset:?}")); - inset - }) -} - -/// The pixels experiment A takes from the left and the top of the client area, for an appbar -/// column `leading` DIPs wide and a top row `top` DIPs tall, at `dpi`. -pub(crate) fn nc_inset_pixels(inset: NcInset, leading: i32, top: i32, dpi: u32) -> [i32; 2] { - let pixels = |dips: i32| (dips.max(0) * dpi as i32 + 48) / 96; - match inset { - NcInset::Off => [0, 0], - NcInset::Left => [pixels(leading), 0], - NcInset::LeftAndTop => [pixels(leading), pixels(top)], - } -} - -/// The client rect, as left, top, right and bottom, with `left` and `top` pixels taken from it. -/// At least one pixel of width and height is always left. -pub(crate) fn shrink_client(rect: [i32; 4], left: i32, top: i32) -> [i32; 4] { - let [l, t, r, b] = rect; - let left = left.clamp(0, (r - l - 1).max(0)); - let top = top.clamp(0, (b - t - 1).max(0)); - [l + left, t + top, r, b] -} - -/// A client size in pixels as DIPs at `dpi`. -pub(crate) fn client_dips(width: i32, height: i32, dpi: u32) -> [i32; 2] { - let dips = |pixels: i32| (pixels.max(0) * 96 + dpi as i32 / 2) / dpi.max(1) as i32; - [dips(width), dips(height)] -} - -/// The bounds of the page view, in its parent's coordinates, for the panel Rivet placed in window -/// DIPs. `parent` is the window position of the page view's parent, and `bar` the height of the -/// bar row at the top of the panel. -pub(crate) fn page_view_rect(panel: Rect, parent: [i32; 2], bar: i32) -> [i32; 4] { - let bar = bar.clamp(0, (panel.height - 1).max(0)); - [ - panel.x - parent[0], - panel.y - parent[1] + bar, - panel.width.max(1), - (panel.height - bar).max(1), - ] -} - -/// The client inset experiment A applied to each window last, in pixels, so Rivet's visuals move -/// back by it. -static APPLIED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -/// Remembers the inset applied to a window. Returns whether it changed. -pub(crate) fn remember_inset(window: isize, inset: [i32; 2]) -> bool { - let mut all = APPLIED.lock().unwrap_or_else(|error| error.into_inner()); - match all.iter_mut().find(|entry| entry.0 == window) { - Some(entry) => std::mem::replace(&mut entry.1, inset) != inset, - None => { - all.push((window, inset)); - inset != [0, 0] - } - } -} - -/// The inset experiment A applied to a window last, in pixels. -pub(crate) fn applied_inset(window: isize) -> [i32; 2] { - APPLIED - .lock() - .unwrap_or_else(|error| error.into_inner()) - .iter() - .find(|entry| entry.0 == window) - .map_or([0, 0], |entry| entry.1) -} - -pub(crate) fn forget(window: isize) { - APPLIED - .lock() - .unwrap_or_else(|error| error.into_inner()) - .retain(|entry| entry.0 != window); - BROWSER_WIDTH - .lock() - .unwrap_or_else(|error| error.into_inner()) - .retain(|entry| entry.0 != window); -} - -/// The width the browser lays each window out in, in its own DIPs, read from a view that spans the -/// window. The browser picks its scale itself, which can differ from the one Windows reports for a -/// window off every monitor, so this width is what turns client pixels into the browser's DIPs. -static BROWSER_WIDTH: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -/// Records the width of a view of the window that starts at its left edge. Returns whether it -/// changed. -pub(crate) fn note_browser_width(window: isize, view: [i32; 4]) -> bool { - if view[0] != 0 || view[2] <= 0 { - return false; - } - let mut all = BROWSER_WIDTH.lock().unwrap_or_else(|error| error.into_inner()); - match all.iter_mut().find(|entry| entry.0 == window) { - Some(entry) => std::mem::replace(&mut entry.1, view[2]) != view[2], - None => { - all.push((window, view[2])); - true - } - } -} - -/// The client size in the browser's DIPs: by the width the browser laid the window out in when it -/// is known, else at `dpi`. -pub(crate) fn browser_dips(window: isize, width: i32, height: i32, dpi: u32) -> [i32; 2] { - let known = BROWSER_WIDTH - .lock() - .unwrap_or_else(|error| error.into_inner()) - .iter() - .find(|entry| entry.0 == window) - .map(|entry| entry.1); - match known { - Some(dips) if width > 0 => [dips, (height.max(0) as i64 * dips as i64 / width as i64) as i32], - _ => client_dips(width, height, dpi), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fr12_client_pixels_follow_the_scale_the_browser_laid_out_at() { - let window = 0x5150; - // Before the browser laid anything out, the scale Windows reports is used. - assert_eq!(browser_dips(window, 1800, 1067, 192), [900, 534]); - // A view that does not start at the left edge says nothing of the window's width. - assert!(!note_browser_width(window, [276, 0, 616, 518])); - assert!(note_browser_width(window, [0, 0, 1440, 824])); - assert_eq!(browser_dips(window, 1800, 1067, 192), [1440, 853]); - forget(window); - assert_eq!(browser_dips(window, 1800, 1067, 192), [900, 534]); - } - - #[test] - fn nfr3_layout_experiments_are_off_unless_switched_on() { - assert_eq!(parse_nccalcsize(None, false), NcInset::Off); - assert_eq!(parse_nccalcsize(Some(""), false), NcInset::Off); - assert_eq!(parse_nccalcsize(Some("0"), true), NcInset::Off); - assert_eq!(parse_nccalcsize(Some("1"), false), NcInset::Left); - assert_eq!(parse_nccalcsize(Some(" Left "), false), NcInset::Left); - assert_eq!(parse_nccalcsize(Some("2"), false), NcInset::LeftAndTop); - assert_eq!(parse_nccalcsize(None, true), NcInset::Left); - assert!(!parse_switch(None, false)); - assert!(!parse_switch(Some("yes please"), false)); - assert!(parse_switch(Some("1"), false)); - assert!(parse_switch(Some("TRUE"), false)); - assert!(parse_switch(None, true)); - assert!(!parse_switch(Some("off"), true)); - } - - #[test] - fn nfr3_client_area_experiment_gives_way_to_page_view_only() { - assert_eq!(effective_nccalcsize(NcInset::Left, true), NcInset::Off); - assert_eq!(effective_nccalcsize(NcInset::LeftAndTop, false), NcInset::LeftAndTop); - } - - #[test] - fn fr2_client_area_leaves_out_the_appbar_column_at_the_window_scale() { - assert_eq!(nc_inset_pixels(NcInset::Off, 268, 52, 144), [0, 0]); - assert_eq!(nc_inset_pixels(NcInset::Left, 268, 52, 96), [268, 0]); - assert_eq!(nc_inset_pixels(NcInset::Left, 268, 52, 144), [402, 0]); - assert_eq!(nc_inset_pixels(NcInset::LeftAndTop, 268, 52, 144), [402, 78]); - // A hidden appbar takes nothing. - assert_eq!(nc_inset_pixels(NcInset::LeftAndTop, 0, 0, 120), [0, 0]); - } - - #[test] - fn fr2_shrunk_client_area_keeps_one_pixel() { - assert_eq!(shrink_client([0, 0, 1600, 1000], 402, 78), [402, 78, 1600, 1000]); - assert_eq!(shrink_client([8, 8, 1608, 1008], 402, 0), [410, 8, 1608, 1008]); - assert_eq!(shrink_client([0, 0, 100, 50], 400, 400), [99, 49, 100, 50]); - assert_eq!(shrink_client([0, 0, 100, 50], -5, -5), [0, 0, 100, 50]); - } - - #[test] - fn fr12_client_pixels_become_dips_at_the_window_scale() { - assert_eq!(client_dips(1600, 1000, 96), [1600, 1000]); - assert_eq!(client_dips(2400, 1500, 144), [1600, 1000]); - assert_eq!(client_dips(2000, 1250, 120), [1600, 1000]); - } - - #[test] - fn fr12_page_view_sits_below_the_bar_inside_the_panel() { - let panel = Rect { - x: 268, - y: 8, - width: 1324, - height: 984, - }; - // A parent at the window's origin. - assert_eq!(page_view_rect(panel, [0, 0], 44), [268, 52, 1324, 940]); - // A parent that starts below the browser's own title row. - assert_eq!(page_view_rect(panel, [0, 32], 44), [268, 20, 1324, 940]); - // A bar taller than the panel leaves one DIP of page. - assert_eq!(page_view_rect(Rect { height: 10, ..panel }, [0, 0], 44)[3], 1); - } - - #[test] - fn fr2_applied_inset_is_remembered_per_window() { - let window = 0x7777_0001; - assert_eq!(applied_inset(window), [0, 0]); - assert!(remember_inset(window, [402, 0])); - assert!(!remember_inset(window, [402, 0])); - assert_eq!(applied_inset(window), [402, 0]); - forget(window); - assert_eq!(applied_inset(window), [0, 0]); - } -} diff --git a/rivet/runtime/windows/src/features/mini_window.rs b/rivet/runtime/windows/src/features/mini_window.rs index 6476f54..5cfe0d8 100644 --- a/rivet/runtime/windows/src/features/mini_window.rs +++ b/rivet/runtime/windows/src/features/mini_window.rs @@ -261,12 +261,6 @@ pub fn is_mini(window: HWND) -> bool { MINIS.with(|all| all.borrow().contains_key(&(window as isize))) } -/// The room a Mini Window keeps at its top for Rivet's row, in DIPs, so the browser lays the page -/// out below it. -pub fn top_inset(window: HWND) -> Option { - is_mini(window).then_some(ROW) -} - /// The pages' area of the window in DIPs as left, top, right and bottom. unsafe fn area(window: HWND) -> Option<[i32; 4]> { crate::features::split::page_area(window) diff --git a/rivet/runtime/windows/src/features/mod.rs b/rivet/runtime/windows/src/features/mod.rs index 6d61336..dfc20c7 100644 --- a/rivet/runtime/windows/src/features/mod.rs +++ b/rivet/runtime/windows/src/features/mod.rs @@ -10,7 +10,6 @@ pub(crate) mod dev_page; pub(crate) mod dev_tools; pub(crate) mod field_caret; pub(crate) mod frame_layout; -pub(crate) mod layout_experiments; pub(crate) mod link_preview; pub(crate) mod link_rules; pub(crate) mod link_tabs; @@ -21,7 +20,7 @@ pub(crate) mod omnibox; pub(crate) mod page_bar; pub(crate) mod page_fit; pub(crate) mod page_links; -pub(crate) mod pane_infobar; +pub(crate) mod page_view; pub(crate) mod second_view; pub(crate) mod settings; pub(crate) mod side_panel; diff --git a/rivet/runtime/windows/src/features/omnibox.rs b/rivet/runtime/windows/src/features/omnibox.rs index 316ee36..fd14763 100644 --- a/rivet/runtime/windows/src/features/omnibox.rs +++ b/rivet/runtime/windows/src/features/omnibox.rs @@ -410,17 +410,6 @@ pub(crate) fn match_count(begin: usize, second: usize, match_size: usize) -> Opt (count <= 64).then_some(count) } -/// Patches the app window's layout so the page area steps run for it. An app window is laid out -/// by `BrowserViewAppLayoutImpl`, not the tabbed layout, so this patch needs nothing of that one. -pub(crate) unsafe fn install_app_layout() -> Result<(), String> { - let (f, _) = loaded().ok_or("this build has no recorded app window layout")?; - crate::browsers::chromium::layout::install_app_layout( - f.app_layout_vtable, - f.app_layout_slot, - f.app_layout_proposed, - ) -} - #[cfg(test)] mod tests { use super::*; diff --git a/rivet/runtime/windows/src/features/page_view.rs b/rivet/runtime/windows/src/features/page_view.rs new file mode 100644 index 0000000..5f2db43 --- /dev/null +++ b/rivet/runtime/windows/src/features/page_view.rs @@ -0,0 +1,108 @@ +//! Where Rivet places a window's page view. The browser's own layout is left alone: Rivet works out +//! the panel from the client area itself and places the window's page view, and the pages of a grid, +//! inside it. + +use crate::features::frame_layout::Rect; + +/// A client size in pixels as DIPs at `dpi`. +pub(crate) fn client_dips(width: i32, height: i32, dpi: u32) -> [i32; 2] { + let dips = |pixels: i32| (pixels.max(0) * 96 + dpi as i32 / 2) / dpi.max(1) as i32; + [dips(width), dips(height)] +} + +/// The bounds of the page view, in its parent's coordinates, for the panel Rivet placed in window +/// DIPs. `parent` is the window position of the page view's parent, and `bar` the height of the +/// bar row at the top of the panel. +pub(crate) fn page_view_rect(panel: Rect, parent: [i32; 2], bar: i32) -> [i32; 4] { + let bar = bar.clamp(0, (panel.height - 1).max(0)); + [ + panel.x - parent[0], + panel.y - parent[1] + bar, + panel.width.max(1), + (panel.height - bar).max(1), + ] +} + +pub(crate) fn forget(window: isize) { + BROWSER_WIDTH + .lock() + .unwrap_or_else(|error| error.into_inner()) + .retain(|entry| entry.0 != window); +} + +/// The width the browser lays each window out in, in its own DIPs, read from a view that spans the +/// window. The browser picks its scale itself, which can differ from the one Windows reports for a +/// window off every monitor, so this width is what turns client pixels into the browser's DIPs. +static BROWSER_WIDTH: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Records the width of a view of the window that starts at its left edge. Returns whether it +/// changed. +pub(crate) fn note_browser_width(window: isize, view: [i32; 4]) -> bool { + if view[0] != 0 || view[2] <= 0 { + return false; + } + let mut all = BROWSER_WIDTH.lock().unwrap_or_else(|error| error.into_inner()); + match all.iter_mut().find(|entry| entry.0 == window) { + Some(entry) => std::mem::replace(&mut entry.1, view[2]) != view[2], + None => { + all.push((window, view[2])); + true + } + } +} + +/// The client size in the browser's DIPs: by the width the browser laid the window out in when it +/// is known, else at `dpi`. +pub(crate) fn browser_dips(window: isize, width: i32, height: i32, dpi: u32) -> [i32; 2] { + let known = BROWSER_WIDTH + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + .find(|entry| entry.0 == window) + .map(|entry| entry.1); + match known { + Some(dips) if width > 0 => [dips, (height.max(0) as i64 * dips as i64 / width as i64) as i32], + _ => client_dips(width, height, dpi), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fr12_client_pixels_follow_the_scale_the_browser_laid_out_at() { + let window = 0x5150; + // Before the browser laid anything out, the scale Windows reports is used. + assert_eq!(browser_dips(window, 1800, 1067, 192), [900, 534]); + // A view that does not start at the left edge says nothing of the window's width. + assert!(!note_browser_width(window, [276, 0, 616, 518])); + assert!(note_browser_width(window, [0, 0, 1440, 824])); + assert_eq!(browser_dips(window, 1800, 1067, 192), [1440, 853]); + forget(window); + assert_eq!(browser_dips(window, 1800, 1067, 192), [900, 534]); + } + + #[test] + fn fr12_client_pixels_become_dips_at_the_window_scale() { + assert_eq!(client_dips(1600, 1000, 96), [1600, 1000]); + assert_eq!(client_dips(2400, 1500, 144), [1600, 1000]); + assert_eq!(client_dips(2000, 1250, 120), [1600, 1000]); + } + + #[test] + fn fr12_page_view_sits_below_the_bar_inside_the_panel() { + let panel = Rect { + x: 268, + y: 8, + width: 1324, + height: 984, + }; + // A parent at the window's origin. + assert_eq!(page_view_rect(panel, [0, 0], 44), [268, 52, 1324, 940]); + // A parent that starts below the browser's own title row. + assert_eq!(page_view_rect(panel, [0, 32], 44), [268, 20, 1324, 940]); + // A bar taller than the panel leaves one DIP of page. + assert_eq!(page_view_rect(Rect { height: 10, ..panel }, [0, 0], 44)[3], 1); + } +} diff --git a/rivet/runtime/windows/src/features/pane_infobar.rs b/rivet/runtime/windows/src/features/pane_infobar.rs deleted file mode 100644 index 313323f..0000000 --- a/rivet/runtime/windows/src/features/pane_infobar.rs +++ /dev/null @@ -1,158 +0,0 @@ -//! The browser's infobar belongs to the pane whose tab it is about. -//! -//! Chromium keeps one `InfoBarContainerView` per window, right above the page, and its layout -//! gives it the whole width of the page area. With a split, that bar spanned both panes although -//! it speaks for the window's own page only. Rivet narrows it to the pane of the window's page -//! view, and the other pane rises to the bar's top so it does not keep an empty strip. - -use std::cell::RefCell; -use std::collections::HashMap; - -use windows_sys::Win32::Foundation::HWND; - -use crate::features::address_bar::rides_above_page; -use crate::features::second_view::Mode; - -thread_local! { - /// Per window: the height of the bars right above the page, and the page area width and the - /// main pane's columns the last layout narrowed them to. - static BARS: RefCell> = RefCell::new(HashMap::new()); -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct Seen { - height: i32, - width: i32, - columns: Option<(i32, i32)>, -} - -/// The height of the browser's bars right above the window's page, from the last layout. -pub(crate) fn bar_above(window: HWND) -> i32 { - BARS.with(|bars| { - bars.borrow() - .get(&(window as isize)) - .map_or(0, |seen| seen.height) - }) -} - -/// The second view's bounds `second` with the pane raised over the browser's bars of height -/// `height`, which belong to the other pane. A view that shows no page stays. -pub(crate) fn lift(mode: Mode, second: [i32; 4], height: i32) -> [i32; 4] { - let [x, y, width, bounds_height] = second; - if mode == Mode::Inset || height <= 0 || width <= 0 { - return second; - } - let height = height.min(y.max(0)); - [x, y - height, width, bounds_height + height] -} - -/// A bar's bounds narrowed to the main pane, which starts `columns.0` DIPs into the page -/// `contents` and is `columns.1` wide. -pub(crate) fn narrow(bar: [i32; 4], contents: [i32; 4], columns: (i32, i32)) -> [i32; 4] { - let (x, width) = columns; - [contents[0] + x, bar[1], width.max(1), bar[3]] -} - -/// The page area step: the bars above the page take the main pane's columns while a split is -/// open, and their height is kept for the second view's placement. -pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { - let Some(contents) = area.contents() else { - return; - }; - let page = *contents; - let columns = crate::features::second_view::split_columns(area.window, page[2]); - let mut height = 0; - for (_, bounds) in area.all_bounds() { - if bounds == contents || !rides_above_page(*bounds, page) { - continue; - } - height += (*bounds)[3]; - if let Some(columns) = columns { - *bounds = narrow(*bounds, page, columns); - } - } - let seen = Seen { - height, - width: page[2], - columns, - }; - BARS.with(|bars| bars.borrow_mut().insert(area.window as isize, seen)); -} - -/// Whether the page area must be laid out again: the split's columns changed since the last -/// layout narrowed the bars, and there are bars to narrow. -fn stale(seen: Option, columns: impl Fn(i32) -> Option<(i32, i32)>) -> bool { - seen.is_some_and(|seen| seen.height > 0 && columns(seen.width) != seen.columns) -} - -/// Lays the page area out again when a split opened, closed or moved its divider since the bars -/// were last narrowed. Called when the second view changes, outside the browser's layout. -pub(crate) unsafe fn follow(window: HWND) { - let seen = BARS.with(|bars| bars.borrow().get(&(window as isize)).copied()); - if stale(seen, |width| { - crate::features::second_view::split_columns(window, width) - }) { - crate::hooks::page_area::relayout(window); - } -} - -/// Drops a closed window. -pub(crate) fn forget(window: HWND) { - BARS.with(|bars| bars.borrow_mut().remove(&(window as isize))); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fr9_an_infobar_spans_only_the_pane_that_owns_its_tab() { - // Brave 156.1.98.63 showed a 56 DIP infobar across both panes of a split. - let contents = [0, 100, 1164, 600]; - let bar = [0, 44, 1164, 56]; - assert_eq!(narrow(bar, contents, (0, 694)), [0, 44, 694, 56]); - // The window's page on the right, after the second view on the left. - assert_eq!(narrow(bar, contents, (470, 694)), [470, 44, 694, 56]); - } - - #[test] - fn fr9_the_other_pane_rises_to_the_infobar_top() { - let second = [702, 100, 462, 600]; - assert_eq!(lift(Mode::Split, second, 56), [702, 44, 462, 656]); - assert_eq!( - lift(Mode::Docked { width: 240 }, second, 56), - [702, 44, 462, 656] - ); - // No bar, an empty view, or a view at the top leave it. - assert_eq!(lift(Mode::Split, second, 0), second); - assert_eq!(lift(Mode::Inset, second, 56), second); - assert_eq!(lift(Mode::Split, [0, 20, 100, 100], 56), [0, 0, 100, 120]); - } - - #[test] - fn fr9_the_page_area_is_laid_out_again_only_when_the_columns_changed() { - let seen = Seen { - height: 56, - width: 1164, - columns: None, - }; - assert!(stale(Some(seen), |_| Some((0, 694))), "a split opened"); - assert!(!stale(Some(seen), |_| None)); - let narrowed = Seen { - columns: Some((0, 694)), - ..seen - }; - assert!(stale(Some(narrowed), |_| None), "the split closed"); - assert!( - !stale( - Some(Seen { - height: 0, - ..narrowed - }), - |_| None - ), - "no bar to widen" - ); - assert!(!stale(None, |_| Some((0, 694)))); - } -} diff --git a/rivet/runtime/windows/src/features/second_view.rs b/rivet/runtime/windows/src/features/second_view.rs index 5d5f813..38d118b 100644 --- a/rivet/runtime/windows/src/features/second_view.rs +++ b/rivet/runtime/windows/src/features/second_view.rs @@ -655,20 +655,6 @@ unsafe fn virtual_of(view: usize, name: &str, slot_name: &str) -> Option }) } -/// The main page's columns, as x and width within a page area `width` DIPs wide, while the -/// window shows a split. The browser's bar above the page is narrowed to them. -pub(crate) fn split_columns(window: HWND, width: i32) -> Option<(i32, i32)> { - split().filter(|split| split.window == window as isize && split.mode == Mode::Split)?; - grid_bounds( - &grid_of(window as isize), - [0, 0, width, 1], - rail_of(window as isize), - ) - .into_iter() - .find(|(slot, _)| *slot == 0) - .map(|(_, rect)| (rect[0], rect[2])) -} - /// The first view below `root` that holds a page whose vtable is `page_vtable`, as the view and /// the page. The Sidebar finds the extension page that the browser's side panel shows this way. pub(crate) unsafe fn page_under(root: usize, page_vtable: usize) -> Option<(usize, usize)> { @@ -773,33 +759,30 @@ unsafe fn area_of(split: &Split) -> Option<[i32; 4]> { ); *FULL.lock().unwrap_or_else(|error| error.into_inner()) = now; } - // Experiment: the page area is the panel Rivet placed, not what the browser gave the page view. - if crate::features::layout_experiments::page_view_only() { - if let Some(panel) = crate::features::frame_layout::panel_bounds(split.window as HWND) { - let [ox, oy] = window_origin(split.main); - let parent = [ox - now[0], oy - now[1]]; - let full = crate::features::layout_experiments::page_view_rect(panel, parent, 0); - *FULL.lock().unwrap_or_else(|error| error.into_inner()) = full; - let container = word(split.main + offsets().0) - .filter(|parent| *parent != 0) - .map(|parent| bounds_of(parent)); - // The page view's parent spans the window, so its width is the browser's own. - let noted = container.is_some_and(|bounds| { - crate::features::layout_experiments::note_browser_width(split.window, bounds) - }); - if noted { - crate::frame::place_panel_by_rivet(split.window as HWND); - } - crate::trace::trace_changed( - "experiment page view area", - &format!( - "experiment page view only: panel {panel:?}, page view parent at {parent:?} \ - with bounds {container:?}, browser gave {now:?}, Rivet's area {full:?}, \ - bar row {}", - top_of(split.window) - ), - ); + // The page area is the panel Rivet placed, not what the browser gave the page view. + if let Some(panel) = crate::features::frame_layout::panel_bounds(split.window as HWND) { + let [ox, oy] = window_origin(split.main); + let parent = [ox - now[0], oy - now[1]]; + let full = crate::features::page_view::page_view_rect(panel, parent, 0); + *FULL.lock().unwrap_or_else(|error| error.into_inner()) = full; + let container = word(split.main + offsets().0) + .filter(|parent| *parent != 0) + .map(|parent| bounds_of(parent)); + // The page view's parent spans the window, so its width is the browser's own. + let noted = container.is_some_and(|bounds| { + crate::features::page_view::note_browser_width(split.window, bounds) + }); + if noted { + crate::frame::place_panel_by_rivet(split.window as HWND); } + crate::trace::trace_changed( + "page view placed area", + &format!( + "page view: panel {panel:?}, page view parent at {parent:?} with bounds \ + {container:?}, browser gave {now:?}, Rivet's area {full:?}, bar row {}", + top_of(split.window) + ), + ); } let full = *FULL.lock().unwrap_or_else(|error| error.into_inner()); let full = fitted(split.main, full); @@ -840,16 +823,6 @@ unsafe fn place(split: &Split) -> bool { } else { moved }; - // A page on the top line rises over the browser's bars, which belong to the main page. - let moved = if rect[1] == full[1] { - crate::features::pane_infobar::lift( - split.mode, - moved, - crate::features::pane_infobar::bar_above(window), - ) - } else { - moved - }; crate::features::sidebar_page::fit(window, split.mode, moved) }; // A page view that keeps its page inside a border grows by it, so every pane's page starts @@ -1693,7 +1666,6 @@ pub(crate) unsafe fn close(window: HWND) -> bool { let inset = open_with(window, window, 0, Mode::Inset); crate::trace::trace(&format!("second view: closed to the rail inset: {inset}")); } - crate::features::pane_infobar::follow(window); true } diff --git a/rivet/runtime/windows/src/features/side_panel.rs b/rivet/runtime/windows/src/features/side_panel.rs index d7e79bf..fe8cf62 100644 --- a/rivet/runtime/windows/src/features/side_panel.rs +++ b/rivet/runtime/windows/src/features/side_panel.rs @@ -23,8 +23,6 @@ use crate::builds::Build; use crate::chromium::image; use crate::chromium::memory::{prologue_is, readable}; use crate::feature::{available_here, Needs}; -use crate::features::frame_layout::{self}; -use crate::hooks::page_area::{self, PageArea}; use crate::targets::Target; /// The values of the loaded browser build. @@ -158,14 +156,9 @@ pub unsafe fn objects(window: HWND) -> Option { } /// The `BrowserWindow` subobject of a window's `BrowserView`, which the frame view keeps in its -/// tracker of the browser view. A window whose frame view is not known has it from the layout, -/// which lays that same view out. +/// tracker of the browser view. The frame view is found from the window's live view tree. unsafe fn browser_window_of(window: HWND) -> Option { - let host = page_area::laid_out_host(window); - match frame_layout::frame_view(window) { - Some(frame) => crate::chromium::window_views::frame_browser_view(frame, host), - None => host, - } + crate::chromium::window_views::browser_view_of(window) } unsafe fn find_objects(window: HWND, base: usize) -> Option { @@ -804,150 +797,21 @@ pub fn is_unfolded(window: HWND) -> bool { UNFOLDED.with(|set| set.borrow().contains(&(window as isize))) } -/// The width the rail takes from the right of a window's page area. -fn rail_of(window: HWND) -> i32 { - // Where the second view is recorded, it keeps the rail free itself. - if crate::features::second_view::available() { - return 0; - } - if UNFOLDED.with(|set| set.borrow().contains(&(window as isize))) { - RAIL_WIDTH - } else { - 0 - } -} - /// The width of an open side panel, in DIPs. The mock-up's extension panel is 240 DIPs wide. pub const PANEL_WIDTH: i32 = 240; /// The height Rivet keeps free above an open side panel for its own header row. pub const HEADER_ROW: i32 = 40; -/// Leaves `rail` DIPs at the right edge of the page area. The page keeps the width it has with no -/// panel open. An open side panel is `PANEL_WIDTH` wide at the right end of the page, over it, and -/// ends at the rail. `page` is the left and right edge the page has with no panel open. `top` is the -/// top of the page area: Rivet's header row sits there, and the panel starts right below it even when -/// the browser keeps a bar, like an infobar, between the area's top and its own panel. -fn make_room( - contents: &mut [i32; 4], - outline: Option<&mut [i32; 4]>, - side_panel: Option<&mut [i32; 4]>, - animation: Option<&mut [i32; 4]>, - page: (i32, i32), - rail: i32, - top: i32, -) { - // The panel's right edge ends at the rail. While Chrome animates the panel in, it is narrower. - let panel = side_panel - .as_ref() - .filter(|bounds| bounds[2] > 0) - .map(|bounds| { - ( - page.1 - rail, - bounds[2].min(PANEL_WIDTH), - bounds[1], - bounds[3], - ) - }); - for bounds in [side_panel, animation].into_iter().flatten() { - bounds[0] = match panel { - Some((edge, width, _, _)) => { - // The header row above the panel is Rivet's, so the browser's panel starts below it. - let below = top + HEADER_ROW; - let bottom = bounds[1] + bounds[3]; - bounds[1] = below; - bounds[3] = (bottom - below).max(0); - // Rivet's hairline takes the panel's first column. - bounds[2] = width - 1; - edge - width + 1 - } - None => bounds[0] - rail, - }; - } - for bounds in [Some(&mut *contents), outline].into_iter().flatten() { - let right = match panel { - // Chrome shrank and insets the contents for the panel. The panel floats, so the - // contents are what they are with no panel: from the page's left to the rail. The caller - // gives both edges, because Chrome's own move while the panel slides in. - Some((edge, _, panel_top, height)) => { - bounds[0] = page.0; - bounds[1] = panel_top; - bounds[3] = height; - edge - } - None => bounds[0] + bounds[2] - rail, - }; - bounds[2] = (right - bounds[0]).max(1); - } -} - -thread_local! { - static CONTENTS_SEEN: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) }; -} - -/// Traces the page's bounds whenever a layout changes them, so a check can compare the page -/// before and after a panel opens. -fn trace_contents(window: HWND, contents: &[i32; 4]) { - if CONTENTS_SEEN.with(|seen| seen.replace(*contents)) != *contents { - trace(&format!("page {:x} bounds {contents:?}", window as isize)); - } -} - -/// Whether this build's Sidebar has been checked. A build can record the browser's layout, which the -/// pages of a split need, without it. +/// Whether this build's Sidebar has been checked. pub fn sidebar_checked() -> bool { checked() } -/// The Sidebar's part of the page area layout: it reserves the rail, and lets an open panel float -/// over the page. -pub(crate) unsafe fn on_page_area(area: &mut PageArea) { - let rail = rail_of(area.window); - area.rail = rail; - if rail > 0 { - if let Some(contents) = area.contents() { - let side_panel = area.bounds(bv().side_panel); - let animation = area.bounds(bv().side_panel_animation); - let outline = area.bounds(bv().contents_outline); - let panel_view = area.field(bv().side_panel); - let page = area.page().map(|bounds| *bounds).unwrap_or([0; 4]); - // The page starts where the browser's vertical tab list ends. - let left = area - .bounds(bv().vertical_tabs) - .map_or((*contents)[0], |tabs| (*tabs)[0] + (*tabs)[2]); - make_room( - &mut *contents, - outline.map(|bounds| &mut *bounds), - side_panel.map(|bounds| &mut *bounds), - animation.map(|bounds| &mut *bounds), - (left, page[0] + page[2]), - rail, - page[1], - ); - // The panel floats over the page, so its layer paints above the page's. - if panel_view != 0 && side_panel.is_some_and(|bounds| (*bounds)[2] > 0) { - frame_layout::raise_view(panel_view as *mut c_void); - } - trace_contents(area.window, &*contents); - } - } -} - -/// Folds or unfolds the Sidebar of a window and lays its page area out again. +/// Folds or unfolds the Sidebar of a window. The second view keeps the rail free beside the page, +/// so a build without it cannot unfold the Sidebar. pub unsafe fn set_unfolded(window: HWND, unfolded: bool) { - if crate::features::second_view::available() { - UNFOLDED.with(|set| { - let mut set = set.borrow_mut(); - if unfolded { - set.insert(window as isize); - } else { - set.remove(&(window as isize)); - } - }); - crate::features::second_view::set_rail(window, if unfolded { RAIL_WIDTH } else { 0 }); - return; - } - if let Err(error) = page_area::install() { - trace(&error); + if !crate::features::second_view::available() { + trace("this browser build records no second view, so the rail has no room"); return; } UNFOLDED.with(|set| { @@ -958,7 +822,7 @@ pub unsafe fn set_unfolded(window: HWND, unfolded: bool) { set.remove(&(window as isize)); } }); - page_area::relayout(window); + crate::features::second_view::set_rail(window, if unfolded { RAIL_WIDTH } else { 0 }); } unsafe fn dump_entry_memory(window: HWND) { @@ -996,7 +860,6 @@ enum Command { Dump, Open(u32), Rail(bool), - DumpLayout, Click(String), Entries, Colours, @@ -1014,7 +877,6 @@ impl Command { match text { "rail on" => return Some(Self::Rail(true)), "rail off" => return Some(Self::Rail(false)), - "layout" => return Some(Self::DumpLayout), "entries" => return Some(Self::Entries), "colours" => return Some(Self::Colours), _ if text.starts_with("hit ") => { @@ -1076,11 +938,6 @@ pub unsafe fn tick(window: HWND, directory: Option<&std::path::Path>) { } } Some(Command::Click(command)) => crate::side_rail::simulate(window, &command), - Some(Command::DumpLayout) => { - let _ = page_area::install(); - page_area::dump_next(); - page_area::relayout(window); - } Some(Command::Hit(x, y)) => { if let Some(found) = objects(window).filter(|_| bv().event_handler_for_point != crate::builds::ABSENT) @@ -1221,107 +1078,9 @@ mod tests { let whale = row("Naver Whale"); assert!(whale.supported && whale.registry_end == Some(true)); assert_eq!((whale.extension_entry, whale.entry_count), (0x15, 0x16)); - // The traced app window layout keeps the page area, the top row and the page container here. - assert_eq!( - (whale.page_area, whale.toolbar, whale.contents_container), - (Some(0x28), 0x40, Some(0x90)) - ); let samsung = row("Samsung Internet"); assert!(samsung.supported); assert_eq!(samsung.hidden_entries, &[20, 21, 22, 23, 24]); - assert_eq!(samsung.old_layout, Some(true)); - assert_eq!( - (samsung.contents_container, samsung.side_panel), - (Some(0x80), 0x98) - ); - } - - #[test] - fn fr10_open_panel_floats_over_the_page_and_leaves_its_width_alone() { - let mut contents = [8, 47, 692, 591]; - let mut panel = [700, 46, 378, 600]; - let mut animation = [700, 46, 378, 600]; - make_room( - &mut contents, - None, - Some(&mut panel), - Some(&mut animation), - (0, 1078), - RAIL_WIDTH, - 46, - ); - assert_eq!( - panel, - [799, 46 + HEADER_ROW, PANEL_WIDTH - 1, 600 - HEADER_ROW], - "ends at the rail, below Rivet's header row, after its hairline" - ); - assert_eq!( - contents, - [0, 46, 1038, 600], - "the page is as wide as with no panel open: up to the rail" - ); - assert_eq!(animation, panel); - } - - #[test] - fn fr10_open_panel_starts_below_the_header_row_even_under_an_infobar() { - // An infobar keeps the browser's own panel and the page 56 DIPs below the page area's top, - // where Rivet's header row is. The panel starts right under that row all the same. - let mut contents = [267, 101, 747, 737]; - let mut panel = [1014, 101, 418, 737]; - make_room( - &mut contents, - None, - Some(&mut panel), - None, - (267, 1432), - RAIL_WIDTH, - 45, - ); - assert_eq!(panel[1], 45 + HEADER_ROW); - assert_eq!( - panel[1] + panel[3], - 101 + 737, - "its bottom stays where the browser put it" - ); - assert_eq!( - contents[1], 101, - "the page keeps its place under the infobar" - ); - } - - #[test] - fn fr10_rail_leaves_a_closed_side_panel_without_width_and_the_page_whole() { - let mut contents = [0, 46, 1078, 600]; - let mut panel = [1078, 46, 0, 600]; - make_room( - &mut contents, - None, - Some(&mut panel), - None, - (0, 1078), - RAIL_WIDTH, - 46, - ); - assert_eq!(contents, [0, 46, 1038, 600]); - assert_eq!(panel[2], 0); - } - - #[test] - fn fr10_open_panel_keeps_the_page_whole_while_it_slides_in() { - // Chrome animates the panel in from outside the window and shifts the contents with it. - let mut contents = [270, 45, 900, 681]; - let mut panel = [1200, 44, 120, 690]; - make_room( - &mut contents, - None, - Some(&mut panel), - None, - (268, 1092), - RAIL_WIDTH, - 44, - ); - assert_eq!(contents, [268, 44, 784, 690]); } #[test] @@ -1332,13 +1091,6 @@ mod tests { )); } - #[test] - fn fr10_rail_never_collapses_the_page() { - let mut contents = [0, 0, 20, 100]; - make_room(&mut contents, None, None, None, (0, 20), RAIL_WIDTH, 0); - assert_eq!(contents[2], 1); - } - #[test] fn fr10_side_panel_pages_turn_chromes_blues_to_the_tint_and_keep_neutrals() { let accent = warm(0xff0b57d0).expect("Chrome's accent blue is a blue"); diff --git a/rivet/runtime/windows/src/features/sidebar_page.rs b/rivet/runtime/windows/src/features/sidebar_page.rs index 733935a..c2963df 100644 --- a/rivet/runtime/windows/src/features/sidebar_page.rs +++ b/rivet/runtime/windows/src/features/sidebar_page.rs @@ -76,14 +76,6 @@ pub(crate) fn below_header(mode: Mode, second: [i32; 4]) -> [i32; 4] { [x + 1, y + header, width - 1, (height - header).max(1)] } -/// The browser's own side panel and the page after the page area layout, while the second view -/// shows the panel's page: the page keeps the width it has with no panel, up to `page_right`, and -/// the browser's panel keeps no width at that edge. -pub(crate) fn float_over(contents: &mut [i32; 4], side_panel: &mut [i32; 4], page_right: i32) { - contents[2] = (page_right - contents[0]).max(1); - *side_panel = [page_right, side_panel[1], 0, side_panel[3]]; -} - /// The extension entry the browser shows in the window, if any. unsafe fn showing_extension(window: HWND) -> Option { panel::listed_entries(window) @@ -145,7 +137,6 @@ unsafe fn take(window: HWND, key: EntryKey) { crate::trace::trace("sidebar page: the second view did not open"); return; } - crate::hooks::page_area::relayout(window); crate::trace::trace(&format!( "sidebar page: extension page {page:#x} from view {holder:#x} in the second view" )); @@ -160,38 +151,12 @@ pub(crate) unsafe fn give_back(window: HWND) { second_view::close(window); } second_view::hand_page(entry.holder, entry.page); - crate::hooks::page_area::relayout(window); crate::trace::trace(&format!( "sidebar page: extension page {:#x} back to view {:#x}", entry.page, entry.holder )); } -/// The page area step: while the second view shows the side panel's page, the browser's panel -/// keeps no width and the page keeps its own. -pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { - if !hosts(area.window) { - return; - } - let row = &crate::builds::get().side_panel; - let page = area.page().map(|bounds| *bounds); - let Some(page_right) = page.map(|page| page[0] + page[2]) else { - return; - }; - for offset in [row.side_panel, row.side_panel_animation] { - let Some(side_panel) = area.bounds(offset) else { - continue; - }; - if let Some(contents) = area.contents() { - float_over(&mut *contents, &mut *side_panel, page_right); - } - if let Some(outline) = area.bounds(row.contents_outline) { - let mut unused = *side_panel; - float_over(&mut *outline, &mut unused, page_right); - } - } -} - /// Drops a closed window without calling into its views, which the browser deletes with it. pub(crate) fn forget(window: HWND) { HOSTED.with(|hosted| hosted.borrow_mut().remove(&(window as isize))); @@ -227,14 +192,4 @@ mod tests { [1124, 44, 0, 700] ); } - - #[test] - fn fr10_an_open_extension_panel_does_not_change_the_page_width() { - // The browser narrowed the page by its 320 DIP panel; the page keeps the whole area. - let mut contents = [0, 44, 844, 700]; - let mut side_panel = [844, 44, 320, 700]; - float_over(&mut contents, &mut side_panel, 1164); - assert_eq!(contents, [0, 44, 1164, 700]); - assert_eq!(side_panel, [1164, 44, 0, 700]); - } } diff --git a/rivet/runtime/windows/src/features/split.rs b/rivet/runtime/windows/src/features/split.rs index a8dd5d3..502a46b 100644 --- a/rivet/runtime/windows/src/features/split.rs +++ b/rivet/runtime/windows/src/features/split.rs @@ -26,12 +26,6 @@ pub unsafe fn install_panels() -> Result<(), String> { backend().install_panels() } -/// The part of the page area layout that belongs to split view: the pages of a split fill the area -/// the Sidebar left, and the toolbar follows the active page. -pub(crate) unsafe fn on_page_area(area: &mut crate::hooks::page_area::PageArea) { - backend().on_page_area(area) -} - /// Whether the browser's address can follow the focused page. A toolbar that places it by hand keeps /// it over the first page, so only that page's row shows the browser's address. pub fn address_follows_page() -> bool { @@ -311,15 +305,6 @@ pub fn row_top(first_line: bool, view_top: i32, page_top: i32) -> i32 { } } -/// The pages of a split fill the area the browser leaves for its pages, whatever insets it keeps -/// there, so they start where a single page does. The top stays below the browser's bars. -pub fn fill_area(contents: &mut [i32; 4], area: &[i32; 4]) { - let bottom = area[1] + area[3]; - contents[0] = area[0]; - contents[2] = area[2]; - contents[3] = (bottom - contents[1]).max(1); -} - /// The height of the top row of a page, in device-independent pixels. pub const ROW_HEIGHT: i32 = 44; /// Room on the first page's row for the appbar toggle, and for the grip on every row. @@ -466,8 +451,8 @@ pub unsafe fn toggle_split(window: HWND) -> bool { #[cfg(test)] mod tests { use super::{ - caption_over, drop_pair, drop_zone, fill_area, partner_of, row_buttons, row_top, RowButton, - Side, CAPTION_ROOM, TOGGLE_ROOM, + caption_over, drop_pair, drop_zone, partner_of, row_buttons, row_top, RowButton, Side, + CAPTION_ROOM, TOGGLE_ROOM, }; #[test] @@ -500,13 +485,6 @@ mod tests { assert_eq!(row_top(false, 8, 400), 356); } - #[test] - fn fr9_split_pages_fill_the_browsers_page_area_without_its_insets() { - let mut contents = [271, 135, 1157, 699]; - fill_area(&mut contents, &[267, 79, 1165, 759]); - assert_eq!(contents, [267, 135, 1165, 703]); - } - #[test] fn fr9_tab_dropped_on_an_edge_splits_that_side() { let page = [100.0, 50.0, 800.0, 600.0]; diff --git a/rivet/runtime/windows/src/frame.rs b/rivet/runtime/windows/src/frame.rs index d688cff..66a8bf2 100644 --- a/rivet/runtime/windows/src/frame.rs +++ b/rivet/runtime/windows/src/frame.rs @@ -24,7 +24,7 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{ HTMINBUTTON, HTTOP, HTTOPLEFT, ICON_BIG, ICON_SMALL, IDC_SIZEWE, MSG, PM_REMOVE, SM_CXICON, SM_CXPADDEDBORDER, SM_CXSMICON, SM_CYSIZEFRAME, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WH_GETMESSAGE, WM_CAPTURECHANGED, WM_CLOSE, WM_DPICHANGED, - WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCCALCSIZE, WM_NCDESTROY, + WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCDESTROY, WM_NCHITTEST, WM_NCLBUTTONDBLCLK, WM_NCLBUTTONDOWN, WM_NCLBUTTONUP, WM_NCMOUSELEAVE, WM_NCMOUSEMOVE, WM_NCRBUTTONDOWN, WM_NCRBUTTONUP, WM_NULL, WM_SETCURSOR, WM_SETICON, WM_SYSCOMMAND, WM_WINDOWPOSCHANGED, WNDPROC, WS_THICKFRAME, @@ -180,8 +180,9 @@ unsafe fn trace_reflection(window: HWND) -> bool { return false; }; let handler = GetWindowLongPtrW(window, GWLP_USERDATA) as usize; - // Read on the window's own thread, where the browser layout recorded it. - let host = crate::hooks::page_area::laid_out_host(window); + // The browser view the window's frame view holds, read on the window's own thread. It is known + // once an earlier walk of this build ran. + let host = crate::chromium::window_views::browser_view_of(window); std::thread::spawn(move || { let started = std::time::Instant::now(); let found = reflect::find_cached( @@ -2013,56 +2014,13 @@ unsafe fn toggle_message() -> u32 { RegisterWindowMessageW(wide(TOGGLE_MESSAGE).as_ptr()) } -/// Lays the browser out again, now that the appbar's width or mode changed, and redraws. +/// Places the panel and the page view again, now that the appbar's width or mode changed, and +/// redraws. The browser's own layout is not asked. unsafe fn relayout(window: HWND) { - use crate::features::layout_experiments::{self, NcInset}; - // Experiment: Windows takes the appbar's column out of the client area again at its new width. - if attached(window) && layout_experiments::nccalcsize() != NcInset::Off { - SetWindowPos( - window, - std::ptr::null_mut(), - 0, - 0, - 0, - 0, - SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, - ); - } - // Experiment: Rivet places the panel and the page view, the browser's layout is not asked. - if attached(window) && layout_experiments::page_view_only() { + if attached(window) { place_panel_by_rivet(window); follow_second_view(window); - update_appbar(window); - return; - } - // The frame view lays out again on request, which also works for a maximized window. - if frame_layout::relayout(window) { - if is_waiting(window) { - crate::trace::trace("attach: asked the frame view to lay out again"); - } - update_appbar(window); - return; - } - // A frame change only marks the browser's views for a layout on its next compositor frame, - // and a cloaked or off-screen window may draw none; a size change lays it out at once. - if nudge(window, "retry") { - update_appbar(window); - return; } - if is_waiting(window) { - crate::trace::trace( - "attach: asked for a frame change, as the frame view's layout is not recorded", - ); - } - SetWindowPos( - window, - std::ptr::null_mut(), - 0, - 0, - 0, - 0, - SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, - ); update_appbar(window); } @@ -2453,7 +2411,6 @@ static SECOND_VIEW_IDLE: std::sync::atomic::AtomicU32 = std::sync::atomic::Atomi /// Lays the second page view out now and keeps doing so for a few ticks. pub(crate) unsafe fn follow_second_view(window: HWND) { - crate::features::pane_infobar::follow(window); if !crate::features::second_view::is_open(window) { return; } @@ -2823,36 +2780,16 @@ struct Attach { window: HWND, } -fn caption_row_height(window: HWND) -> Option { - attached(window).then_some(crate::CAPTION_HEIGHT + frame_layout::PANEL_TOP) -} - -fn top_inset_extra(window: HWND) -> Option { - // A Rivet window has no title bar above its panel: the browser's top elements begin at the - // panel's top gap on every browser, whatever height its own title bar has. - // A Mini Window keeps the room of Rivet's row on its own surface. - attached(window) - .then_some(frame_layout::PANEL_GAP) - .or_else(|| crate::features::mini_window::top_inset(window)) -} - /// The features of a Rivet window in the order they are installed. A feature the browser does not /// have leaves the window as it is, and a failure of a feature the window cannot do without ends -/// the attach, so the browser keeps working without Rivet. +/// the attach, so the browser keeps working without Rivet. The browser's own layout is left alone: +/// the frame view's functions are only found, so a view's window can be told, and Rivet places the +/// panel and the page view itself. fn attach_steps() -> Vec> { - attach_steps_for(crate::features::layout_experiments::page_view_only()) -} - -/// The attach sequence. `page_view_only` is the experiment that leaves the browser's layout alone: -/// the frame view's functions are found but its client view placement is not replaced, and the -/// caption layout, caption height and top inset are not installed. Rivet places the panel and the -/// page view itself. -fn attach_steps_for(page_view_only: bool) -> Vec> { use crate::feature::{Feature, FeatureStep, OnFailure, Step}; - let frame_install: fn(&mut Attach) -> Result<(), String> = if page_view_only { - |_| unsafe { frame_layout::install_unpatched(reserved_width) } - } else { - |_| unsafe { frame_layout::install(reserved_width) } + let frame_install: fn(&mut Attach) -> Result<(), String> = |_| unsafe { + frame_layout::install()?; + page_view_placeable(crate::features::second_view::available()) }; let feature = |feature, needs, install, on_failure, skip_when_unavailable, log_failure| { Step::Feature(FeatureStep { @@ -2864,7 +2801,7 @@ fn attach_steps_for(page_view_only: bool) -> Vec> { log_failure, }) }; - let mut steps = vec![ + vec![ feature( Feature::FrameLayout, frame_layout::needs_layout, @@ -2890,7 +2827,6 @@ fn attach_steps_for(page_view_only: bool) -> Vec> { Some("rivet: could not paint the frame"), ), Step::Setup(|_| { - frame_layout::PANEL.store(true, std::sync::atomic::Ordering::Relaxed); frame_layout::on_panel_change(panel_moved); true }), @@ -2902,40 +2838,6 @@ fn attach_steps_for(page_view_only: bool) -> Vec> { false, Some("rivet: could not paint caption buttons"), ), - feature( - Feature::CaptionLayout, - frame_layout::needs_caption_layout, - |_| unsafe { frame_layout::install_caption_layout(caption_row_height) }, - OnFailure::Continue, - false, - Some("rivet: could not lay out caption buttons"), - ), - // The caption height and the top inset size the panel's top row, so they never depend on the - // trace file. Failures show in the trace when it is on. - feature( - Feature::CaptionHeight, - frame_layout::needs_caption_height, - |_| unsafe { - let caption = frame_layout::install_caption_height(caption_row_height); - crate::trace::trace(&format!("caption height: {caption:?}")); - caption - }, - OnFailure::Continue, - false, - None, - ), - feature( - Feature::TopInset, - frame_layout::needs_top_inset, - |_| unsafe { - let top = frame_layout::install_top_inset(top_inset_extra); - crate::trace::trace(&format!("top inset: {top:?}")); - top - }, - OnFailure::Continue, - false, - None, - ), Step::Setup(|_| unsafe { if let Some(path) = trace_file("rivet-nav.log") { crate::trace::set_trace(path); @@ -2945,11 +2847,6 @@ fn attach_steps_for(page_view_only: bool) -> Vec> { if crate::trace::tracing() { crate::trace::trace_crashes(); } - crate::trace::trace(&format!( - "experiments: page view only {}, client area inset {:?}", - crate::features::layout_experiments::page_view_only(), - crate::features::layout_experiments::nccalcsize() - )); true }), Step::Setup(|_| unsafe { @@ -3013,7 +2910,7 @@ fn attach_steps_for(page_view_only: bool) -> Vec> { true }), Step::Setup(|attach| unsafe { - // A frame change makes the browser lay out its frame again, now through the layout hook. + // A frame change makes the browser lay out its frame again for the subclassed window. SetWindowPos( attach.window, std::ptr::null_mut(), @@ -3024,37 +2921,32 @@ fn attach_steps_for(page_view_only: bool) -> Vec> { SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, ); update_appbar(attach.window); - // Without the client view hook no browser layout tells Rivet where the panel is. - if crate::features::layout_experiments::page_view_only() { - place_panel_by_rivet(attach.window); - } + // No browser layout tells Rivet where the panel is, so Rivet places it. + place_panel_by_rivet(attach.window); true }), - ]; - if page_view_only { - steps.retain(|step| { - !matches!( - step, - Step::Feature(step) if matches!( - step.feature, - Feature::CaptionLayout | Feature::CaptionHeight | Feature::TopInset - ) - ) - }); + ] +} + +/// Whether Rivet can place the window's page view: only through the second view's record. A build +/// without it would leave the page under Rivet's surfaces, so it stays a plain browser window. +fn page_view_placeable(second_view: bool) -> Result<(), String> { + if second_view { + Ok(()) + } else { + Err("this browser build records no second view, so Rivet cannot place its page view".into()) } - steps } -/// Experiment: the panel of a window from its client area, placed by Rivet where the browser's -/// client view placement is not hooked. This also does what the hooked layout does for the window: -/// it records the layout's scale and lets a window that waits for its first layout show. +/// The panel of a window from its client area, placed by Rivet. This also records the layout's +/// scale and lets a window that waits for its first layout show. pub(crate) unsafe fn place_panel_by_rivet(window: HWND) { if !attached(window) || IsIconic(window) != 0 { return; } let mut client: RECT = std::mem::zeroed(); GetClientRect(window, &mut client); - let [width, height] = crate::features::layout_experiments::browser_dips( + let [width, height] = crate::features::page_view::browser_dips( window as isize, client.right, client.bottom, @@ -3080,9 +2972,9 @@ pub(crate) unsafe fn place_panel_by_rivet(window: HWND) { frame_layout::rivet_panel(bounds, reserved) }; crate::trace::trace_changed( - "experiment page view panel", + "page view panel", &format!( - "experiment page view only: client {}x{} px at {} dpi, panel {panel:?}", + "page view: client {}x{} px at {} dpi, panel {panel:?}", client.right, client.bottom, dpi(window) @@ -3092,75 +2984,6 @@ pub(crate) unsafe fn place_panel_by_rivet(window: HWND) { crate::features::second_view::note_layout(); } -/// Experiment: the inset Windows took from a window's client area, in DIPs at the window's layout -/// scale. Zero unless the client area experiment runs. -pub(crate) fn client_inset_dips(window: HWND) -> [i32; 2] { - let [left, top] = crate::features::layout_experiments::applied_inset(window as isize); - if left == 0 && top == 0 { - return [0, 0]; - } - let dpi = unsafe { layout_dpi(window) }.max(96) as i32; - [(left * 96 + dpi / 2) / dpi, (top * 96 + dpi / 2) / dpi] -} - -/// Experiment: answers `WM_NCCALCSIZE` with the browser's client area less the appbar's column, and -/// less the top row when asked, and moves Rivet's visuals back by the same amount. -unsafe fn shrink_client_area(window: HWND, wparam: WPARAM, lparam: LPARAM) -> LRESULT { - use crate::features::layout_experiments; - let result = call_browser(window, WM_NCCALCSIZE, wparam, lparam); - if wparam == 0 || lparam == 0 { - return result; - } - let inset = layout_experiments::nccalcsize(); - let leading = if framed(window) { - layout_of(window).leading() - } else { - 0 - }; - let top = crate::features::split::ROW_HEIGHT + frame_layout::PANEL_GAP; - let [left, top] = layout_experiments::nc_inset_pixels(inset, leading, top, dpi(window)); - // The first rect of `NCCALCSIZE_PARAMS` is the client rect the browser answered. - let rect = lparam as *mut RECT; - let before = [(*rect).left, (*rect).top, (*rect).right, (*rect).bottom]; - let after = layout_experiments::shrink_client(before, left, top); - (*rect).left = after[0]; - (*rect).top = after[1]; - let applied = [after[0] - before[0], after[1] - before[1]]; - let changed = layout_experiments::remember_inset(window as isize, applied); - crate::trace::trace_changed( - "experiment client area", - &format!( - "experiment client area: {inset:?} window {:#x} client {before:?} to {after:?}, \ - inset {applied:?} px at {} dpi, leading {leading} DIPs, changed {changed}", - window as usize, - dpi(window) - ), - ); - // A size message can arrive while the visuals are borrowed, so they are moved every time. - offset_visuals(window, applied); - result -} - -/// Experiment: moves the root of Rivet's visuals so they keep their place in the window while the -/// client area starts `inset` pixels further in. A visual left of or above the client area shows -/// only if the window's composition target draws outside the client area. -unsafe fn offset_visuals(window: HWND, inset: [i32; 2]) { - APPBARS.with(|appbars| { - if let Ok(appbars) = appbars.try_borrow() { - if let Some(appbar) = appbars.get(&(window as isize)) { - let done = appbar.offset_root(-inset[0] as f32, -inset[1] as f32); - crate::trace::trace_changed( - "experiment visuals", - &format!( - "experiment client area: Rivet's visuals moved by {:?} px: {done:?}", - [-inset[0], -inset[1]] - ), - ); - } - } - }); -} - unsafe fn create_appbar(window: HWND) { if attached(window) { return; @@ -3168,7 +2991,7 @@ unsafe fn create_appbar(window: HWND) { if let Some(path) = trace_file("rivet-vertical-tabs.log") { crate::trace::set_trace(path); } - // Without the layout hook the browser would draw underneath the appbar, so an unknown + // Without the build's frame view functions Rivet cannot tell a view's window, so an unknown // browser build keeps working without Rivet instead. let mut attach = Attach { window }; crate::feature::run(&attach_steps(), &mut attach, log); @@ -3727,13 +3550,6 @@ fn reserved_width(window: HWND, bounds: frame_layout::Rect) -> Option { } let leading = layout_of(window).leading(); LAID_LEADING.with(|all| all.borrow_mut().insert(window as isize, leading)); - // Where Windows already left the appbar's column out of the client area, the browser's - // layout reserves nothing more. - if crate::features::layout_experiments::nccalcsize() - != crate::features::layout_experiments::NcInset::Off - { - return Some(0); - } Some(leading) } } @@ -3912,8 +3728,7 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> if message == RegisterWindowMessageW(wide(crate::features::split::RELAYOUT_MESSAGE).as_ptr()) && attached(window) { - crate::hooks::page_area::relayout(window); - update_appbar(window); + relayout(window); return 0; } if message == RegisterWindowMessageW(wide("Rivet.ToggleSplit").as_ptr()) && attached(window) { @@ -4379,18 +4194,9 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> } 0 } - WM_NCCALCSIZE - if attached(window) - && crate::features::layout_experiments::nccalcsize() - != crate::features::layout_experiments::NcInset::Off => - { - shrink_client_area(window, wparam, lparam) - } WM_WINDOWPOSCHANGED if attached(window) => { let result = call_browser(window, message, wparam, lparam); - if crate::features::layout_experiments::page_view_only() { - place_panel_by_rivet(window); - } + place_panel_by_rivet(window); // Every browser sends this on a resize, so the second view follows it on all of them. follow_second_view(window); update_appbar(window); @@ -4461,7 +4267,6 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> KillTimer(window, SECOND_VIEW_TIMER); crate::features::second_view::forget(window); crate::features::sidebar_page::forget(window); - crate::features::pane_infobar::forget(window); LAYOUTS.with(|layouts| layouts.borrow_mut().remove(&(window as isize))); SLIDE.with(|slides| slides.borrow_mut().remove(&(window as isize))); DRAGGING.with(|set| set.borrow_mut().remove(&(window as isize))); @@ -4479,7 +4284,7 @@ unsafe fn handle(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> crate::features::page_links::forget(window); APPBAR_STATE.with(|states| states.borrow_mut().remove(&(window as isize))); frame_layout::forget_view(window); - crate::features::layout_experiments::forget(window as isize); + crate::features::page_view::forget(window as isize); crate::features::widgets::forget(window); crate::side_rail::forget(window); crate::features::mini_window::forget(window); @@ -5135,31 +4940,36 @@ mod tests { } #[test] - fn fr12_page_view_only_attaches_without_the_frame_layout_hooks() { + fn fr12_a_build_without_the_second_view_is_not_attached() { + // Rivet places the page view only through the second view, so such a build would leave + // the page under Rivet's surfaces. + assert_eq!(super::page_view_placeable(true), Ok(())); + assert!(super::page_view_placeable(false) + .is_err_and(|reason| reason.contains("no second view"))); + } + + #[test] + fn fr12_the_attach_places_the_page_without_the_browsers_layout() { use crate::feature::{Feature, Step}; - let features = |steps: Vec>| -> Vec { - steps - .iter() - .filter_map(|step| match step { - Step::Feature(step) => Some(step.feature), - Step::Setup(_) => None, - }) - .collect() - }; - let hooked = [ - Feature::CaptionLayout, - Feature::CaptionHeight, - Feature::TopInset, - ]; - let today = features(super::attach_steps_for(false)); - let experiment = features(super::attach_steps_for(true)); - for feature in hooked { - assert!(today.contains(&feature)); - assert!(!experiment.contains(&feature)); - } - // The frame view's functions are still found, so a view's window can be told. - assert!(experiment.contains(&Feature::FrameLayout)); - assert_eq!(today.len(), experiment.len() + hooked.len()); + let features: Vec = super::attach_steps() + .iter() + .filter_map(|step| match step { + Step::Feature(step) => Some(step.feature), + Step::Setup(_) => None, + }) + .collect(); + // The frame view's functions are still found, so a view's window can be told. No step + // changes the browser's own layout. + assert_eq!( + features, + [ + Feature::FrameLayout, + Feature::FrameColour, + Feature::CaptionPaint, + Feature::Split, + Feature::SplitLayout + ] + ); } #[test] diff --git a/rivet/runtime/windows/src/hooks/mod.rs b/rivet/runtime/windows/src/hooks/mod.rs deleted file mode 100644 index 8a17509..0000000 --- a/rivet/runtime/windows/src/hooks/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Hooks that more than one feature takes part in. - -pub(crate) mod page_area; diff --git a/rivet/runtime/windows/src/hooks/page_area.rs b/rivet/runtime/windows/src/hooks/page_area.rs deleted file mode 100644 index a2e233c..0000000 --- a/rivet/runtime/windows/src/hooks/page_area.rs +++ /dev/null @@ -1,508 +0,0 @@ -//! The hook on the browser's layout of the page area, which is shared by every feature that changes -//! where the page goes. The browser's own layout runs first. Then each step below gets the bounds it -//! produced and may change them, in this order and no other. - -use std::cell::RefCell; -use std::collections::HashMap; -use std::ffi::c_void; - -use windows_sys::Win32::Foundation::HWND; - -use crate::chromium::image; -use crate::chromium::memory::{prologue_is, readable}; -use crate::chromium::view::View; -use crate::features::frame_layout; - -thread_local! { - /// The host view each window's browser layout works on, so Rivet can ask for a layout. - static HOST_VIEWS: RefCell> = RefCell::new(HashMap::new()); - /// The vertical extent below the top row of each window, as (top, height) in the host view. - static AREAS: RefCell> = RefCell::new(HashMap::new()); -} - -fn row() -> &'static crate::builds::SidePanel { - &crate::builds::get().side_panel -} - -/// Where a window's page area is, in device-independent pixels of the window. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PageGeometry { - pub x: i32, - pub right: i32, - pub top: i32, - pub bottom: i32, -} - -/// The top of a window's page area in the browser view, as the layout recorded it. -pub fn area_top(window: HWND) -> Option { - AREAS.with(|areas| areas.borrow().get(&(window as isize)).map(|area| area.0)) -} - -/// The view the browser's layout last laid out for a window: the `views::View` of its -/// `BrowserView`, which is also its `BrowserWindow` part. -pub(crate) fn laid_out_host(window: HWND) -> Option { - HOST_VIEWS.with(|views| views.borrow().get(&(window as isize)).copied()) -} - -/// The page area of a window, below its top row, from the browser view's bounds and the extent -/// the layout recorded. -pub unsafe fn page_geometry(window: HWND) -> Option { - let host = HOST_VIEWS.with(|views| views.borrow().get(&(window as isize)).copied())?; - let (top, height) = AREAS.with(|areas| areas.borrow().get(&(window as isize)).copied())?; - // The page area lies in the browser view, so its origin is the sum of the bounds of the view and - // its ancestors, at the offsets this build keeps them. - let bounds_offset = crate::builds::get().layout.view_bounds_offset; - let parent_offset = View::parent_offset(bounds_offset)?; - let (mut x, mut y, mut width) = (0, 0, 0); - let mut view = host; - for depth in 0..16 { - if !readable(view + bounds_offset, 16) || !readable(view + parent_offset, 8) { - return None; - } - let bounds = View::at(view).bounds(bounds_offset); - x += bounds[0]; - y += bounds[1]; - if depth == 0 { - width = bounds[2]; - } - view = View::at(view).parent_address(parent_offset); - if view == 0 || !readable(view, 8) { - break; - } - } - Some(PageGeometry { - x, - right: x + width, - top: y + top, - bottom: y + top + height, - }) -} - -/// Where the bounds of the browser's views are when its layout has run. Chrome keeps them in a map -/// it applies afterwards, and Edge sets them on the views at once, so each has its own source. -pub(crate) trait LayoutBounds { - /// The bounds the layout gave the view, which a step may change. - unsafe fn of(&mut self, view: usize) -> Option<*mut [i32; 4]>; - /// Makes the changes of the steps take effect, once they all ran. - unsafe fn commit(&mut self) {} - /// Traces every view of the layout with the layout field that holds it. - unsafe fn dump(&self, _this: *const c_void, _trace: &dyn Fn(&str)) {} - /// Every view the layout placed, where the source can list them. - unsafe fn views(&self) -> Vec { - Vec::new() - } -} - -/// One run of the browser's layout, which the steps of the pipeline work on. -pub(crate) struct PageArea<'a> { - this: *mut c_void, - bounds: &'a mut dyn LayoutBounds, - pub window: HWND, - /// The width a step reserved at the right of the page area for the Sidebar's rail. - pub rail: i32, -} - -impl PageArea<'_> { - /// The view the layout object keeps at `offset`. - pub(crate) unsafe fn field(&self, offset: usize) -> usize { - if offset == crate::builds::ABSENT { - return 0; - } - *(self.this.cast::().add(offset) as *const usize) - } - - /// The bounds the layout gave the view that sits at `offset` of the layout object. - pub(crate) unsafe fn bounds(&mut self, offset: usize) -> Option<*mut [i32; 4]> { - let view = self.field(offset); - self.bounds.of(view) - } - - /// The bounds the layout gave the view of the pages, found by its class name or the row. - pub(crate) unsafe fn contents(&mut self) -> Option<*mut [i32; 4]> { - self.bounds(crate::chromium::window_views::contents_field()) - } - - /// The bounds the layout gave the area below the top row, found by its class name or the row. - pub(crate) unsafe fn page(&mut self) -> Option<*mut [i32; 4]> { - self.bounds(crate::chromium::window_views::page_area_field()) - } - - /// The bounds the layout gave every view it placed, where the source can list them. - pub(crate) unsafe fn all_bounds(&mut self) -> Vec<(usize, *mut [i32; 4])> { - let views = self.bounds.views(); - views - .into_iter() - .filter_map(|view| self.bounds.of(view).map(|bounds| (view, bounds))) - .collect() - } -} - -/// The steps that change the page area, in the order they run. The top bar takes its row, the Sidebar reserves its rail -/// next, and the pages of a split fill what is left. An extension page in the second view leaves -/// the browser's own panel no width, and the bars above the page keep to their pane. -const STEPS: [unsafe fn(&mut PageArea); 5] = [ - crate::features::address_bar::on_page_area, - crate::features::side_panel::on_page_area, - crate::features::sidebar_page::on_page_area, - crate::features::pane_infobar::on_page_area, - crate::features::split::on_page_area, -]; - -static DUMP_LAYOUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// Traces every view of the next layout with the layout field that holds it. -pub(crate) fn dump_next() { - DUMP_LAYOUT.store(true, std::sync::atomic::Ordering::Relaxed); -} - -fn trace(message: &str) { - crate::trace::trace(&format!("side panel: {message}")); -} - -/// The browser's own layout function, which the hook of the browser's family calls first. -pub(crate) fn original() -> usize { - ORIGINAL.load(std::sync::atomic::Ordering::Acquire) -} - -static ORIGINAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - -/// Runs the steps of the page area after the browser laid `host` out. `this` is the layout object. -pub(crate) unsafe fn run( - this: *mut c_void, - host: usize, - window: HWND, - bounds: &mut dyn LayoutBounds, -) { - HOST_VIEWS.with(|views| views.borrow_mut().insert(window as isize, host)); - // A layout without the recorded page container is traced once, which shows where it keeps it. - static DUMPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - let contents = crate::chromium::window_views::contents_field(); - let unknown = contents != crate::builds::ABSENT - && bounds - .of(*(this.cast::().add(contents) as *const usize)) - .is_none() - && crate::trace::tracing() - && !DUMPED.swap(true, std::sync::atomic::Ordering::Relaxed); - if DUMP_LAYOUT.swap(false, std::sync::atomic::Ordering::Relaxed) || unknown { - trace("layout dump"); - bounds.dump(this, &trace); - } - let mut area = PageArea { - this, - bounds, - window, - rail: 0, - }; - if let Some(page) = area.page() { - let page = *page; - AREAS.with(|areas| { - areas - .borrow_mut() - .insert(window as isize, (page[1], page[3])) - }); - } - let traced = |area: &mut PageArea| { - [ - crate::chromium::window_views::page_area_field(), - crate::chromium::window_views::contents_field(), - row().toolbar, - ] - .map(|offset| area.bounds(offset).map(|bounds| *bounds)) - }; - let before = traced(&mut area); - for step in STEPS { - step(&mut area); - } - let after = traced(&mut area); - crate::trace::trace_changed( - "page area", - &format!("page area: area, page, top row {before:?} to {after:?}"), - ); - area.bounds.commit(); -} - -/// Whether the row records the browser's layout. That alone decides the patch: the page area -/// serves the address bar, the split and the Sidebar, so a build whose Sidebar is off still moves -/// its page with the browser's own layout. A row that does without the layout holds no address -/// for it, or zero. -pub(crate) fn layout_recorded(layout_vtable: usize, proposed: usize) -> bool { - let recorded = |address: usize| address != crate::builds::ABSENT && address != 0; - recorded(layout_vtable) && recorded(proposed) -} - -/// Whether the patched layouts are enough for a caller, from what each patch answered. `tabbed` -/// is the patch of the layout the row's Sidebar part records, and `app` makes the patch of an app -/// window's own layout class. -/// -/// Where the build has an app layout class, a Rivet window is laid out by it alone, so the bar of -/// an app window needs only that patch and the tabbed one may be missing. A caller that asks for -/// any window takes the tabbed patch as before, and the app patch where the row has no tabbed -/// layout. An old-layout build lays out every window with the one class its row records, so -/// nothing changes there: the tabbed patch is needed, and an app window needs both. -pub(crate) fn relied_on( - app_window: bool, - old_layout: bool, - tabbed: Result<(), String>, - app: impl FnOnce() -> Result<(), String>, -) -> Result<(), String> { - match (app_window, old_layout) { - (true, true) => tabbed.and_then(|()| app()), - (true, false) => app(), - (false, true) => tabbed, - (false, false) => tabbed.or_else(|error| app().map_err(|_| error)), - } -} - -fn old_layout() -> bool { - row().old_layout == Some(true) -} - -/// Whether a layout of this process is patched, so the page area steps run after it. -fn patched() -> bool { - original() != 0 || crate::browsers::chromium::layout::app_layout_patched() -} - -/// Why the browser's layout is not patched in this process, when an experiment leaves it alone and -/// Rivet places the page view itself. -pub(crate) const LEFT_ALONE: &str = "the page view only experiment leaves the browser's layout alone"; - -fn left_alone() -> Result<(), String> { - left_alone_when(crate::features::layout_experiments::page_view_only()) -} - -fn left_alone_when(page_view_only: bool) -> Result<(), String> { - if page_view_only { - Err(LEFT_ALONE.into()) - } else { - Ok(()) - } -} - -/// Patches the layout of the page area once per process, for a caller that asks for any window: -/// the layout the row records, or else the app window's own. -pub(crate) unsafe fn install() -> Result<(), String> { - left_alone()?; - relied_on(false, old_layout(), install_tabbed(), || { - crate::features::omnibox::install_app_layout() - }) -} - -/// Patches the layout that lays out an app window, once per process. The tabbed layout is patched -/// too where the row records it, and only an old-layout build needs it. -pub(crate) unsafe fn install_for_app_window() -> Result<(), String> { - left_alone()?; - relied_on(true, old_layout(), install_tabbed(), || { - crate::features::omnibox::install_app_layout() - }) -} - -/// Patches the layout the row records, once per process. Without the recorded layout nothing -/// here runs. -unsafe fn install_tabbed() -> Result<(), String> { - const MISSING: &str = "this browser build has no recorded layout for the Sidebar"; - if !layout_recorded(row().layout_vtable, row().proposed) { - return Err(MISSING.into()); - } - if original() != 0 { - return Ok(()); - } - let Some(image) = image::recorded() else { - return Err(MISSING.into()); - }; - let base = image.base; - let slot_rva = row().layout_vtable + row().proposed_slot * 8; - if !image.points_to(slot_rva, row().proposed) { - return Err(MISSING.into()); - } - let slot = (base + slot_rva) as *mut usize; - let mut previous: windows_sys::Win32::System::Memory::PAGE_PROTECTION_FLAGS = 0; - if windows_sys::Win32::System::Memory::VirtualProtect( - slot.cast(), - 8, - windows_sys::Win32::System::Memory::PAGE_READWRITE, - &mut previous, - ) == 0 - { - return Err("could not unprotect the layout vtable".into()); - } - ORIGINAL.store(slot.read(), std::sync::atomic::Ordering::Release); - slot.write(crate::browsers::layout_hook()); - windows_sys::Win32::System::Memory::VirtualProtect(slot.cast(), 8, previous, &mut previous); - Ok(()) -} - -/// The browser view of a window, from the frame view the browser laid out last. The frame view holds -/// the `BrowserWindow` subobject of `BrowserView` and that subobject's address is the `views::View` -/// the browser's layout works on. -unsafe fn host_of(window: HWND) -> Option { - let frame = frame_layout::frame_view(window)?; - crate::chromium::window_views::frame_browser_view(frame, None) -} - -/// Lays the browser view out again, which runs the patched layout. A window the layout has not run -/// for yet is found through its frame view. Does nothing while no layout is patched. -pub(crate) unsafe fn relayout(window: HWND) { - let Some(image) = image::recorded() else { - return; - }; - if !patched() { - return; - } - let base = image.base; - let host = HOST_VIEWS - .with(|views| views.borrow().get(&(window as isize)).copied()) - .or_else(|| host_of(window)); - if let Some(host) = host.filter(|_| { - prologue_is( - base + row().layout_immediately, - row().layout_immediately_prologue, - ) - }) { - let layout: unsafe extern "system" fn(*mut c_void) = - std::mem::transmute(base + row().layout_immediately); - layout(host as *mut c_void); - } -} - -/// A browser that lays its view out without the proposed layout gives no page area, so the area is -/// the split view's own bounds in the window. -static OWN_AREAS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -unsafe fn window_position(view: usize) -> [i32; 2] { - let offset = crate::builds::get().layout.view_bounds_offset; - let Some(parent) = View::parent_offset(offset) else { - return [0, 0]; - }; - let (mut x, mut y, mut at) = (0, 0, view); - for _ in 0..16 { - if at == 0 { - break; - } - let bounds = *((at + offset) as *const [i32; 4]); - x += bounds[0]; - y += bounds[1]; - at = *((at + parent) as *const usize); - } - [x, y] -} - -pub(crate) unsafe fn remember_own_area(window: HWND, view: usize) { - // A patched layout already recorded the area, whichever layout class ran. - if area_top(window).is_some() { - return; - } - let [x, y] = window_position(view); - let bounds = *((view + crate::builds::get().layout.view_bounds_offset) as *const [i32; 4]); - let area = [x, y, x + bounds[2], y + bounds[3]]; - let mut all = OWN_AREAS.lock().unwrap_or_else(|error| error.into_inner()); - match all.iter_mut().find(|(key, _)| *key == window as isize) { - Some(entry) => entry.1 = area, - None => all.push((window as isize, area)), - } -} - -pub(crate) fn own_area(window: HWND) -> Option<[i32; 4]> { - OWN_AREAS - .lock() - .unwrap_or_else(|error| error.into_inner()) - .iter() - .find(|(key, _)| *key == window as isize) - .map(|(_, area)| *area) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Bounds that sit in a list, as a stand-in for the browser's own. - struct Listed(Vec<(usize, [i32; 4])>); - - impl LayoutBounds for Listed { - unsafe fn of(&mut self, view: usize) -> Option<*mut [i32; 4]> { - self.0 - .iter_mut() - .find(|(key, _)| *key == view) - .map(|(_, bounds)| bounds as *mut _) - } - } - - #[test] - fn fr10_an_old_layout_is_patched_without_the_sidebar_row() { - // Samsung Internet 143.0.4.29's old layout, whose Sidebar row is not supported. - assert!(layout_recorded(0x0E18_0BE0, 0x013C_8310)); - assert!(!layout_recorded(crate::builds::ABSENT, 0x013C_8310)); - assert!(!layout_recorded(0x0E18_0BE0, crate::builds::ABSENT)); - // A row made for a build whose tabbed layout was not found holds zero or no address. - assert!(!layout_recorded(0, 0x013C_8310)); - assert!(!layout_recorded(0x0E18_0BE0, 0)); - } - - fn missing() -> Result<(), String> { - Err("no tabbed layout".into()) - } - - fn no_app() -> Result<(), String> { - Err("no app layout".into()) - } - - #[test] - fn fr12_an_app_window_is_laid_out_without_the_tabbed_layout() { - // The row has no tabbed layout, and the app window's own layout class is patched. - assert_eq!(relied_on(true, false, missing(), || Ok(())), Ok(())); - // The tabbed patch alone never lays out an app window. - assert_eq!(relied_on(true, false, Ok(()), no_app), Err("no app layout".into())); - // The Sidebar's callers go on with either patch, and name the tabbed one when both fail. - assert_eq!(relied_on(false, false, missing(), || Ok(())), Ok(())); - assert_eq!(relied_on(false, false, missing(), no_app), Err("no tabbed layout".into())); - } - - #[test] - fn fr12_a_recorded_tabbed_layout_does_not_ask_for_the_app_patch() { - fn never() -> Result<(), String> { - panic!("the app layout was patched") - } - assert_eq!(relied_on(false, false, Ok(()), never), Ok(())); - assert_eq!(relied_on(false, true, Ok(()), never), Ok(())); - } - - #[test] - fn fr10_an_old_layout_build_still_needs_the_layout_its_row_records() { - // One class lays out every window of such a build, so the app patch is no substitute. - let no_tabbed = Err("no tabbed layout".to_owned()); - assert_eq!(relied_on(true, true, missing(), || Ok(())), no_tabbed); - assert_eq!(relied_on(false, true, missing(), || Ok(())), no_tabbed); - // An app window of such a build needs both, as before. - assert_eq!(relied_on(true, true, Ok(()), no_app), Err("no app layout".into())); - assert_eq!(relied_on(true, true, Ok(()), || Ok(())), Ok(())); - } - - #[test] - fn fr12_page_view_only_never_patches_the_page_area_layout() { - assert_eq!(left_alone_when(false), Ok(())); - assert_eq!(left_alone_when(true), Err(LEFT_ALONE.to_owned())); - // The address bar then moves the page view itself, on a build with the second view. - assert_eq!( - crate::features::address_bar::offset_for(left_alone_when(true), true), - crate::features::address_bar::Offset::PageView - ); - } - - #[test] - fn fr10_a_view_the_build_does_not_have_is_never_looked_up() { - // A layout object whose first word is a pointer a lookup would otherwise take for a view. - let object = [0x1234_5678usize; 4]; - let mut bounds = Listed(vec![(0x1234_5678, [1, 2, 3, 4])]); - let mut area = PageArea { - this: object.as_ptr() as *mut c_void, - bounds: &mut bounds, - window: 0 as HWND, - rail: 0, - }; - unsafe { - assert_eq!(area.field(0), 0x1234_5678); - assert_eq!(area.field(crate::builds::ABSENT), 0); - assert!(area.bounds(crate::builds::ABSENT).is_none()); - assert_eq!(*area.bounds(0).unwrap(), [1, 2, 3, 4]); - } - } -} diff --git a/rivet/runtime/windows/src/lib.rs b/rivet/runtime/windows/src/lib.rs index fe8604f..1eca9b6 100644 --- a/rivet/runtime/windows/src/lib.rs +++ b/rivet/runtime/windows/src/lib.rs @@ -362,8 +362,6 @@ mod frame; #[cfg(windows)] mod ground; #[cfg(windows)] -mod hooks; -#[cfg(windows)] mod installed_browsers; #[cfg(windows)] mod offscreen; diff --git a/rivet/runtime/windows/src/row_data.rs b/rivet/runtime/windows/src/row_data.rs index a1e3a63..7ba7eca 100644 --- a/rivet/runtime/windows/src/row_data.rs +++ b/rivet/runtime/windows/src/row_data.rs @@ -391,10 +391,7 @@ mod tests { assert_eq!(read.to_row(), row, "{} {:?}", build.browser, build.version); assert_eq!(read.version, build.version); assert_eq!(read.toolbar.get_color, build.toolbar.get_color); - assert_eq!( - read.layout.layout_immediately_prologue, - build.layout.layout_immediately_prologue - ); + assert_eq!(read.layout.on_paint_prologue, build.layout.on_paint_prologue); assert_eq!(read.layout.caption_ink_ids, build.layout.caption_ink_ids); } } @@ -417,18 +414,12 @@ mod tests { let mut row = builds::CHROME.to_row(); for (part, key) in [ ("layout", "frame_browser_window_offset"), - ("side_panel", "contents_container"), - ("side_panel", "host_view"), - ("side_panel", "page_area"), ("toolbar", "get_widget_slot"), ] { row[part].as_object_mut().unwrap().remove(key); } let build = builds::Build::from_row(&row).expect("a row without window offsets reads"); assert_eq!(build.layout.frame_browser_window_offset, None); - assert_eq!(build.side_panel.contents_container, None); - assert_eq!(build.side_panel.host_view, None); - assert_eq!(build.side_panel.page_area, None); assert_eq!(build.toolbar.get_widget_slot, None); } @@ -453,7 +444,7 @@ mod tests { Some("0x") ); assert!(row["layout"]["caption_ink_ids"][0].is_number()); - let bytes = row["layout"]["layout_immediately_prologue"].as_str().unwrap(); + let bytes = row["layout"]["on_paint_prologue"].as_str().unwrap(); assert!(!bytes.starts_with("0x") && bytes.len() % 2 == 0); assert!(row["version"][0].is_number()); } diff --git a/rivet/runtime/windows/src/side_rail.rs b/rivet/runtime/windows/src/side_rail.rs index d8a11c3..fb59a2f 100644 --- a/rivet/runtime/windows/src/side_rail.rs +++ b/rivet/runtime/windows/src/side_rail.rs @@ -45,7 +45,15 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{ use crate::appbar::Appbar; use crate::features::side_panel::{self as panel, PANEL_WIDTH, RAIL_WIDTH}; -use crate::hooks::page_area::PageGeometry; + +/// Where a window's page area is, in device-independent pixels of the window. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PageGeometry { + pub x: i32, + pub right: i32, + pub top: i32, + pub bottom: i32, +} const PAPER: u32 = 0xfbfaf7; const INK: u32 = 0x1f2024; @@ -787,20 +795,21 @@ pub(crate) unsafe fn page_and_open_zone(window: HWND) -> Option<([f32; 4], [f32; open_zone_at(right, bottom), )) } -/// The page area the rail is placed by. Where the second view is recorded, it narrows the page for -/// the rail itself, so the area comes from the page view and needs neither the browser's layout nor -/// its side panel. The rail's visual then covers the strip the page left, so no old page pixels show. -unsafe fn rail_geometry(window: HWND) -> Option { - if crate::features::second_view::available() { - let [x, top, right, bottom] = crate::features::second_view::full_page_area(window)?; - return Some(crate::hooks::page_area::PageGeometry { - x, - right, - top, - bottom, - }); +/// The page area the rail is placed by. The second view narrows the page for the rail itself, so +/// the area comes from the page view and needs neither the browser's layout nor its side panel. The +/// rail's visual then covers the strip the page left, so no old page pixels show. A build without +/// the second view has no rail. +unsafe fn rail_geometry(window: HWND) -> Option { + if !crate::features::second_view::available() { + return None; } - crate::hooks::page_area::page_geometry(window).filter(|_| panel::sidebar_checked()) + let [x, top, right, bottom] = crate::features::second_view::full_page_area(window)?; + Some(PageGeometry { + x, + right, + top, + bottom, + }) } /// Places and paints the rail and the open button of a window. Called with the other visuals of @@ -812,9 +821,10 @@ pub unsafe fn update(window: HWND, appbar: &Appbar, visible: bool, dpi: u32) { if let std::collections::hash_map::Entry::Vacant(e) = rails.entry(window as isize) { let Ok(rail) = Rail::new(appbar) else { return }; e.insert(rail); - // The page area is known once the browser has laid out with the patched layout. - if let Err(error) = crate::hooks::page_area::install() { - crate::trace::trace(&format!("side rail: {error}")); + if !crate::features::second_view::available() { + crate::trace::trace( + "side rail: this browser build records no second view, so it has no rail", + ); } if let Err(error) = panel::install_page_colours() { crate::trace::trace(&format!("side rail: {error}")); @@ -1140,10 +1150,8 @@ unsafe extern "system" fn poll(window: HWND, _: u32, _: usize, _: u32) { match unknown { None => {} Some(Unknown::Relayout) => { - // Not laid out since the layout hook went in. Lay out outside any layout of the - // browser's, a few times at most: a layout repaints the whole browser window. + // The page view has not been placed yet. Ask again a few times at most. crate::features::activity::count(crate::features::activity::Counter::RailRelayout); - crate::hooks::page_area::relayout(window); crate::frame::update_appbar(window); return; } diff --git a/scripts/tests/layers.baseline b/scripts/tests/layers.baseline index a47b235..a0b4c6f 100644 --- a/scripts/tests/layers.baseline +++ b/scripts/tests/layers.baseline @@ -1,10 +1,9 @@ # Feature layer violations per file: . # Written by scripts/tests/layers.test.sh --update. Counts may only go down. -rivet/runtime/windows/src/features/address_bar.rs rows 1 -rivet/runtime/windows/src/features/address_bar.rs unsafe 29 -rivet/runtime/windows/src/features/address_bar.rs windows_sys 11 +rivet/runtime/windows/src/features/address_bar.rs unsafe 28 +rivet/runtime/windows/src/features/address_bar.rs windows_sys 10 rivet/runtime/windows/src/features/app_window.rs rows 10 -rivet/runtime/windows/src/features/app_window.rs unsafe 24 +rivet/runtime/windows/src/features/app_window.rs unsafe 23 rivet/runtime/windows/src/features/app_window.rs windows_sys 4 rivet/runtime/windows/src/features/bubble_anchor.rs rows 2 rivet/runtime/windows/src/features/bubble_anchor.rs unsafe 6 @@ -19,11 +18,11 @@ rivet/runtime/windows/src/features/dev_page.rs windows_sys 5 rivet/runtime/windows/src/features/dev_tools.rs rows 2 rivet/runtime/windows/src/features/dev_tools.rs unsafe 4 rivet/runtime/windows/src/features/dev_tools.rs windows_sys 1 -rivet/runtime/windows/src/features/frame_layout.rs rows 75 -rivet/runtime/windows/src/features/frame_layout.rs unsafe 45 +rivet/runtime/windows/src/features/frame_layout.rs rows 43 +rivet/runtime/windows/src/features/frame_layout.rs unsafe 23 rivet/runtime/windows/src/features/frame_layout.rs windows_sys 5 rivet/runtime/windows/src/features/link_preview.rs unsafe 13 -rivet/runtime/windows/src/features/link_preview.rs windows_sys 3 +rivet/runtime/windows/src/features/link_preview.rs windows_sys 2 rivet/runtime/windows/src/features/link_rules.rs unsafe 10 rivet/runtime/windows/src/features/link_rules.rs windows_sys 3 rivet/runtime/windows/src/features/link_tabs.rs rows 2 @@ -32,40 +31,33 @@ rivet/runtime/windows/src/features/link_tabs.rs windows_sys 2 rivet/runtime/windows/src/features/look.rs unsafe 6 rivet/runtime/windows/src/features/look.rs windows_sys 3 rivet/runtime/windows/src/features/mini_window.rs unsafe 27 -rivet/runtime/windows/src/features/mini_window.rs windows_sys 25 +rivet/runtime/windows/src/features/mini_window.rs windows_sys 23 rivet/runtime/windows/src/features/navigation.rs rows 19 rivet/runtime/windows/src/features/navigation.rs unsafe 17 rivet/runtime/windows/src/features/navigation.rs windows_sys 1 rivet/runtime/windows/src/features/omnibox.rs rows 4 -rivet/runtime/windows/src/features/omnibox.rs unsafe 27 +rivet/runtime/windows/src/features/omnibox.rs unsafe 26 rivet/runtime/windows/src/features/omnibox.rs windows_sys 1 rivet/runtime/windows/src/features/page_links.rs rows 2 rivet/runtime/windows/src/features/page_links.rs unsafe 13 rivet/runtime/windows/src/features/page_links.rs windows_sys 2 -rivet/runtime/windows/src/features/pane_infobar.rs rows 1 -rivet/runtime/windows/src/features/pane_infobar.rs unsafe 2 -rivet/runtime/windows/src/features/pane_infobar.rs windows_sys 1 rivet/runtime/windows/src/features/second_view.rs unsafe 83 -rivet/runtime/windows/src/features/second_view.rs windows_sys 7 +rivet/runtime/windows/src/features/second_view.rs windows_sys 5 rivet/runtime/windows/src/features/settings.rs unsafe 19 rivet/runtime/windows/src/features/settings.rs windows_sys 4 -rivet/runtime/windows/src/features/side_panel.rs rows 61 +rivet/runtime/windows/src/features/side_panel.rs rows 52 rivet/runtime/windows/src/features/side_panel.rs unsafe 26 rivet/runtime/windows/src/features/side_panel.rs windows_sys 4 -rivet/runtime/windows/src/features/sidebar_page.rs rows 1 -rivet/runtime/windows/src/features/sidebar_page.rs unsafe 5 +rivet/runtime/windows/src/features/sidebar_page.rs unsafe 4 rivet/runtime/windows/src/features/sidebar_page.rs windows_sys 1 rivet/runtime/windows/src/features/split.rs rows 2 -rivet/runtime/windows/src/features/split.rs unsafe 17 -rivet/runtime/windows/src/features/split.rs windows_sys 4 +rivet/runtime/windows/src/features/split.rs unsafe 16 +rivet/runtime/windows/src/features/split.rs windows_sys 3 rivet/runtime/windows/src/features/tab_list.rs unsafe 17 rivet/runtime/windows/src/features/tab_list.rs windows_sys 1 rivet/runtime/windows/src/features/tabs.rs rows 56 rivet/runtime/windows/src/features/tabs.rs unsafe 52 rivet/runtime/windows/src/features/tabs.rs windows_sys 5 -rivet/runtime/windows/src/features/vertical_tabs.rs rows 41 -rivet/runtime/windows/src/features/vertical_tabs.rs unsafe 21 -rivet/runtime/windows/src/features/vertical_tabs.rs windows_sys 8 rivet/runtime/windows/src/features/widgets.rs rows 6 rivet/runtime/windows/src/features/widgets.rs unsafe 4 rivet/runtime/windows/src/features/widgets.rs windows_sys 1 From 22375e4a0fa720be4b384f5c1079764ec1ec9607 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:53:35 +0000 Subject: [PATCH 29/29] Publish: develop 50c0017 to release Generated by .github/scripts/release/sync-release.sh. The internal planning documents listed below are kept on develop only: PROJECT.md AGENTS.md docs/INTENT.md docs/RESEARCH.md docs/SPEC.md scripts/tests/appspike --- rivet/platform/windows/src/hold.rs | 5 +---- rivet/runtime/windows/src/builds/tests.rs | 4 ++-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/rivet/platform/windows/src/hold.rs b/rivet/platform/windows/src/hold.rs index aeee1aa..ee3f701 100644 --- a/rivet/platform/windows/src/hold.rs +++ b/rivet/platform/windows/src/hold.rs @@ -27,14 +27,11 @@ const HOLD_GRANTS: [&str; 2] = ["*S-1-15-2-1:(OI)(CI)(RX)", "*S-1-15-2-2:(OI)(CI /// The builds whose complete row is written by hand in the runtime's code. Rows the table job /// records come from the checked-in table instead, so recording one needs no change here. The /// runtime's tests compare `verified` with its rows, so the launcher and the runtime cannot disagree. -const HAND_ROWS: [(&str, Version); 10] = [ +const HAND_ROWS: [(&str, Version); 7] = [ ("chrome.exe", [157, 0, 8103, 38]), ("chrome.exe", [156, 0, 8078, 80]), ("chrome.exe", [156, 0, 8078, 74]), - ("chrome.exe", [156, 0, 8078, 48]), - ("msedge.exe", [156, 0, 4314, 50]), ("whale.exe", [5, 39, 412, 57]), - ("brave.exe", [156, 1, 98, 62]), ("brave.exe", [156, 1, 98, 63]), ("brave.exe", [157, 1, 99, 55]), ("samsunginternet.exe", [30, 0, 4, 29]), diff --git a/rivet/runtime/windows/src/builds/tests.rs b/rivet/runtime/windows/src/builds/tests.rs index 0be0e74..c5f9665 100644 --- a/rivet/runtime/windows/src/builds/tests.rs +++ b/rivet/runtime/windows/src/builds/tests.rs @@ -113,10 +113,10 @@ fn nfr3_chrome_156_frame_paint_prologues_match_the_installed_build() { fn nfr6_the_launcher_opens_exactly_the_complete_rows() { use rivet_platform_windows::hold::{module_of, table_versions, verified}; let verified = verified(); - // Chrome 150 only keeps the frame hooks, so a window of it would not have Rivet's top row. + // Rivet places the page itself in its second view, so a row without it opens no Rivet window. let complete: Vec<_> = all() .iter() - .filter(|build| !std::ptr::eq(**build, &CHROME_150)) + .filter(|build| build.app_window.is_some()) .collect(); assert_eq!( complete.len(),