#!/bin/sh
#
# qcom-ab-slot -- the A/B slot flags of a Qualcomm ABL phone, from Linux.
#
#   qcom-ab-slot status               the flags of boot_a and boot_b
#   qcom-ab-slot mark-successful [-n] mark the running slot successful
#                                     (-n: check and show, write nothing)
#
# The bootloader keeps the slot state in byte 6 of the GPT attributes of the
# slot's partitions (qbootctl gpt-utils.h, ../docs/reference/qbootctl.txt):
# bits 0-1 priority, bit 2 active, bits 3-5 retry count, bit 6 successful,
# bit 7 unbootable.  It counts the retry count down on every boot of a slot
# that is not successful and stops on an unbootable slot without falling
# back (docs/BOOT.md); marking the slot successful ends the count-down.
#
# This sets the successful bit in boot_<slot> only, the partition fastboot
# reports the slot state from (getvar slot-successful), in the primary and
# the backup GPT, and recomputes their CRCs -- the edit qbootctl's
# mark_boot_successful makes, which also sets it on the slot's other A/B
# partitions.  The running slot is the active one: this ABL passes no
# androidboot.slot_suffix.  Before writing, both GPTs are checked (signature,
# header and entry CRCs, equal entry arrays, the entry's name), the sectors
# are saved to /var/lib/qcom-ab-slot, and afterwards read back and checked
# again.  CRC32 is gzip's (the same polynomial as GPT's, in its trailer).

set -eu
PATH=/usr/bin:/usr/sbin:/bin:/sbin

LABELS=/dev/disk/by-partlabel
SAVE=/var/lib/qcom-ab-slot
W=

die() { echo "qcom-ab-slot: $*" >&2; exit 1; }

cleanup() { [ -z "$W" ] || rm -rf "$W"; }
trap cleanup EXIT

# u FILE OFFSET u1|u4|u8: unsigned little-endian integer
u() { od -An -t "$3" -j "$2" -N "${3#u}" "$1" | tr -d ' \n'; }

# putle FILE OFFSET VALUE NBYTES: write a little-endian integer into FILE
putle() {
	_v=$3 _n=$4
	{
		while [ "$_n" -gt 0 ]; do
			printf "\\$(printf %03o $((_v & 255)))"
			_v=$((_v >> 8)) _n=$((_n - 1))
		done
	} | dd of="$1" bs=1 seek="$2" conv=notrunc 2>/dev/null
}

crc32() { gzip -n -c < "$1" | tail -c 8 | od -An -t u4 -N 4 | tr -d ' \n'; }

# part LABEL: sets P (partition), DISK, N (number), SS (sector size)
part() {
	P=$(readlink -f "$LABELS/$1") || die "no partition $1"
	[ -b "$P" ] || die "no partition $1"
	_b=${P##*/}
	DISK=/dev/$(basename "$(readlink -f "/sys/class/block/$_b/..")")
	N=$(cat "/sys/class/block/$_b/partition")
	SS=$(cat "/sys/class/block/${DISK##*/}/queue/logical_block_size")
}

# readgpt TAG LBA: header sector to $W/TAG.hdr, entry sectors to $W/TAG.ent,
# the exact entry array to $W/TAG.arr; checks both CRCs.  Sets ELBA, ESEC,
# ESZ, CNT, HSZ, and ALT (the other header's LBA; the next readgpt
# overwrites it, so a caller keeps it in BAK).
readgpt() {
	_h=$W/$1.hdr
	dd if="$DISK" of="$_h" bs="$SS" skip="$2" count=1 2>/dev/null
	[ "$(dd if="$_h" bs=8 count=1 2>/dev/null)" = "EFI PART" ] ||
		die "$DISK: no GPT header at LBA $2"
	HSZ=$(u "$_h" 12 u4)
	[ "$HSZ" -ge 92 ] && [ "$HSZ" -le "$SS" ] || die "$DISK: header size $HSZ"
	dd if="$_h" of="$W/$1.chk" bs="$HSZ" count=1 2>/dev/null
	putle "$W/$1.chk" 16 0 4
	[ "$(crc32 "$W/$1.chk")" = "$(u "$_h" 16 u4)" ] ||
		die "$DISK: $1 header CRC mismatch"
	[ "$(u "$_h" 24 u8)" = "$2" ] || die "$DISK: $1 header is not at LBA $2"
	ALT=$(u "$_h" 32 u8)
	ELBA=$(u "$_h" 72 u8) CNT=$(u "$_h" 80 u4) ESZ=$(u "$_h" 84 u4)
	ESEC=$(( (CNT * ESZ + SS - 1) / SS ))
	dd if="$DISK" of="$W/$1.ent" bs="$SS" skip="$ELBA" count="$ESEC" 2>/dev/null
	dd if="$W/$1.ent" of="$W/$1.arr" bs="$ESZ" count="$CNT" 2>/dev/null
	[ "$(crc32 "$W/$1.arr")" = "$(u "$_h" 88 u4)" ] ||
		die "$DISK: $1 entry array CRC mismatch"
	eval "${1}_ELBA=\$ELBA"
}

# fixcrc TAG: entry CRC from TAG.ent into TAG.hdr, then the header CRC
fixcrc() {
	dd if="$W/$1.ent" of="$W/$1.arr" bs="$ESZ" count="$CNT" 2>/dev/null
	putle "$W/$1.hdr" 88 "$(crc32 "$W/$1.arr")" 4
	putle "$W/$1.hdr" 16 0 4
	dd if="$W/$1.hdr" of="$W/$1.chk" bs="$HSZ" count=1 2>/dev/null
	putle "$W/$1.hdr" 16 "$(crc32 "$W/$1.chk")" 4
}

# flags LABEL: the attribute byte of LABEL's entry, from the primary GPT
flags() {
	part "$1"
	W=$(mktemp -d)
	readgpt pri 1
	_o=$(( (N - 1) * ESZ ))
	_name=$(dd if="$W/pri.arr" bs=1 skip=$((_o + 56)) count=72 2>/dev/null | tr -d '\000')
	[ "$_name" = "$1" ] || die "$DISK: entry $N is '$_name', not $1"
	u "$W/pri.arr" $((_o + 54)) u1
	rm -rf "$W"; W=
}

show() {	# LABEL BYTE
	printf '%s: 0x%02x priority=%d active=%d retry=%d successful=%d unbootable=%d\n' \
		"$1" "$2" $(($2 & 3)) $((($2 >> 2) & 1)) $((($2 >> 3) & 7)) \
		$((($2 >> 6) & 1)) $((($2 >> 7) & 1))
}

status() {
	for s in a b; do
		show "boot_$s" "$(flags "boot_$s")"
	done
}

mark_successful() {
	dry=$1
	slot=
	for s in a b; do
		f=$(flags "boot_$s")
		[ $(((f >> 2) & 1)) = 1 ] || continue
		[ -z "$slot" ] || die "both slots active"
		slot=$s
	done
	[ -n "$slot" ] || die "no active slot"
	label=boot_$slot

	part "$label"
	W=$(mktemp -d)
	readgpt pri 1
	BAK=$ALT
	readgpt bak "$BAK"
	[ "$ALT" = 1 ] || die "$DISK: backup header does not point back to LBA 1"
	cmp -s "$W/pri.arr" "$W/bak.arr" || die "$DISK: primary and backup entries differ"

	o=$(( (N - 1) * ESZ ))
	old=$(u "$W/pri.arr" $((o + 54)) u1)
	show "$label" "$old"
	[ $(((old >> 7) & 1)) = 0 ] || die "$label is unbootable, not touching it"
	if [ $(((old >> 6) & 1)) = 1 ]; then
		echo "$label: already successful"
		return 0
	fi
	new=$((old | 0x40))
	for t in pri bak; do
		putle "$W/$t.ent" $((o + 54)) "$new" 1
		fixcrc "$t"
	done
	cmp -s "$W/pri.arr" "$W/bak.arr" || die "internal: entry arrays differ after the edit"
	show "$label (new)" "$new"
	if [ "$dry" = 1 ]; then
		echo "dry run: $DISK not written"
		return 0
	fi

	# keep what was there: the sectors as read, before the edit
	mkdir -p "$SAVE"
	stamp=$(date +%Y%m%d-%H%M%S)
	for t in pri bak; do
		eval "_e=\$${t}_ELBA"
		_l=1; [ "$t" = pri ] || _l=$BAK
		dd if="$DISK" of="$SAVE/${DISK##*/}-$stamp-$t-hdr-lba$_l" bs="$SS" skip="$_l" count=1 2>/dev/null
		dd if="$DISK" of="$SAVE/${DISK##*/}-$stamp-$t-ent-lba$_e" bs="$SS" skip="$_e" count="$ESEC" 2>/dev/null
	done

	# each header goes to the LBA it names itself
	[ "$(u "$W/pri.hdr" 24 u8)" = 1 ] && [ "$(u "$W/bak.hdr" 24 u8)" = "$BAK" ] ||
		die "internal: header LBAs do not match where they would be written"

	# backup first: until the primary is written, the primary is the old,
	# valid table.  udev re-reads the disk after each write, so the kernel
	# may log "Alternate GPT is invalid" once, between the backup entries
	# and the backup header; it uses the primary then, and the next re-read
	# is clean (measured 2026-11-07).
	dd if="$W/bak.ent" of="$DISK" bs="$SS" seek="$bak_ELBA" conv=notrunc,fsync 2>/dev/null
	dd if="$W/bak.hdr" of="$DISK" bs="$SS" seek="$BAK" conv=notrunc,fsync 2>/dev/null
	dd if="$W/pri.ent" of="$DISK" bs="$SS" seek="$pri_ELBA" conv=notrunc,fsync 2>/dev/null
	dd if="$W/pri.hdr" of="$DISK" bs="$SS" seek=1 conv=notrunc,fsync 2>/dev/null
	sync

	# read back through a fresh view and check again
	echo 3 > /proc/sys/vm/drop_caches
	rm -rf "$W"; W=$(mktemp -d)
	readgpt pri 1
	BAK=$ALT
	readgpt bak "$BAK"
	cmp -s "$W/pri.arr" "$W/bak.arr" || die "$DISK: entries differ after writing"
	got=$(u "$W/pri.arr" $((o + 54)) u1)
	[ "$got" = "$new" ] || die "$DISK: wrote 0x$(printf %02x "$new"), read 0x$(printf %02x "$got")"
	show "$label (written)" "$got"
	echo "saved the old sectors in $SAVE/${DISK##*/}-$stamp-*"
}

case "${1:-}" in
status)
	status ;;
mark-successful)
	if [ "${2:-}" = -n ]; then mark_successful 1; else mark_successful 0; fi ;;
*)
	echo "usage: qcom-ab-slot status | mark-successful [-n]" >&2
	exit 2 ;;
esac
