Operating Systems 2019F Lecture 9

From Soma-notes
Jump to navigation Jump to search

Video

Video from the lecture given on October 2, 2019 is now available.

Notes

Lecture 9
---------

Trying to explain assembly code!

Key concepts
* saving and loading of registers from stack
* call/ret
* passing arguments
* using base pointer register for local variables


When you enter a function, you save any registers that you will clobber
 - they are saved by pushing them on the stack
 - they must be popped when the function exits
 - register save/restore (like any instruction) can be optimized away

Registers are marked by a %
Constant values are marked by a $

The stack pointer contains the current "top" of the stack (note that the stack grows down in memory).

The base pointer contains the value of the stack pointer as it was
at the start of the function.

We use the base pointer to access parameters that are passed to a function and to access local variables.

To allocate local variables, we just decrement the stack pointer (to make space).  We can get rid of them by restoring the stack pointer from the base pointer (on function exit).


Key steps to make a function call
* push arguments onto stack or store in registers
* call function (save current instruction on stack, jump to function)

Key steps on entry to a function
* save base pointer
* copy stack pointer to base pointer register
* decrement stack pointer to make room for local variables

Key steps on exiting a function
* copy base pointer register to stack pointer register
* do ret (pop instruction pointer from stack, jump to it)

After function call finishes
* take arguments off stack, get return value

What happens when a signal is delivered to a process?
* the currently running instruction is saved to the stack
* kernel replaces instruction pointer value with signal handler location
  (after putting proper arguments on stack)

Code

#include <stdio.h>

int something(char *s)
{
        printf("You said: %s\n", s);

        return 0;
}


int main(int argc, char *argv[], char *envp[])
{
        printf("Entering main.\n");
        if (argc > 1) {
                something(argv[1]);
        } else {
                printf("No argument given.\n");
        }      
        printf("Exiting main.\n");

        return 0;
}