【发布时间】:2015-09-22 07:51:01
【问题描述】:
我一直在为程序使用以下代码来打开自身的文件句柄并读取其内容,但我遇到了问题...这是代码...
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
样本输出...
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>
我在使用 OpenFile 时做错了什么?
【问题讨论】:
-
使用 OpenFile 将是您做错的一件事。用于打开文件的 Win32 API 是 CreateFile。
-
您还缺少读取文件内容的代码。
-
您阅读文档了吗?它的开头是这样的: 此功能功能有限,不推荐使用。对于新的应用程序开发,请使用 CreateFile 函数。
-
正如 Ross Ridge 所指出的,您正在打开文件,但从未阅读过它。您应该将文件的(部分)内容读入缓冲区,然后在调用
WriteFile时将指向该缓冲区的指针作为第二个参数传递。相反,您传递的是指向文件句柄的指针:push dword hSelfFile -
明白。我这样做的唯一原因是因为在我玩这段代码的时候,我确实在我的输出顶部看到了难以捉摸的 MZ,尽管我将使用 ReadFile 代替。谢谢!你们中的一个人应该提出答案。