How to properly patch a PE file?

I’d like to patch some PE file to do some extra things. First, though for the sake of testing I’m just going to add just a simple Message Box to the code. What I’ve done for that so far:

Added a new section to the file using the IDA – “Add segment”, then set required flags with CFF Explorer:

enter image description here

Added a super simple code in the new section (just a function):

![enter image description here

and finally changed the original main function just to call my new function:

enter image description here

The problem is that when i run the debugger (in IDA) the added function address is somehow changed from the proper address () to sth. like that:

![enter image description here

As can be seen the first byte is somehow changed during process run from 00 to 0D!

Why does this happens and how to fix the code the main successfully call my function?

  • 2

    Time to learn about relocations.

    – 

  • 3

    Aside: I don’t think add sp, sp is going to do you any favors.

    – 

  • If you calculate the relative displacement from the call instruction to _my_fun based on the file offsets, IIC, that becomes invalid when you run the PE because the loader loads the sections using RVAs.

    – 

  • @JonathonReinhart. Yeah, ok thx for REALLY GREAT suggestion, but Can You put in a little more effort and and propose a solution or at least elaborate the topic a little more?

    – 

  • @jtxkopt Ok, so the great question is HOW to fix it?

    – 

Leave a Comment