#!/bin/bash
#
# Applies the peak login crash fix to a libcef.so.
#
# Background:
# CEF bug 151.3.16 - hash_set::find() in libcef+0x6200f40 does not
# return "AccessiblePDFForm" and the result is dereferenced without
# a NULL check. This causes a SIGSEGV during Google/YouTube login.
#
# Fix: NULL check before dereferencing at file offset 0x61fff55
#      (VA 0x6200f55, .text delta VA = file + 0x1000).
#
# old (11 bytes):  48 8b 40 10 5d c3 cc cc cc cc cc
#   mov 0x10(%rax),%rax   / pop %rbp / ret / pad
# new (11 bytes):  48 85 c0 74 04 48 8b 40 10 5d c3
#   test %rax,%rax / je +4 / mov 0x10(%rax),%rax / pop %rbp / ret

set -e

OFFSET=0x61fff55
OLD="48 8b 40 10 5d c3 cc cc cc cc cc"
NEW="48 85 c0 74 04 48 8b 40 10 5d c3"

if [ $# -ne 1 ]; then
	echo "usage: $0 /path/to/libcef.so" >&2
	exit 1
fi

F="$1"

if [ ! -f "$F" ]; then
	echo "error: $F does not exist" >&2
	exit 1
fi

CUR=$(dd if="$F" bs=1 skip=$((OFFSET)) count=11 2>/dev/null | od -An -v -tx1 | tr -d ' \n')

if [ "$CUR" = "$(echo $NEW | tr -d ' ')" ]; then
	echo "OK: $F is already patched (fix is active)"
	exit 0
fi

if [ "$CUR" != "$(echo $OLD | tr -d ' ')" ]; then
	echo "error: $F has unexpected bytes at offset $OFFSET:" >&2
	echo "  found:    $CUR" >&2
	echo "  expected: $OLD" >&2
	echo "  -> wrong libcef version? fix only for CEF 151.3.16" >&2
	exit 1
fi

echo "$NEW" | xxd -r -p -s $((OFFSET)) - | dd of="$F" bs=1 seek=$((OFFSET)) conv=notrunc status=none
echo "OK: fix applied to $F"
