Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58491

Patch an executable file

In short

What would be the easiest way to make sure that the high word of ecx contains 0 by replacing following instruction in the exe file?

004044be 0fbf4dfc        movsx   ecx,word ptr [ebp-4]

Instead of containing FFFF9298 after executing adress 004044be I'd like ecx to contain 00009298.

What have I tried

I have tried replacing movsx with a simple movby replacing the opcode 0fbf in the executable with 8b0c but that didn't work out as planned (using the debugger to verify the change, I'm sure it was at the the right place)

Some background

I have a rather old program that for one reason or another AV's when I try to print to my HP printer. Everything works fine when I print to CutePDF so the current workaround is to generate a PDF file and print the PDF.

Getting my feet wet with WinDbg I tried to find the reason of why this was happening. While this is not the root cause of my problem, it seems that ecx at some point get's a negative value which is used to allocate memory, ultimately resulting in an exception.

I could try to find why a negative value is returned but during my debugging session, I noticed that zeroing out the high word in ecx did the job (aka printed the file).

So instead of containing FFFF9298 after executing adress 004044be I'd like ecx to contain 00009298.

004044ac 0fbf05e8025100  movsx   eax,word ptr [Encore32!SystemsPerPageDlogProc+0x10e4a1 (005102e8)]
004044b3 05416f0000      add     eax,6F41h
004044b8 668945fc        mov     word ptr [ebp-4],ax
004044bc 6a40            push    40h
004044be 0fbf4dfc        movsx   ecx,word ptr [ebp-4] --> replace with ?
004044c2 51              push    ecx
004044c3 8b55f8          mov     edx,dword ptr [ebp-8]
004044c6 52              push    edx

Upvotes: 1

Views: 1564

Answers (2)

nrz
nrz

Reputation: 10580

movsx mean "move with sign extend". That means that the top bit of src is copied to all high bits of dest. You don't want that.

movzx fills top bits with 0.

movzx ecx,word ptr [ebp-4] is what you need. Using 32-bit code as in your example it can be encoded as 0F B7 4D FC.

Upvotes: 3

Igor Skochinsky
Igor Skochinsky

Reputation: 25318

Use movzx, it does exactly what you need.

The opcode (for 16->32 version) is 0F B7 /r so just patching BF to B7 should do it.

Upvotes: 3

Related Questions