2008-03-25

Emulating exit(3) and moving stack on the fly.

Recently, during coding embedded stuff for industrial robots I had very interesting problem.

I needed to implement exit(3) function. But the system on the robot is very simple. There aren't any kinds of syscalls.

So, the functions exit(3) must emulate the only proper way of exiting the program. It should emulate returning/exiting from main() function.

My friend, Michal Luczaj, found clever way of doing this. The basic idea is to do:

void (*exit)();

void user_main(){
int whatever;
/* bla, bla , bla */
exit();
}

int main(){
exit = &&final_quit;

/* execute the application */
user_main();

final_quit:
return(0);
}

Well, this won't work, because the stack after calling exit() in user_main() is not the stack that should be in main().

That's also my other problem. My robots have very limited stack, so I want to move the stack to other memory area.

The final code emulates exit() and moves the stack. It works like this:
int main(){
start();
}

int start()
{
SAVE_STACK_POINTER();
myexit = &&final_quit;

new_sp = malloc(128*1024);
SET_STACK_POINTER(new_sp);

user_main();
/* stack broken here - don't do anything please */
final_quit:
RESTORE_STACK_POINTER();
return(0);
}

void user_main(){
myexit();
}


No comments: