Skip to content

Instantly share code, notes, and snippets.

@kleptog
Created April 20, 2024 13:35
Show Gist options
  • Save kleptog/7174a84c0a2343e3b8ed0f4c660aefef to your computer and use it in GitHub Desktop.
Save kleptog/7174a84c0a2343e3b8ed0f4c660aefef to your computer and use it in GitHub Desktop.
Python script to validate haproxy optimisation
# Based on https://github.com/haproxy/haproxy/blob/50d8c187423d6b7e9b1083e05370885f6d12e844/src/h1.c#L578
test_nums = list(range(0x20, 0x27)) + list(range(0x7b, 0x81))
def test1(a, b, c, d):
# What I expected the code to skip given the comment
return all([0x24 <= a <= 0x7e, 0x24 <= b <= 0x7e,0x24 <= c <= 0x7e,0x24 <= d <= 0x7e])
def test3(a, b, c, d):
# What it actually does skip
return all([0x24 <= a, 0x24 <= b, 0x24 <= c, 0x24 <= d]) and any([a <= 0x7e, b <= 0x7e, c <= 0x7e, d <= 0x7e])
def test2(a, b, c, d):
# Shortcut in haproxy code
n = (a << 24) + (b << 16) + (c << 8) + d
n1 = n = (n - 0x24242424) & 0xFFFFFFFF
if n & 0x80808080:
return False, n1, 0
n2 = n = (n - 0x5b5b5b5b) & 0xFFFFFFFF
if not (n & 0x80808080):
return False, n1, n2
return True, n1, n2
def test4(a, b, c, d):
# Corrected shortcut in haproxy code
n = (a << 24) + (b << 16) + (c << 8) + d
n1 = (n - 0x24242424) & 0xFFFFFFFF
if n1 & 0x80808080:
return False, n1, 0
n2 = (~n - ~0x7e7e7e7e) & 0xFFFFFFFF
if (n2 & 0x80808080):
return False, n1, n2
return True, n1, n2
for a in test_nums:
for b in test_nums:
for c in test_nums:
for d in test_nums:
r1 = test1(a, b, c, d)
r2, n1, n2 = test2(a, b, c, d)
r3 = test3(a, b, c, d)
r4, n3, n4 = test4(a, b, c, d)
if r2 != r3:
# Never hit
print("XXX")
if r1 != r4:
# Never hit
print("XXX")
print("%X%X%X%X %5s %5s %5s%s %5s%s %08X %08X %08X" % (
a, b, c, d,
r1, r2,
r3, ("*" if r2 != r3 else " "),
r4, ("*" if r1 != r4 else " "),
n1, n2, n4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment