【问题标题】:How do I find a file inside the current directory in x86 Windows Assembly如何在 x86 Windows 程序集的当前目录中找到文件
【发布时间】:2014-08-05 05:44:57
【问题描述】:

我的代码有一些问题。我正在尝试读取可执行文件中的两个 PE 标头。但是,当我调用 ReadFile 时,它​​会将 [hFile] 设置为 5A,这不是我从 CreateFile 放入的句柄。据我了解,ReadFile 不应以任何方式改变这一点。但是,当我将句柄存储在另一个变量中并使用它来设置文件指针时,下一条ReadFile 指令仍然给我MZ 标头而不是PE 标头,它位于距@ 偏移3C 处987654327@标头。

总结:ReadFile 更改了我的句柄,SetFilePointer 将更改视为无效句柄,SetFilePointer 在给定有效句柄时不会更改下一次读取的指针。

format PE console 4.0
entry start

include 'win32ax.inc'

section '.data' data readable writeable

thisFile db "thisfile.exe",0
read db ?
hFile dd ?

section '.text' data readable executable

start:
;========Open File================
invoke CreateFile,thisFile,GENERIC_READ,FILE_SHARE_READ,0,\
                  OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0
mov [hFile],eax

;========MZ HEADER================
invoke ReadFile,[hFile],read,2,NULL,0 ; = MZ, , however, changes [hFile]
                                      ;to 5A? Why does it change it?
invoke printf,read

;========PE HEADER================
invoke SetFilePointer,[hFile],03Ch,0,FILE_CURRENT ; = 0, beginning of file ATM
                                                  ;Should make next read = PE
invoke ReadFile,[hFile],read,3,NULL,0 ; = PE

invoke printf,read

invoke getchar
invoke ExitProcess,0 

【问题讨论】:

    标签: windows file assembly x86 fasm


    【解决方案1】:

    在这里,您将 2 个字节读入 read

    invoke ReadFile,[hFile],read,2,NULL,0
    

    但是看看你是如何声明read的:

    read db ?
    

    这是一个字节。因此,您使用ReadFile 读取的第二个字节将被写入内存中read 之后的任何内容,恰好是hFile。因此,您将覆盖hFile 的最低有效字节。

    您的代码中还有一个地方是您尝试将 3 个字节读入 read,但我想这会失败,因为届时您的 hFile 将无效。

    您需要做的是为read 保留更多空间,就像您计划在其中存储的一样多。假设您想要 4 个字节,您可以通过以下方式获得:

    read db 4 dup(0)
    

    read: times 4 db 0
    

    read rb 4
    

    read dd ?
    

    由于您将 read 作为字符串传递给 printf,因此请记住,字符串应以 NUL 结尾。

    【讨论】:

    • 所以在过去的几周里,我很幸运,因为我的数据没有被覆盖。感谢您澄清我的一个误解。我一直认为abc DB ? 意味着它将为我放入的内容腾出空间。
    • 一个较小的子问题,但是。在汇编中,我将如何处理我不知道它有多大的数据。就像一个文件名。因为如果我对每个未知长度的变量都执行filename DB 256 dup (0),它会导致我的程序膨胀。 GlobalAlloc 是我的答案吗?
    • 是的,在某些时候您可能需要某种堆分配例程。在 Windows 中有几个(LocalAllocGlobalAllocHeapAlloc,...)。您可能可以在 MSDN 上找到最适合您的用途。
    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多