Homework 1 Solutions

22C:116, Spring 1999

Douglas W. Jones
  1. The answer depends on who you are.

  2. Here is C code to demonstrate nonlocal gotos from within a function using longjmp():
    jmp_buf goto_label; /* declared globally */
    
    void might_do_nonlocal_goto()
    {
        ...
        if (trouble) longjmp( goto_label, 1 );
        ...
    }
    
    void handles_exception()
    {
        if (setjmp( goto_label ) == 0) {
    	/* normal code for the program */
            ...
            might_do_nonlocal_goto();
            ...
        } else {
    	/* target of nonlocal goto */
            ...
        }
    }
    

  3. The implementation of setjmp() and longjmp() depends on the contents of the jump buffer. This must contain, at minium, the following: First, the program counter value to be used by the long jump. Without this, the required control transfer would be impossible. Second, the stack pointer at the time of the call to set jump. This is needed so that the stack context can be restored by long jump. In a pure stack machine, nothing else would be needed, but in a machine with multiple registers, some part of the computation state at the time of the call to setjmp may be stored in registers and not on the stack. In this case, these regsters must also be saved in the jump buffer.

    Given this, setjmp() must save the return address and stack pointer, plus any other saved regster values that are needed, into the jump buffer. The setjmp function would return zero in an entirely normal way. The longjmp() function would operate by first setting the stack pointer to the value saved in the jump buffer and then loading the return address from the jump buffer into the return address location on the stack. If other values are stored in the jump buffer, they would be loaded into registers or into register save areas on the stack. Finally, the longjmp() function would execute a normal function return.

  4. A processor is a physical system component, made of hardware, containing registers, an arithmetic unit, and a control unit of some kind. Processors execute programs. A process is a logical part of a program. The logical state of a process corresponds to the physical state of a processor, and the process requires the use of a processor to advance its logical state. A system may have many more processes than processors, and whenever the processor executed instructions, it does so on behalf of some process.

  5. Interrupts and traps are similar transfers of control from a running program to a service routine. They differ in the way they are initiated. Interrupts are initiated asynchronously in response to events in the outside world, while traps occur as side-effects of the execution of instructions by the program itself.