Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ARMv7 Word Patch (CBNZ)

Tags:

arm

I have an iPhone app that I am disassembling.

It is my understanding that a CBNZ instruction is "Compare and Branch on Non-Zero." and a CBZ is "Compare and Branch on Zero"

I can not find anywhere online to confirm this but to me it seems that CBNZ is represented by B9 in an address like so "0x B9 DC" and CBZ is "0x B3 DC".

The full address is: DC B9 53 48 03 99 78 44 00 68 BF F1 74 EE 51 49

I am modifying it to: DC B3 53 48 03 99 78 44 00 68 BF F1 74 EE 51 49

Previously I had patched this same check in ARMv6 though it was represented by a BNE "0x D1 30" that I patched to a B "0x E0 32"

This: 32 D1 5B 48 5C 49 78 44 79 44 00 68 09 68 AC F1

To: 32 E0 5B 48 5C 49 78 44 79 44 00 68 09 68 AC F1

This behaved exactly how I expected to, taking the branch and continuing on as I wanted it to. Normally it only takes such branch if it passes a check.

I figured patching a CBNZ to a CBZ would have similar results though it seems not.

Hope someone can help me understand. Sorry if this is not a forum where I should post questions like this though it seems like a good place to ask. If you need more info I will be happy to provide.

like image 732
Untouchable Avatar asked Feb 14 '12 15:02

Untouchable


1 Answers

To understand the assembly, you need to go to bit level. If you don't want to spend time to understand the ARM encoding, get a disassembler (e.g. otool -tV) and an assembler (e.g. as) and they will figure out the instruction encoding/decoding for you.


The encoding of the CBZ/CBNZ instructions are

15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0   <-- bit
 1  0  1  1 op  0  i  1 [         imm5][     Rn]  <-- meaning

where op = 1 means CBNZ, op = 0 means CBZ, 'i :imm5:0' is the relative address to jump, and Rn is the register to check (see ARMv7-ARM §A8.6.27).

Therefore, the word B9DC, in binary,

(1  0  1  1 op  0  i  1 [         imm5][     Rn])
 1  0  1  1  1  0  0  1 [1  1  0  1  1][1  0  0]

means

  • op = 1
  • i = 0
  • imm5 = 11011
  • Rn = 100

means

CBNZ R4, (PC+54)   ; 54 = 0b0110110

while B3DC, in binary,

(1  0  1  1 op  0  i  1 [         imm5][     Rn])
 1  0  1  1  0  0  1  1 [1  1  0  1  1][1  0  0]

means

  • op = 0
  • i = 1
  • imm5 = 11011
  • Rn = 100

means

CBZ R4, (PC+118)  ; 118 = 0b1110110

Note that your patch B9B3 changed the i bit as well, which changed the address it should jump to. You should only change the op bit, meaning you should patch the byte as B1.

like image 98
kennytm Avatar answered Oct 10 '22 02:10

kennytm