Skip to content

Reverse engineeringguide

Optical-sensor register tables in mouse firmware and diffing them against datasheet lists

An optical mouse sensor is configured over a serial bus by writing lists of register and value pairs: one list at power-up and others when the mode, polling rate or resolution changes. The manufacturer’s datasheet prints these lists. The firmware’s copy can match them, differ in a few values, carry extra writes or lack some, and which of those holds is what an analyst wants to know. This guide finds the lists in a firmware image, puts the datasheet’s lists in the same form and compares the two in order.

Sensor datasheets are copy-restricted, so this page quotes none of their registers, values or text. Every register, value and threshold below is made up. Transcribe the datasheet lists you need from your own copy into your own files. The code is Python 3 and runs on a machine without the sensor or the mouse. It assumes a raw Cortex-M firmware image whose code is visible at its run address; if the firmware runs code from random-access memory (RAM), replay the boot copies first, or the inline lists in that code will not be found where you look.

For a mouse patched through its sensor settings, see Patching an nRF52840 gaming mouse’s firmware, which rewrites sensor registers that the stock firmware re-applies.

TermMeaning
Register writeOne step: write a value to a register address on the sensor’s bus.
Bank selectA write to a reserved register that switches which bank of registers the following writes address. The same register number means different things in different banks, so a step is identified by bank, register and value.
BracketA pair of writes on one register that opens a list (a mode-enter value) and closes it (a mode-exit value). A list often starts and ends with the same bank select and register.
WaitA pseudo-step: pause a number of milliseconds. In firmware it is a delay call, not a bus write.
PollA pseudo-step: read a register until it equals a value.
Bit-field writeA datasheet step that sets only some bits of a register, written as a field such as bits 3 to 2. Firmware writes the whole byte, so one datasheet step matches a full-byte write whose field bits agree.
Computed writeA firmware step whose value is calculated at run time, typically a read-modify-write: read, mask, set bits, write.

A list is a script, so its order is part of the content. A bank select placed after the register it should have preceded changes the meaning of every step between them.

Data table: an array of records in flash, read by a loop and sent through one write routine. A common record is three bytes: register, value and a flag. The flag is 0 for a plain write. A reserved register number marks a pseudo-step, and the flag then says what it is: a number of milliseconds to wait, or a register to poll. A table of tables, a run of (pointer, count) word pairs, lets a selector pick a list by index.

Inline code: the list is a function body. Every step compiles to loading the register into one register, the value into another and calling the write routine:

movs r0, #0x7e ; register
movs r1, #0x02 ; value
bl write_reg

There is no table to find, only hundreds of calls to one routine. A scan that looks only for data tables finds nothing in such an image. In an audit of 69 images, a data-table scan with several record widths found one partial list in one image and nothing in the others; the complete lists in the images I read came from decoding code.

The rest of the page uses a made-up 13-step list assembled into a Thumb function and a made-up datasheet list. The firmware function, disassembled:

00001000 <init_list>:
1000: b500 push {lr}
1002: 207e movs r0, #126 @ 0x7e
1004: 2102 movs r1, #2
1006: f000 f833 bl 1070 <write_reg>
100a: 2040 movs r0, #64 @ 0x40
100c: 2101 movs r1, #1
100e: f000 f82f bl 1070 <write_reg>
...

Here 0x7e is the made-up bank-select register, write_reg is at 0x1070 and a delay routine is at 0x1080.

Start where the bus is driven. The routine that writes one register byte over the bus is called from hundreds of places in one function family, with a constant in each of two registers before the call. In a decompile it is the function with the highest caller count that touches the bus peripheral. Note its address. Firmware sometimes has more than one write convention: register-indirect calls through a pointer, or a routine with an extra device argument. Each convention needs its own decoder.

Scan the image at every byte offset for runs of records. Three-byte records with a flag are the common form, so require a flag byte of 0 on ordinary records, at least about 20 records and at least three bank selects in a run; a two-byte form has no flag byte to reject noise and needs more bank selects, around eight. Anchor on the bracket: the open pair and the close pair are usually the same across the lists of one family, with the odd list opening differently.

Lists often sit back to back in one run. Cut a run after a bank select that returns to the default bank and is directly followed by another bank select. A list that ends any other way cannot be cut without the pointer table, so find it: consecutive (pointer, count) word pairs where each pointer is a found table start and each count is that table’s entry count. A pointer table also tells you how many lists exist and in what order the selector indexes them.

For inline code, decode the function as straight-line Thumb. Track the two constants as they are loaded, and emit a step at every call to the write routine. Treat a write to the bank-select register as changing the current bank; BANK in the script is the made-up register 0x7e. The script below does this for a function with no branches, and prints one step per line in the form used by the diff:

#!/usr/bin/env python3
"""Turn an inline register-write list (movs r0,#reg ; movs r1,#val ; bl write_reg) into steps.
usage: extract_inline.py IMAGE LOAD_ADDR START WRITE_REG DELAY_MS (addresses in hex)
Straight-line decode only: no branches, no register moves.
"""
import struct, sys
img = open(sys.argv[1], "rb").read()
load, start, write_reg, delay_ms = (int(a, 16) for a in sys.argv[2:6])
BANK = 0x7E # made-up bank-select register for this example
def bl_target(pc, hw1, hw2):
s, j1, j2 = (hw1 >> 10) & 1, (hw2 >> 13) & 1, (hw2 >> 11) & 1
imm = (s << 24) | ((~(j1 ^ s) & 1) << 23) | ((~(j2 ^ s) & 1) << 22) | ((hw1 & 0x3FF) << 12) | ((hw2 & 0x7FF) << 1)
return pc + 4 + (imm - (1 << 25) if s else imm)
steps, bank, r0, r1, pc = [], None, None, None, start
while pc - load < len(img):
hw1 = struct.unpack_from("<H", img, pc - load)[0]
hw2 = struct.unpack_from("<H", img, pc - load + 2)[0] if pc - load + 4 <= len(img) else 0
if hw1 & 0xFF00 == 0x2000:
r0 = hw1 & 0xFF
elif hw1 & 0xFF00 == 0x2100:
r1 = hw1 & 0xFF
elif hw1 & 0xF800 == 0xF000 and hw2 & 0xD000 == 0xD000:
t = bl_target(pc, hw1, hw2)
if t == write_reg:
if r0 == BANK:
bank = r1
steps.append(("write", bank, r0, r1))
elif t == delay_ms:
steps.append(("wait", bank, r0, None))
pc += 2 # the BL is 4 bytes
elif hw1 == 0xBD00: # pop {pc}: end of the function
break
pc += 2
for kind, bank, reg, val in steps:
print(f"w {bank} 0x{reg:02x} 0x{val:02x}" if kind == "write" else f"d {reg}")

On the example it prints the firmware list:

w 2 0x7e 0x02
w 2 0x40 0x01
w 0 0x7e 0x00
w 0 0x10 0x33
w 0 0x11 0x20
w 0 0x12 0x00
w 3 0x7e 0x03
w 3 0x20 0x05
d 1
w 3 0x21 0x44
w 3 0x23 0x48
w 2 0x7e 0x02
w 2 0x40 0x00

Calls to the delay routine become d lines. This sketch handles constants only and straight-line code. Real lists need more:

  • A branch inside a list needs a path explorer that follows both forks and carries the constants along each path.
  • A call clobbers r0 to r3 and r12 under the Arm procedure call standard,1 so a constant loaded before a call is not valid after it. Reload it, or your tracker will repeat a stale value.
  • A computed value is a read-modify-write. Record the masks it clears and sets when they are constants, so the diff can compare the bits it fixes with a datasheet bit-field step.

Check the extraction against the bytes. Search the image for the instruction pattern of the opening writes: each occurrence should have an extracted list, and an occurrence without one means a decoder miss.

Step 4: put the datasheet lists in the same form

Section titled “Step 4: put the datasheet lists in the same form”

Write each datasheet list into a text file, one step per line: w BANK REG VALUE for a full-byte write, b BANK REG HI:LO VALUE for a bit-field write and d MS for a wait. Transcribing a list of a hundred steps or more is slow, and a typo shows up as a difference, so check each file against the datasheet by eye. Keep these files out of anything you publish.

# made-up list A: kind bank reg value ; w = full-byte write, b = bit-field write (reg hi:lo value), d = wait ms
w 2 0x7e 0x02
w 2 0x40 0x01
w 0 0x7e 0x00
w 0 0x10 0x33
w 0 0x11 0x24
w 3 0x7e 0x03
w 3 0x20 0x05
w 3 0x22 0x01
d 1
w 3 0x21 0x44
b 3 0x23 3:2 0x2
w 2 0x7e 0x02
w 2 0x40 0x00

A positional comparison reports every step after an inserted write as different. An ordered diff finds the longest common subsequence (LCS) of the two lists, weighted so that an exact match scores 2 and a match in the same place with another value scores 1. Steps outside that alignment are reported as present on one side only. The ratio, twice the number of equal steps over the sum of both lengths, summarises it. A bit-field datasheet step matches a firmware full-byte write of the same bank and register when the field’s bits agree.

#!/usr/bin/env python3
"""Ordered diff of a firmware write list against candidate datasheet lists.
usage: diff_lists.py FIRMWARE.txt LIST.txt [LIST.txt ...]
A line is: w BANK REG VAL | b BANK REG HI:LO VAL | d MS. '#' starts a comment.
"""
import sys
def load(path):
steps = []
for line in open(path):
f = line.split("#")[0].split()
if not f:
continue
if f[0] == "w":
steps.append(("w", int(f[1]), int(f[2], 0), int(f[3], 0), None))
elif f[0] == "b":
hi, lo = (int(x) for x in f[3].split(":"))
steps.append(("b", int(f[1]), int(f[2], 0), int(f[4], 0), (hi, lo)))
else:
steps.append(("d", None, int(f[1]), None, None))
return steps
def score(fw, ds):
"""0 = different step, 1 = same place but another value, 2 = same step and value."""
k, bank, reg, val, field = ds
if fw[0] == "d" or k == "d":
return (2 if fw[2] == reg else 1) if fw[0] == k == "d" else 0
if fw[0] != "w" or fw[1] != bank or fw[2] != reg: # the firmware always writes whole bytes
return 0
if k == "b":
hi, lo = field
return 2 if (fw[3] >> lo) & ((1 << (hi - lo + 1)) - 1) == val else 1
return 2 if fw[3] == val else 1
def show(s):
if s[0] == "d":
return f"wait {s[2]} ms"
return f"bank {s[1]} reg 0x{s[2]:02x} = 0x{s[3]:02x}"
def describe(f, d):
if f[0] == "d":
return f"wait {f[2]} ms in firmware, {d[2]} ms in list"
return f"bank {f[1]} reg 0x{f[2]:02x}: firmware 0x{f[3]:02x}, list 0x{d[3]:02x}"
def diff(fw, ds):
n, m = len(fw), len(ds)
best = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
w = score(fw[i], ds[j])
best[i][j] = max(best[i + 1][j], best[i][j + 1], best[i + 1][j + 1] + w if w else 0)
ops, equal, i, j = [], 0, 0, 0
while i < n or j < m:
w = score(fw[i], ds[j]) if i < n and j < m else 0
if w and best[i][j] == best[i + 1][j + 1] + w:
if w == 2:
equal += 1
else:
ops.append(f"differs fw step {i + 1}, list step {j + 1}: {describe(fw[i], ds[j])}")
i, j = i + 1, j + 1
elif i < n and (j == m or best[i][j] == best[i + 1][j]):
ops.append(f"fw only fw step {i + 1}: {show(fw[i])}")
i += 1
else:
ops.append(f"list only list step {j + 1}: {show(ds[j])}")
j += 1
return equal, 2 * equal / (n + m), ops
fw = load(sys.argv[1])
for path in sys.argv[2:]:
ds = load(path)
equal, ratio, ops = diff(fw, ds)
naive = sum(1 for a, b in zip(fw, ds) if score(a, b) != 2)
print(f"{path}: {equal} equal of {len(fw)} firmware / {len(ds)} list steps, ratio {ratio:.2f}; compared by position, {naive} steps differ")
for op in ops:
print(" ", op)

Run on the example firmware list and the datasheet list:

Terminal window
python3 diff_lists.py fw.txt ds_a.txt
ds_a.txt: 11 equal of 13 firmware / 13 list steps, ratio 0.85; compared by position, 4 steps differ
differs fw step 5, list step 5: bank 0 reg 0x11: firmware 0x20, list 0x24
fw only fw step 6: bank 0 reg 0x12 = 0x00
list only list step 8: bank 3 reg 0x22 = 0x01

A positional diff would flag 4 steps. The ordered diff finds 3 differences: one changed value, one write that only the firmware has and one that only the datasheet has. The bit-field step on bank 3 register 0x23 counted as equal because the firmware’s byte has the field’s bits set to the listed value. The wait, which has no register, matched on its duration.

Pass several candidate lists to one run to find which datasheet list a firmware list equals. When several datasheet lists share most of their content, a best match picks the first of a tie, so its label is not evidence of anything.

Datasheets publish lists by condition: a power or performance mode, a polling rate, a resolution band. The firmware picks one with a selector function, so equal-content tells you which datasheet list the firmware carries and the selector tells you when it is applied. Read the selector in the decompile. Its inputs are typically a mode byte, a polling-rate code, a wired or wireless flag and a resolution value compared against one or two thresholds. Record for each list:

  1. The datasheet list it equals by content, with the diff.
  2. The selector inputs that reach it, with the thresholds as written in the code.

Earlier notes of mine labelled two lists as a pair by report rate. By content they matched the datasheet’s lists for two different modes, a high-performance one and a low-power one, so the label said nothing about when the firmware used them. The selector, not the label, says that. Another note described ten large variants and listed twelve addresses where the image held thirteen mode lists. Counting lists from the scan, not by hand, avoids that.

A made-up selector shows the shape:

void apply_mode(uint8_t rate_code, uint16_t res, bool wired) {
if (rate_code == 0x40) run(res < 1500 ? list_c1 : list_c2);
else if (rate_code == 0x20) run(list_p);
else run(wired ? list_w : list_l);
}

The list names are mine. The compared conditions are the evidence. Resolution bands deserve the same care: three lists that differ in a few registers each are the same mode in three bands, and the threshold between bands is in the selector, not in the file.

  • A firmware value that differs from the datasheet is deliberate tuning, a typo or a different part variant, and the diff cannot say which. The ID (identifier) register the firmware reads at start-up, and whether the same difference appears in other builds, narrows it.
  • A partial list in flash data with no pointer to it is flagged, not trusted. In one image such a fragment looked like the start of a mode list and had no referent.
  • “No data table in any of these images” is scoped to the record widths and anchors that were scanned. State them with the result.
  1. Arm, “Procedure Call Standard for the Arm Architecture,” AAPCS32. https://github.com/ARM-software/abi-aa/blob/main/aapcs32/aapcs32.rst ↩