From a04427af61c5e22dd2b02c0acb1d63d26f28a037 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:03:11 +0900 Subject: [PATCH 1/5] Feat: Read a views class's virtual function from its table slot once a second views table lines the slot up alike --- rivet/platform/windows/src/row_port.rs | 6 +- rivet/platform/windows/src/row_resolve.rs | 153 +++++++++++++++++++++- 2 files changed, 155 insertions(+), 4 deletions(-) diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs index 9e2c2ae..85ada44 100644 --- a/rivet/platform/windows/src/row_port.rs +++ b/rivet/platform/windows/src/row_port.rs @@ -1658,7 +1658,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..a6fcf15 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 @@ -536,6 +540,45 @@ 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 candidate tables whose slots hold the same functions as the old table, and how many agree. fn by_slots( old: &Side, @@ -688,6 +731,7 @@ pub enum Method { Slots, ClassName, Fingerprint, + SlotShift, } impl fmt::Display for Method { @@ -701,6 +745,7 @@ impl fmt::Display for Method { Method::Slots => "its slots", Method::ClassName => "its class name", Method::Fingerprint => "its fingerprint", + Method::SlotShift => "its slot shift", }) } } @@ -820,14 +865,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); @@ -922,6 +969,9 @@ 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)); } @@ -1326,7 +1376,14 @@ pub(crate) mod tests { class: None, }, )]); - resolve(&old, &new, &known, &wanted, &BTreeSet::from([OLD_TABLE])) + resolve( + &old, + &new, + &known, + &wanted, + &BTreeSet::from([OLD_TABLE]), + &BTreeSet::new(), + ) } #[test] @@ -1381,6 +1438,96 @@ 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, + }, + )]); + 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}"); + } + #[test] fn nfr6_a_place_outside_the_fingerprint_matches_is_refused() { let answers = [(Method::CallsInto, 0x103300), (Method::TableSlot, 0x103300)]; From a98cfbe9b92ea279a8d81698c327505442464412 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:06:22 +0900 Subject: [PATCH 2/5] Feat: Read the frame, caption, corner and browser view class tables from the window's live views --- .../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 + 5 files changed, 415 insertions(+), 7 deletions(-) create mode 100644 rivet/runtime/windows/src/chromium/live_tables.rs 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 eaf1742accf660319a280112111eb50503622b83 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:11:10 +0900 Subject: [PATCH 3/5] Feat: Find chrome::NewTab from the new tab command's case in the browser's command switch --- rivet/platform/windows/src/lib.rs | 1 + rivet/platform/windows/src/row_command.rs | 476 ++++++++++++++++++++++ rivet/platform/windows/src/row_port.rs | 35 +- rivet/platform/windows/src/row_resolve.rs | 55 ++- 4 files changed, 563 insertions(+), 4 deletions(-) create mode 100644 rivet/platform/windows/src/row_command.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..ac428d7 --- /dev/null +++ b/rivet/platform/windows/src/row_command.rs @@ -0,0 +1,476 @@ +//! 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 85ada44..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"); diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index a6fcf15..cdb3afa 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -22,9 +22,11 @@ //! - 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. +//! - 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. @@ -732,6 +734,7 @@ pub enum Method { ClassName, Fingerprint, SlotShift, + Command, } impl fmt::Display for Method { @@ -746,6 +749,7 @@ impl fmt::Display for Method { Method::ClassName => "its class name", Method::Fingerprint => "its fingerprint", Method::SlotShift => "its slot shift", + Method::Command => "its command id", }) } } @@ -809,6 +813,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 @@ -933,6 +943,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); @@ -975,6 +1009,17 @@ pub fn resolve( if let Some(place) = by_text(&texts_of[&target], &users) { answers.push((Method::Text, 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) { @@ -1374,6 +1419,8 @@ pub(crate) mod tests { kind: Kind::Function, candidates: Some(NEW_TARGETS.to_vec()), class: None, + command: None, + loose: Vec::new(), }, )]); resolve( @@ -1495,6 +1542,8 @@ pub(crate) mod tests { kind: Kind::Function, candidates: None, class: None, + command: None, + loose: Vec::new(), }, )]); let tables = BTreeSet::from([VIEW_TABLE, OTHER_VIEW_TABLE]); From 1f176228e39295f10583fc4833c675852d882f41 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:12:18 +0900 Subject: [PATCH 4/5] Feat: Place a drawing helper by the call its known caller makes to one of its fingerprint places --- rivet/platform/windows/src/row_resolve.rs | 116 ++++++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index cdb3afa..c07de85 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -22,6 +22,12 @@ //! - 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; +//! - 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 @@ -581,6 +587,36 @@ fn by_slot_shift( 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, @@ -735,6 +771,7 @@ pub enum Method { Fingerprint, SlotShift, Command, + KnownCaller, } impl fmt::Display for Method { @@ -750,6 +787,7 @@ impl fmt::Display for Method { Method::Fingerprint => "its fingerprint", Method::SlotShift => "its slot shift", Method::Command => "its command id", + Method::KnownCaller => "a known caller", }) } } @@ -925,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(); @@ -1009,6 +1055,13 @@ pub fn resolve( if let Some(place) = by_text(&texts_of[&target], &users) { answers.push((Method::Text, place)); } + if let (Some(list), Some(from)) = (&want.candidates, prior_callers.get(&target)) { + let given = by_known_callers(&mut new, &known, from, list); + answers.extend(fingerprint_agrees(&given, Some(list))); + 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 @@ -1577,6 +1630,69 @@ pub(crate) mod tests { 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)]; From 86d20839eb99255ded2f45ff261111ff13aced66 Mon Sep 17 00:00:00 2001 From: BREW <81044362+b-re-w@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:14:04 +0900 Subject: [PATCH 5/5] Fix: Compare slices of one type in the command switch and known caller readings --- rivet/platform/windows/src/row_command.rs | 53 ++++++++++++++++++----- rivet/platform/windows/src/row_resolve.rs | 5 ++- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/rivet/platform/windows/src/row_command.rs b/rivet/platform/windows/src/row_command.rs index ac428d7..5a46bb9 100644 --- a/rivet/platform/windows/src/row_command.rs +++ b/rivet/platform/windows/src/row_command.rs @@ -70,14 +70,18 @@ fn table_jump(bytes: &[u8], at: usize, rva: u32) -> Option { 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] }; + 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]) { + 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)); } @@ -86,7 +90,10 @@ fn above_before(bytes: &[u8], end: usize, base: u32) -> Option<(usize, u32)> { let [0x77, rel] = *bytes.get(start..end)? else { return None; }; - Some((start, rip_target(base + start as u32, 2, i32::from(rel as i8))?)) + 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. @@ -125,13 +132,13 @@ fn lowest_before(bytes: &[u8], end: usize) -> i64 { }; let skip = usize::from(matches!(code.first(), Some(0x40..=0x4F)) && code.len() > 1); let rest = &code[skip..]; - let value = match rest { + 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)) + 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), @@ -277,7 +284,9 @@ pub fn command_place_in( .map(|(switch, _)| switch.lowest) .collect(); if lowest.is_empty() { - return Err(format!("no switch of the prior build sends command {id} to it")); + return Err(format!( + "no switch of the prior build sends command {id} to it" + )); } let others = prior .iter() @@ -369,7 +378,10 @@ pub(crate) mod tests { 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_SWITCH, + switch_code(OTHER_SWITCH, 34000, 40, OTHER_TABLE), + ), (other_case, case_code(other_case, ELSEWHERE)), (DEFAULT, vec![0xC3]), (BACK, vec![0xC3]), @@ -402,9 +414,17 @@ pub(crate) mod tests { 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(); + let dispatch = found + .iter() + .find(|switch| switch.at == DISPATCH + 17) + .unwrap(); assert_eq!( - (dispatch.lowest, dispatch.bound, dispatch.table, dispatch.default), + ( + 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)); @@ -454,7 +474,10 @@ pub(crate) mod tests { 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}"); + assert!( + reason.starts_with("only its command id found it"), + "{reason}" + ); } #[test] @@ -463,10 +486,16 @@ pub(crate) mod tests { 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)); + 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}"); + 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(); diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs index c07de85..6e5cc49 100644 --- a/rivet/platform/windows/src/row_resolve.rs +++ b/rivet/platform/windows/src/row_resolve.rs @@ -1055,9 +1055,10 @@ pub fn resolve( if let Some(place) = by_text(&texts_of[&target], &users) { answers.push((Method::Text, place)); } - if let (Some(list), Some(from)) = (&want.candidates, prior_callers.get(&target)) { + 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))); + answers.extend(fingerprint_agrees(&given, Some(list.as_slice()))); for place in given { answers.push((Method::KnownCaller, place)); }