How to dereference a function pointer and read as data in MSVC ++?

The following is my attempt to read the machine code pointed to by the function pointer and print it. Currently the printed data does not match the code that was generated ... I checked the values ​​of the pointers created in the produced executable file and listed by the disassembler (there is a difference between the code / debugger), but don I don’t see anything too disturbing or understand how I I can fix this problem.

void dummy(); int _tmain(int argc, _TCHAR* argv[]) { int i; printf("\nReading dummy...\n"); for(i = 0; i < 25; i++) printf("%.2X ", ((char *)((void *)dummy))[i]); puts(""); dummy(); getchar(); return 0; } void __declspec(naked) dummy() { __asm { nop; nop; nop; nop; ret; } } 
+4
source share
4 answers

Two common mistakes you can make here. First of all, select unsigned char* instead of char *. Then, and important, Project + Properties, Linker, General and turn off incremental binding.

When incremental binding is enabled, the address of the function actually points to a small stub that does not contain anything other than JMP for the real function. This allows the linker to replace the old code with new code without having to rearrange the entire executable image. Your code reads this stub instead of the real function when incremental binding is enabled. The correct conclusion:

 Reading dummy... 90 90 90 90 C3 //... rest is random 
+12
source

Let me guess it printed this:

  FFFFFF90 FFFFFF90 FFFFFF90 FFFFFF90 FFFFFFC3

Try using the hh length modifier with printf:

 printf("%02hhX ", ((char *)((void *)dummy))[i]); 

Output:

  90 90 90 90 C3

The X specifier itself prints the value as an unsigned int , but you pass a char pushed to signed int . The hh modifier changes it to an unsigned char instead of an unsigned int .

+2
source

Change the line

 printf("%.2X ", ((char *)((void *)dummy))[i]); 

to

 printf("%.2X ", ((unsigned char *)dummy)[i]); 
0
source

Here you go:

 #include <stdio.h> void PrintHex(const char* input, const int len) { char * tmp=new char[len*3+1]; for(int i=0;i<len;++i) sprintf(tmp+i*3,"%02x ",*(input+i)&0xFF); printf("%s\n",tmp); }; 
-2
source

Source: https://habr.com/ru/post/1384556/


All Articles