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
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?
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);
}
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!
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"
);
#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.
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)