How to jump the program execution to a specific address in C?

前端 未结 8 711
感动是毒
感动是毒 2021-01-02 01:17

I want the program to jump to a specific address in memory and continue execution from that address. I thought about using goto but I don\'t have a label rather

相关标签:
8条回答
  • 2021-01-02 01:44

    Do you have control of the code at the address that you intend to jump to? Is this C or C++?

    I hesitantly suggest setjmp() / longjmp() if you're using C and can run setjmp() where you need to jump back to. That being said, you've got to be VERY careful with these.

    As for C++, see the following discussion about longjmp() shortcutting exception handling and destructors destructors. This would make me even more hesitant to suggest it's use in C++.

    C++: Safe to use longjmp and setjmp?

    0 讨论(0)
  • 2021-01-02 01:46

    Since the question has a C++ tag, here's an example of a C++ call to a function with a signature like main()--int main(int argc, char* argv[]):

    int main(int argc, char* argv[])
    {
        auto funcAddr = 0x12345678; //or use &main...
        auto result = reinterpret_cast<int (*)(int, char**)>(funcAddr)(argc, argv);
    }
    
    0 讨论(0)
  • 2021-01-02 01:48

    It should look something like this:

    unsigned long address=0x80; 
    
    void (*func_ptr)(void) = (void (*)(void))address;
    func_ptr();
    

    However, it is not a very safe operation, jumping to some unknown address will probably result in a crash!

    0 讨论(0)
  • 2021-01-02 01:52

    I Propos this code:

    asm(
    "LDR R0,=0x0a0000\n\t" /* Or 0x0a0000 for the base Addr. */
    "LDR R0, [R0, #4]\n\t" /* Vector+4 for PC */
    "BX R0"
    );
    
    0 讨论(0)
  • 2021-01-02 01:56
    #include <stdio.h>
    #include <stdlib.h>
    
    void go(unsigned int addr) {
      (&addr)[-1] = addr;
    }
    
    int sub() {
      static int i;
      if(i++ < 10) printf("Hello %d\n", i);
      else exit(0);
      go((unsigned int)sub);
    }
    
    int main() {
      sub();
    }
    

    Of course, this invokes undefined behavior, is platform-dependent, assumes that code addresses are the same size as int, etc, etc.

    0 讨论(0)
  • 2021-01-02 02:00

    gcc has an extension that allows jumping to an arbitrary address:

    void *ptr = (void *)0x1234567;  // a random memory address
    goto *ptr;                      // jump there -- probably crash
    

    This is pretty much the same as using a function pointer that you set to a fixed value, but it will actually use a jump instruction rather than a call instruction (so the stack won't be modified)

    0 讨论(0)
提交回复
热议问题