As a learning exercise, I'm writing a program that outputs a DLL at run-time.
I've written the PE header and have successfully written the DOS header, NT header, optional section header and the .text
section header to a file using WriteFile
, e.g.:
WriteFile(hFile, &nt_header, sizeof(nt_header), &written, NULL);
I'm now like to add some code to the .text
section, but I don't know how to pass a function and its size to WriteFile
, e.g.:
static int test(void)
{
return 10;
}
WriteFile
's second parameter has type LPCVOID
. I tried passing in test
, but that only wrote 1 byte. Passing a pointer to test
wrote 4 bytes, as expected.
This is probably obvious, but I'm not understanding where I'm going wrong.
It's obvious, but the answer isn't what you want, probably. It can't be done, at least not portably.
Functions in C don't have sizes. You also can't assume that the concept "address of a function" means "address of the first machine instruction in the compiled code for a function".
In short, what you're doing isn't possible at that level in C, you can't do I/O on functions directly.