-1

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.

Hugh McMaster
  • 319
  • 3
  • 10

1 Answers1

4

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Right, but not completely, in my opinion. You can have the size of a function with simple workaround, like: define dummies functions before and after the function you want to sizeof. – LPs Sep 24 '15 at 07:20
  • Ah, well I learn something new every day. Is what I want to do only at compiler level? – Hugh McMaster Sep 24 '15 at 07:20
  • 1
    @LPs Please point me at the text in the standard where it says that functions that are adjacent in the source are adjacent in memory after compilation. – unwind Sep 24 '15 at 07:21
  • AFAIK, at least, if you compile Position Independent Code functions will be adjacent. BTW there are a lot of ways to do that, such as using linker script to ensure that. – LPs Sep 24 '15 at 07:37
  • @LPs: that may still needs a lot of supporting code. I assume you can trivially dismiss "OP's function may be inlined", but what about a function that uses `printf`? I agree with unwind, C is not *supposed* to support this. You cannot write out any section of memory willy-nilly and expect it to be a valid program. – Jongware Sep 24 '15 at 07:48
  • @Jongware I agree. You must have total control of your code to do that. Embedded firmware use those technics, such as write flash memory while executing from flash in old style MCUs. – LPs Sep 24 '15 at 07:53