I made this Win32 program that makes a dump of itself and saves that to 'dump.txt' . Though dump.txt doesn't run, probably because of the EXE headers. The program is in assembly, but it's easy assembly and uses only the basic instructions, so it should be pretty understandable.
.386
.model flat, stdcall
option casemap:none
include \RS\include\ifiles.inc
.data
output_filename db "dump.txt", 0
.data?
hInstance DWORD ?
CommandLine DWORD ?
hFile DWORD ?
sFile DWORD ?
.code
start:
push dword ptr 0
call GetModuleHandle
mov dword ptr [hInstance], eax
call GetCommandLine
mov dword ptr [CommandLine], eax
push dword ptr 0
push dword ptr space(SIZEOF OFSTRUCT)
push dword ptr [CommandLine]
call OpenFile
cmp eax, -1
jz err
mov dword ptr [hFile], eax
push dword ptr 0
push dword ptr [hFile]
call GetFileSize
mov dword ptr [sFile], eax
push dword ptr [hFile]
call CloseHandle
push dword ptr 1 or 1000h
push dword ptr space(SIZEOF OFSTRUCT)
push dword ptr offset output_filename
call OpenFile
mov dword ptr [hFile], eax
push dword ptr 0
push dword ptr integer()
push dword ptr [sFile]
push dword ptr [hInstance]
push dword ptr [hFile]
call WriteFile
push dword ptr [hFile]
call CloseHandle
push dword ptr string("Success!")
call StdOut
push dword ptr 0
call ExitProcess
err:
push dword ptr string("Error opening executable file ")
call StdOut
push dword ptr [CommandLine]
call StdOut
push dword ptr 0
call ExitProcess
end start
Is it possible to do the above in a higher-level language?
But it's a weird thing, I was using the command line for this stuff and when I typed "dump.txt" it actually ran the EXE rather than opening it with notepad, but the EXE failed. I tried making a new text file and putting "MZ" for the first two bytes of it, then I typed the filename of that text file in the command line and a message box appeared that said "Unsupported 16-Bit Application" ; so the command interpreter checks the file contents first, before checking the extension?
EDIT: I think I could probably try to fix the no run problem by copying the first (start - [hInstance]) bytes from the executable to the start of the dump file, after dumping itself.
But is there a more cross-platform way to do what that Win32 program did? Like getting the memory address of where the program was loaded?