binaryninja-api icon indicating copy to clipboard operation
binaryninja-api copied to clipboard

Simplify common conditional expression

Open plafosse opened this issue 1 year ago • 8 comments

I'm seeing a lot of this type of condition repeated that should be easy to simplify

(!A || (A && B)) Which simplifies down to just !A || B Similarly (A || (!A && B)) => A || B

plafosse avatar Feb 19 '24 13:02 plafosse

BNDB Shared internally cascade blueprint lantern mosaic has the following conditional at: 100002f37

image

plafosse avatar Feb 19 '24 13:02 plafosse

Added in 4.1.5232

D0ntPanic avatar May 03 '24 20:05 D0ntPanic

Looks like the demorgan's variant of this case is still not handled

image

180022bbc In the unicorn chess taco rainbow binary

plafosse avatar May 10 '24 17:05 plafosse

So to clarify: The original equation if ((((rax_69 == 0x8007007a || rax_69 == 0x80020013) && rax_55 s>= 0) || (rax_69 != 0x8007007a && rax_69 != 0x80020013)) && rdi s< 0) A = (rax_69 == 0x8007007a || rax_69 == 0x80020013) !A = (rax_69 != 0x8007007a && rax_69 != 0x80020013) B = rax_55 s>= 0 C = rdi s< 0 This boils down to: ((A && B) || !A) && C We dont' care about C so we can drop it and rewrite the equation ((A && B) || !A) which can convert to (B || !A)

The final equation can be simplified down to:

if ((rax_55 s>= 0 || (rax_69 != 0x8007007a && rax_69 != 0x80020013)) && rdi s< 0)

plafosse avatar May 10 '24 18:05 plafosse

Another variant from the unicorn chess taco rainbow binary:

18000c304 if ((*(this + 0x2940) == 0 && result_5 s>= 0 && i != 0) || (*(this + 0x2940) != 0 && (i_1 u>= r13_1 || result_4 s>= 0) && i_1 u>= r13_1))

Substitute the following:

A = *(this + 0x2940) == 0
B = result_5 s>= 0 && i != 0
C = (i_1 u>= r13_1 || result_4 s>= 0) && i_1 u>= r13_1)

We get the equation: (A & B) | (!A & C) Can be translated to (A & B) | C

plafosse avatar May 16 '24 15:05 plafosse

Simliarly from the same binary:

18000c304                      if ((i_1 u>= r13_1 || result_4 s>= 0) && i_1 u< r13_1)

Substitute the following

A = i_1 u>= r13_1
B = result_4 s>= 0
C = i_1 u< r13_1

We get (A || B) && !A Which simplifies down to B && !A

plafosse avatar May 16 '24 16:05 plafosse

Any attempt to implement Quine-McCluskey algorithm?

uniquadev avatar May 21 '24 07:05 uniquadev

@uniquadev I wasn't familiar with that algorithm until you mentioned it. That looks very interesting, thanks for the tip! We do have some additional constraints that we need to deal such as keeping a mapping of addresses from the original bytes.

plafosse avatar Jun 25 '24 12:06 plafosse

These types of conditions are far more rare with the new control flow algorithm in 4.1, so the optimization is much less essential now.

D0ntPanic avatar Jul 02 '24 21:07 D0ntPanic