• C

Switching Stacks

Inside a Interrupt Service Routine, I need to change the presently running program's Stack to the ISR's Stack. I have two questions.

1. What is the Code for this in Microsoft C? or can I use     inline assembly?
2. How do I determine where to put the Stack Pointer? i.e     how do I determine the amount of stack used?
Who is Participating?
bculverConnect With a Mentor Commented:
The following code should get you going. Upon entry of the interrupt handler the __interrupt command forces the handler to reload the data segment, thus you have access to you global variables and a place to save the current stack registers. Also remember that if you use an alternate stack, local variables in the interrupt handler are going to be inaccessable because there referenced to the original stack not your new one (there are ways around this but it can get real messy, just use a bit of gloabal space for any needed locals. Any functions called by the interrupt handler are ok to have local variables). As far as the stack size, it depends on what you handler does. Function calls parameters and local variables are all allocated to the stack so count em up if you need and add a few extra (double it) for good luck. If you enable IRQ's in the middle you your handler, you'll also have to account for OS or other interrupt needs also, (maybe a couple of hundred bytes or so.)

// Global
char stack[1024];  
int  ssreg,spreg;

void __interrupt __far IntHandler()
_asm mov      ssreg, ss                  // save current ss
_asm mov      spreg, sp                  // save current sp
_asm mov      ax, offset stack[1024-2]      // get ptr to top of stack
_asm mov      sp, ax                        // stack address to sp
_asm mov      ax, ds                        // stack segment to ax
_asm mov      ss, ax                        // stack seg to ss


_asm mov      ss, ssreg                  // restore ss
_asm mov      sp, spreg                  // restore sp

to do this you need to use assembler....

for C/C++ the inline asm is like this..

  asm {
  //asm code goes here,,

SP(Stack Pointer) is the assembler register....
ravipalAuthor Commented:
Thanks bculver, I need few clarifications on your code.

The 1024 you put in the char stack array, Is is a assumed figure ? or is that a fixed figure??

Why do you put 1024-2 to get ptr to the top of the stack?, is it not 1024-1?

What is the reason behind moving values to AX before moving them to SP and SS respectively?

Would appreciate your clarifications very much.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.