This is my first time around, and I really hope you guys can help me, as I have ran out of ideas by now.
I have searched for an answer for a couple of hours now, and cou
You don't need the extra padding when you're injecting the code, so it's fine to discard them. It should also be fine to copy them over, it will just result in a few extra bytes of copying. Chances are the memory you're injecting to will by a page-aligned block anyway, so you're not really gaining anything by stripping it out.
But if you really want to strip it out, a simple solution to your problem would be to just iterate backwards from the last byte before the next function, until there are no more 0xcc bytes.
i.e.:
__declspec(naked) void Foo()
{
__asm
{
_emit 0x4A
_emit 0x4B
}
}
__declspec(naked) void FooEnd() {}
int main(int argc, char** argv)
{
//start at the last byte of the memory-aligned code instead of the first byte of FooEnd
unsigned char* fooLast = (unsigned char*)FooEnd-1;
//keep going backwards until we don't have a 0xcc
while(*fooLast == 0xCC)
fooLast--;
//fooLast will now point at the last byte of your function, so you need to add 1
int length = ((int)fooLast - (int)Foo) + 1;
//should output 2 for the length of Foo
std::cout << length;
}