简体   繁体   中英

OpenFile not working in x86 NASM assembly

I have been using the following code for a program to open a file handle to itself and to read its contents, but I've run into a problem... Here's the code...

extern GetStdHandle
extern GetModuleFileNameA
extern OpenFile
extern WriteFile
extern ExitProcess

import GetStdHandle kernel32.dll
import GetModuleFileNameA kernel32.dll
import OpenFile kernel32.dll
import WriteFile kernel32.dll
import ExitProcess kernel32.dll

global ..start

segment .code USE32

;Get standard output handle for writing to the console
push dword -11
call [GetStdHandle]
mov dword [hStdOut], eax

push dword filepath ;Buffer to store filepath
push dword 0 ;Setting this to NULL retrieves file name of 
             ;the program's exe on disk
call [GetModuleFileNameA] ;ANSI format of return string (the way that
                          ;OpenFile likes it)

;Here we are checking to see if the filename was returned
;On the console it looks blank but if you dump the output of the
;program to a file using the command program.exe > program.dump the
;path shows up in a hex editor. So the path is fine...
push dword 0
push dword bytesRead
push dword 128 ;Maximum path size for OpenFile
push dword filepath
push dword [hStdOut]
call [WriteFile]

push dword 0
push dword ofstruct
push dword filepath
call [OpenFile]
mov dword [hSelfFile], eax

push dword 0
push dword bytesRead
push dword 32 ;Arbitrary number to show the beginning of
              ;hSelfFile to see if the handle is pointing to
              ;the file. It should show the magic number MZ
              ;at the beginning if we're doing this right
push dword hSelfFile
push dword [hStdOut]
call [WriteFile] 

;Here is where we should see the elusive MZ magic number in the
;output

;Yes I will use CloseHandle (even though the program automatically
;closes all open handles before exiting), but for now I need to see
;if the OpenFile actually works or not before I do such things

push 0
call [ExitProcess]

segment .data

segment .bss
hStdOut resd 1
hSelfFile resd 1
bytesRead resd 1
ofstruct resb 136
filepath resb 128

Sample output...


C:\DOCUME~1\Admin\Desktop\asm>test0.exe
C:\DOCUME~1\Admin\Desktop\asm\test0.exe
                                            Φ      ê☺  σF±ÿC:\DOCUME~1\Admi
C:\DOCUME~1\Admin\Desktop\asm>

What am I doing wrong with OpenFile?

The file needs to be read into a buffer with ReadFile before WriteFile can output the contents of the file, it cannot be read just by passing a file handle from OpenFile to WriteFile.

Documentation...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM