1

I'm currently disassembling some firmware, when I stumbled across the following code snippet produced by Ghidra (the names are already my own ones):

void memset(byte *addr,byte value,int count)
                            assume LRset = 0x0
                            assume TMode = 0x1
  undefined         r0:1           <RETURN>                                
  byte *            r0:4           addr                                    
  byte              r1:1           value
  int               r2:4           count
  undefined4        r0:4           iPtr                                    

22 b1           cbz        count,LAB_FIN
02 44           add        count,addr
                      LAB_LOOP
00 f8 01 1b     strb.w     value,[iPtr],#0x1
90 42           cmp        iPtr,count
fb d1           bne        LAB_LOOP
                      LAB_FIN  
70 47           bx         lr
00              ??         00h
bf              ??         BFh

Ghidra's decompiler produces the following output (after setting some types):

void memset(byte *addr,byte value,int count)
{
  byte *iPtr;

  if (count != 0) {
    iPtr = addr;
    do {
      iPtr = iPtr + 1;
      *iPtr = value;                // write to iPtr AFTER the pointer was increased
      iPtr = iPtr;
    } while (iPtr != addr + count);
  }
  return;
}

Now, I have two questions:

  1. The decompiled function suggests that this memset function will not set the given address (addr) to the specified value, but will always start with addr+1. This, however, doesn't feel right and as far as I understand the strb.w instruction it uses post-indexing. Therefore - I think - the order of the pointer-increment and the assignment instruction is wrong. Am I right or do I miss something?

  2. After the bx instruction there are two further bytes. I don't have the slightest idea what they are. Given that they are not "00" I don't think that they are (solely) used for alignment purposes. (The next function definitively starts directly after these two bytes.) Does anyone have an idea?

0

Indeed, it seems to be incorrect. The syntax [R0],#1 is called post-indexed: first the store (or load) is performed, and then the base address is incremented (or decremented) by the value specified. So the assignment and increment should be swapped.

As for 00 BF, it is the opcode for the NOP instruction, probably inserted to align next function on a 4-byte boundary.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.