Log in

View Full Version : How to write array-elements using a loop in MASM32?


profdracula
January 13th, 2005, 09:24
Hi all!

I'm a newbee to ASM-coding. I'm writing a patch for an app, but don't know how to write bytes(from an array) to the target-app using a loop. My code writes first byte at required offset sucessfully. But how to write remaining bytes? [ Of course Offsets are also at random locations in EXE].

Part of my code is:

bytPatch DB Byte1, Byte2,.............., Byte-n
ofsOffset DD Offset1, Offset2,.........., Offset-n

;----------------------------------------------------------------]
invoke SetFilePointer, hFile, ofsOffset, 0, 0
.IF eax==-1
;Handle-error
.ENDIF
invoke WriteFile, hFile, offset bytPatch, 1, offset bWrite, 0
.IF !eax
;Handle-error
.ENDIF
;----------------------------------------------------------------]

lifewire
January 13th, 2005, 10:47
Code:

mov esi, offset sourcearray
mov edi, offset destination
mov ecx,size
rep movsb

profdracula
January 13th, 2005, 11:24
Thanx lifewire!

Can you tell me where i put this in my code and how does this loop terminate?

JimmyClif
January 13th, 2005, 13:12
Quote:
[Originally Posted by profdracula]Hi all!

I'm a newbee to ASM-coding. I'm writing a patch for an app, but don't know how to write bytes(from an array) to the target-app using a loop. My code writes first byte at required offset sucessfully. But how to write remaining bytes? [ Of course Offsets are also at random locations in EXE].


If you have many places to patch and you want to use WriteFile you could do it the following way:

Code:

;;;;>>>Untested Code<<<;;;;;;

BytesToPatch db 03,a1 ; lenght == 2
db c1,d1,d1 ; lenght == 3
db 90 ; lenght == 1
db 90,90, ab, cd ; lenght == 4
db etc...

LenghtsToPatch dd 02, 03, 01, 04

OffsetsToPatch dd 00492321, 00987652, etc.... , 0 ; terminating 0 for the while loop ending at WHILE [EDI] != 0


mov edi, OffsetsToPatch
mov esi, BytesToPatch
mov ebx, LenghtsToPatch
.WHILE [edi] != 0
invoke SetFilePointer, hFile, [edi] , 0, 0
.IF eax==-1
;Handle-error
.ENDIF
invoke WriteFile, hFile, [esi] , [ebx], offset bWrite, 0
.IF !eax
;Handle-error
.ENDIF
add edi, 4
add esi, [ebx]
add ebx, 4
.ENDW


Now this code will load the offset of the PatchLocations into EDI, after each SetFilePointer & WriteFile we will add 4 to EDI so it points to the next OffsetLocation and then we restart the loop.

This code will have all the bytes to change in one big declaration, I split them up by how many bytes are in per location... This BytesToPatch will get loaded into ESI. At the end of the loop I add to ESI the number of bytes that Location needs to patch, which for me EBX keeps track for.

I used ESI, EDI and EBX because these registers are preserved through API calls. I did not use them as Destination and Source Registers as Lifewire did.