Restart your computer using function pointers in C

I learned about function pointers in C when I came across a program that restarts the computer after execution.

void (*f) (void);
f=(void (*)(void) MK_FP(0xFFFF,0x0000);
f();

The (void (*) (void)) part was not contained in the source code, and I had to make this addition to get the code for compilation. How it works?

Many thanks.

0
source share
3 answers

For programs that manually construct function pointers from numeric literals and call them, the C standard only says that the behavior is undefined. This means that you cannot expect that the program will behave the same from computer to computer or even from launch to run on the same computer.

, :

IBM PC, MS-DOS, FFFF:0000 . ( F000:FFF0 - , , , , , , - , .) , , , .

, MK_FP , , IBM PC MS-DOS, FFFF:0000 .

( IBM PC) , . , MK_FP() 32- 64- , . , , , , , . , . DOS, , .

, - , , ! - ​​, (Unix-family: reboot(2); Windows: ExitWindowsEx), .

, FFFF:0000 - , Linux x86. , , . . http://lxr.free-electrons.com/source/arch/x86/kernel/reboot.c#L484 http://lxr.free-electrons.com/source/arch/x86/realmode/rm/reboot.S , FFFF:0000 "" (16- ).

+5

, x86 , , "Power On Reset Vector" (source).

+1

This is a system-specific (i.e., non-portable) approach to restarting the machine. What is the intended OS for this program? This is DOS (I guess). Try running it inside a virtual machine and find out.

If you want this to work on other platforms, you need to write some platform-specific things, for example:

#ifdef __linux__
  system("shutdown -P now");
#elif _WIN32
  #if (WINVER == NTDDI_WIN7) // Windows 7
    system("C:\\WINDOWS\\System32\\shutdown /s");
  #endif
  #if ((WINVER <= NTDDI_WINXPSP3) && (WINVER >= NTDDI_WINXP)) // Windows XP
    system("C:\\WINDOWS\\System32\\shutdown -s");
  #endif
#else
  #error System not recognized
#endif
+1
source

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


All Articles