13. Exceptions, Traps and Interrupts

Part of 22C:60, Computer Organization Notes
by Douglas W. Jones
THE UNIVERSITY OF IOWA Department of Computer Science

Background

Up to this point, we have focused on purely sequential control transfers, with no provision for exceptional conditions. In fact, programmers never need to go beyond these simple models, but by adding exceptions to our programming languages and interrupt mechanisms to our computer hardware, we can write programs far more compactly than we could if we were forced to handle exceptions with explicit error returns. To illustrate this, consider the following simple program:

A simple program with no exception handling
int distance( int x1, int y1, int x2, int y2 )
/* return the cartesian distance between <x1, y1> and <x2, y2> */
{
        return squareroot( square( x1 - x2 ) + square( y1 - y2 ) );
}

Here, we assume that square() and squareroot() are subroutines that compute the appropriate functions of their arguments. This code looks straightforward, until you consider the possibility that squaring a number, or addition, or subtraction would produce an overflow.

A classic way to deal with errors within functions is to define some return value as an error flag. For example, since neither the distance between two points nor the square of a number can be negative, we might be tempted to use negative values as error indicators. One of the reasons that the IEEE standard floating point representation includes NaNs (not a number values) is specifically to facilitate this. Confining ourselves to the purely sequential subset of C and C++ and ignoring overflows resulting from adding or subtracting, this leads us to the following hard-to-read code:

A simple program made unreadable by clumsy exception handling
int distance( int x1, int y1, int x2, int y2 )
/* return the cartesian distance between <x1, y1> and <x2, y2>
   returns a negative value if there is an overflow */
{
        int squarex = square( x1 - x2 );
        int squarey = square( y1 - y2 );
        if ((squarex < 0) || (squarey < 0)) {
                /* taking the square produced an overflow */
                return -1;
        } else {
                return squareroot( squarex + squarey );
        }
}

The above code becomes even worse if we attempt to detect overflow in the addition or subtraction operators. This is why, in the late 1960s programming language designers began to explore what we now call exception handling mechanisms. Although the language PL/I developed by IBM in the mid 1960s had a crude exception handling mechanism, and although Pascal and C, both developed around 1970, had primitives from which exception handling mechanisms could be developed, the modern model of exception handling did not reach maturity until the development of the Ada language in the late 1970s. Variants of the Ada exception model, were incorporated into C++, Java and several other more recent languages.

In this model, exceptions are global objects, so an exception may be raised anywhere in the code. Wherever the exception is raised, the result is a transfer of control to the current handler for that exception. At any instant, each exception defined in the program must have exactly one handler. Raising or throwing an exception (the terminology varies between languages) causes a transfer of control to that exception's current handler. Consider the following example, using Ada syntax:

An exception handler in Ada
procedure X is
    K: BOOLEAN; -- a local variable
begin
    ... the body of X, code here might raise CONSTRAINT_ERROR ...
exception
    when CONSTRAINT_ERROR =>
        ... the handler for constraint errors ...
end X;

In this example, the subroutine named X installs a handler for the CONSTRAINT_ERROR exception. The identity of any previously installed handler for this exception is saved, and on exit from X, the previous handler will be re-installed. Within the body of X as well as within the body of any subroutines called from X, raising the CONSTRAINT_ERROR exception will cause an immediate transfer of control to the handler, unless a new handler is installed.

The CONSTRAINT_ERROR exception is one of Ada's predefined exceptions. It is used when a program tries to use a value that is outside the range of legal values for some operation. For example, it is raised when an array index is out of bounds.

It is important to note that raising an exception does more than just transfer control to the handler for that exception. It also restores the context of that handler. In the above Ada code, because the CONSTRAINT_ERROR handler is part of the subroutine X, it has access to any and all local variables of X; in this case, the Boolean variable K. From this, we conclude that if local variables are stored in activation records that are pushed onto a stack, raising an exception must restore the stack pointer to its value at the time the handler was installed.

Exceptions in C++ and Java are considerably, and perhaps unnecessarily more complex. In these languages, handlers may be parameterized, and programs distinguish between different handlers by testing the values of the parameters. Furthermore, the usual explanation of exception handling in these languages is given in terms of a complex computation instead of a quick jump to the appropriate handler. The core mechanism discussed here underlies the typical implementation of C++ exceptions and could be used in compiled versions of Java.

Exercises

a) Modify the distance() routine given above so that it not only returns a negative value if the calles to square() or squareroot() involve overflows, but also if any of the sums or differences produce an overflow. Since C and C++ do integer arithmetic without reporting any exceptions, you will have to use explicit if statements to do this! Consider the sum a+b where both variables are positive. This will produce an overflow if a+b>max, but this boolean expression cannot be evaluated on a machine where max is the largest integer that can be represented. Therefore, we must do a bit of algebra and note that a+b>max implies a>max-b; we can evaluate this expression!

b) What happens to the variables of a program when an exception is raised and handled? Which variables can be trusted to have well determined values, and of these, which will have their values unchanged from the time the handler was installed? Which variables have undetermined or ill defined values as a result of the exception being raised?
 

Exceptions at the Machine Level

The attributes we have enumerated for exceptions above lead, in a fairly direct way, to an assembly language implementation. First, we noted that exceptions are global. This leads us, immediately, to the conclusion that, in the Hawk assembly language, each exception must be a COMMON block, since that is our assembler's mechanism for global storage allocation.

In the previous section, we mentioned two components of an exception. First, each exception must identify its current handler. Since the handler is a piece of code, the identity of that handler is just the address of the entry point of that code. Second, on entry to the handler, we noted that the activation record of the subroutine containing that handler must be restored. Therefore, the exception must identify the activation record of the handler. Because exceptions may be raised anywhere, we should put the generic declarations applicable to all exceptions in a header file that can be included by any routine that wants to declare an exception, install a handler or raise an exception.

The header file for Hawk exception handling
; exceptions.h -- declarations applying to exceptions

; an exception is a record structure with the following fields
EXHAND  =       0       ; one word, the address of the handler
EXAR    =       4       ; one word, the handler's activation record
EXSIZE  =       8       ; the total size of the exception record

In Ada, there are a number of predefined exceptions, CONSTRAINT_ERROR for example, which is raised by an attempt to use an array index outside the legal range, by an attempt to follow a null pointer or by an attempt to assign a value to a variable that is outside the legal range of values for that variable. The following code shows the code needed to create a CONSTRAINT_ERROR exception in assembly language. We would duplicate this code in each source file where this exception is raised or handled.

Declaring an exception in a Hawk program
        USE     "exceptions.h"

        COMMON  CONSTRAINT_ERROR, EXSIZE

This code is no different from the declaration of any other global variable on the Hawk. The block of EXSIZE bytes named CONSTRAINT_ERROR is uninitialized, and each file that repeats this code will be able to load the external address CONSTRAINT_ERROR into a register to point to this global variable. Recall that repeating a common declaration in different separately assembled files of a program creates only one copy of that common block shared by all of them. All such common blocks should, of course, be declared to have the same size.

Suppose a routine within the program wants to install a handler for constraint errors. The routine must include, in its activation record, space to save the previous handler for the exception. This can be declared as follows, using the style of activation record construction discussed at the end of Chapter 11:
 

Activaton record structure for a routine that installs an exception handler
        ...  definitions of other local variables
ARSIZE  =       ...

OLDCON  =       ARSIZE          ; save area for previous handler
ARSIZE  =       ARSIZE + EXSIZE

These are entirely unremarkable declarations for a local variable that is part of the activation record. The overall control structure of a C++ or Java try-catch block, or the overall structure of an Ada block that ends with an exception handler would be as follows in machine language:

Overall structure of a block that handles exceptions
        ; save old CONSTRAINT_ERROR exception in OLDCON in my AR
        ; install MYHAND as new CONSTRAINT_ERROR handler

        ... body of try clause

        ; restore old CONSTRAINT_ERROR exception from OLDCON in my AR

        BR      MYHANDEND
MYHAND:

        ; restore old CONSTRAINT_ERROR exception from OLDCON in my AR

        ... body of handler

MYHANDEND:

The above control structure is similar to the structure of an if-then-else block. The try clause resembles a then clause, ending with a branch to the end of the structure. Similarly, the handler resembles an else clause, beginning with a label. The big difference is that this structure transfers control to the handler from anywhere inside the try block or any routine it calls. In contrast, the control transfer to an else clause comes from only one place!

The code to save the state of a global variable in a local variable is no different for exceptions than it would be for any other variable. Installing a handler is fairly simple too:

Code to save the old handler and install a new handler
        ; save old CONSTRAINT_ERROR exception in OLDCON in my AR
        LIL     R3,CONSTRAINT_ERROR
        LOAD    R4,R3,EXHAND    ; oldcon.exhand = constraint_error.exhand
        STORE   R4,R2,OLDCON+EXHAND
        LOAD    R4,R3,EXAR      ; oldcon.exar = constraint_error.exar
        STORE   R4,R2,OLDCON+EXAR

        ; install MYHAND as new CONSTRAINT_ERROR handler
        LEA     R4,MYHAND
        STORE   R4,R3,EXHAND    ; constraint_error.exhand = myhand
        STORE   R2,R3,EXAR      ; constraint_error.exar   = AR

Note in the above code that indexed addressing using R2 and the displacement OLDCON addresses the first word of the OLDCON field in the activation record. Since this field is a multiword object, we can use OLDCON+EXHAND to reference one word of this object and OLDCON+EXAR to reference the other word of the object. Restoring the old handler reverses the logic of the save code above:

Code to restore the old handler
        ; restore old CONSTRAINT_ERROR exception from OLDCON in my AR
        LIL     R3,CONSTRAINT_ERROR
        LOAD    R4,R2,OLDCON+EXHAND
        STORE   R4,R3,EXHAND    ; constraint_error.exhand = oldcon.exhand
        LOAD    R4,R2,OLDCON+EXAR
        STORE   R4,R3,EXAR      ; constraint_error.exar = oldcon.exar

Typically, the old handler would be restored immediately prior to a jump to the end of the exception handler, or alternatively, immediately prior to a return from the function. In any case, the initial code of the handler itself must also restore the previous handler. Now, we have the complete mechanism in place, allowing the following code to be used to transfer control to the exception handler:

Raising an exception, the general case
        LIL     R1,CONSTRAINT_ERROR
        LOAD    R2,R1,EXAR      ; AR = constraint_error.exar
        LOAD    R1,R1,EXHAND
        JUMPS   R1              ; PC = constraint_error.exhand

A far more compact transfer of control to the exception handler is possible if we know that the handler is local. The above verson must be used when the handler is not local, for example, when the exception is being raised in a library routine and it must be handled by some user routine. If the exception is being raised locally, within the body of the try clause, we can use a far simpler formulation because register 2 does not need to change. In that case, we raise the exception with a simple branch instruction:

Raising a local exception
        BR      MYHAND          ; raise constraint_error locally

Things are further simplified in the main program, since there is no previous handler for any exceptions declared there, there is no need to save the prevous handler on entry to the main program, nor is there any need to restore the previous handler at the end.

We must ask, for any exception mechanism, exactly what is restored by the transfer of control to the exception handler, and what is lost as the exception is raised. For the machine code outlined above, the author of the exception handler can usually rely on things stored in its activation record, but there is no eacy way for it to account for what is or is not in the registers at the time the exception is raised. Therefore, any routine that installs an exception handler must save in its activation record its return address and anything else on which the exception handler relies.

Exercises

c) Write a Hawk main program that simply initializes the display, installs a default handler for CONSTRAINT_ERROR and then calls the external subroutine APPLICATION. Your handler should just print out the message constraint error in the upper left corner of the display and then exit.

d) The code given here to save the old handler and install its replacement and the code given here to restore the old handler violates the data abstraction of the exception mechanism by exposing, to the programmer, the internal structure of the exception variable. Write a pair of subroutines to hide this information. The interface to these belongs in the file exception.h and the subroutines would go in a new file, exception.a.

e) The code given here to save the old handler and install its replacement and the code given here to restore the old handler violates the data abstraction of the exception mechanism by exposing, to the programmer, the internal structure of the exception variable. Write a pair of macros that can be included in the file exception.h that hide this information.

An Example

To illustrate this set of exception handling tools, consider the problem of adding support for exceptions to one of the unsigned multiply routines given in Chapter 9. Multiplication can produce values too large to store in one word, so it is appropriate to raise a constraint error when this occurs.

Unsigned multiplication with overflow detection
MULTIPLY:       ; link through R1
                ; R3 = multiplier on entry, product on return
                ; R4 = multiplicand on entry, destroyed
                ; R5 = temporary copy of multiplier, destroyed
        MOVE    R5,R3           ; move the multiplier
        CLR     R3              ; product = 0;
        TESTR   R5
        BZS     MULTLX          ; if (multiplier != 0) {
MULTLP:                         ;   do {
        SRU     R5,1            ;     multiplier = multiplier >> 1;
        BCR     MULTEI          ;     if (multiplier was odd) {
        ADD     R3,R3,R4        ;       product = product + multiplicand;
        BCS     RCONERR         ;       if carry set, raise constraint error
MULTEI:                         ;     }
        SL      R4,1            ;     multiplicand = multiplicand << 1;
        BCS     RCONERR         ;     if carry set, raise constraint error
        TESTR   R5
        BZR     MULTLP          ;   } while (multiplier != 0);
MULTLX:                         ; }
        JUMPS   R1              ; return product;

RCONERR:                        ; common code for raising constraint error
        LIL     R1,CONSTRAINT_ERROR
        LOAD    R2,R1,EXAR      ; AR = constraint_error.exar
        LOAD    R1,R1,EXHAND
        JUMPS   R4              ; PC = constraint_error.exhand

In the above code, it was easy to detect the need to raise an exception; testing the carry bit was enough. Once this condition is detected, a sequence of 4 instructions is used to raise the exception. This sequence is identical in every context where the exception might be raised, so it is reasonable to write it once block and let all the different checks for the exception jump to this little block of code.

Suppose we have an assembly language version of the code for distance() from the start of this chapter that uses use the above multiply routine to compute the required squares. The following code calls this and outputs the distance in decimal, for example, saying "the distance is 39 microns", but if there is an range-constraint exception, it outputs "the distance is too big". To do this, it installs a handler.

Code that installs a handler, part 1
; activation record format for the Show Distance routine
RETAD   =       0
X1      =       4               ; saved parameters
Y1      =       8
X2      =       12
Y2      =       16
ARSIZE  =       20

OLDCON  =       ARSIZE          ; save old constraint error handler
ARSIZE  =       ARSIZE + EXSIZE

SHOWDIST:       ; on entry, R3 = x1, coordinates of two points
                ;           R4 = y1
                ;           R5 = x2
                ;           R6 = y2
        STORES  R1,R2           ; save return address
        STORE   R3,R2,X1
        STORE   R4,R2,Y1
        STORE   R5,R2,X2
        STORE   R6,R2,Y2        ; save parameters

        LEA     R3,SDMSG
        ADDI    R2,ARSIZE
        LIL     R1,DSPST
        JSRS    R1,R1           ; dspst( "the distance is " );
        ADDI    R2,-ARSIZE
        
        ; save old CONSTRAINT_ERROR exception in OLDCON in my AR
        LIL     R3,CONSTRAINT_ERROR
        LOAD    R4,R3,EXHAND    ; oldcon.exhand = constraint_error.exhand
        STORE   R4,R2,OLDCON+EXHAND
        LOAD    R4,R3,EXAR      ; oldcon.exar = constraint_error.exar
        STORE   R4,R2,OLDCON+EXAR

        ; install MYHAND as new CONSTRAINT_ERROR handler
        LEA     R4,SDHAND
        STORE   R4,R3,EXHAND    ; constraint_error.exhand = sdhand
        STORE   R2,R3,EXAR      ; constraint_error.exar   = AR

        ; body of code to which new handler applies
        LOAD    R3,R2,X1
        LOAD    R4,R2,Y1
        LOAD    R5,R2,X2
        LOAD    R6,R2,Y2
        ADDI    R2,ARSIZE
        JSR     R1,DISTANCE     ; R3 = distance( x1, y1, x2, y2 );

        LIL     R1,DSPDEC
        JSRS    R1,R1           ; dspdec( R3 );

        LEA     R3,SDUNIT
        LIL     R1,DSPST
        JSRS    R1,R1           ; dspst( " microns" );
        ADDI    R2,-ARSIZE

Code that installs a handler, part 2
        ; restore old CONSTRAINT_ERROR exception from OLDCON in my AR
        LIL     R3,CONSTRAINT_ERROR
        LOAD    R4,R2,OLDCON+EXHAND
        STORE   R4,R3,EXHAND    ; constraint_error.exhand = oldcon.exhand
        LOAD    R4,R2,OLDCON+EXAR
        STORE   R4,R3,EXAR      ; constraint_error.exar = oldcon.exar

        BR      SDDONE          ; skip around exception handler

SDHAND:                         ; exception handler for showdist
        ; restore old CONSTRAINT_ERROR exception from OLDCON in my AR
        LIL     R3,CONSTRAINT_ERROR
        LOAD    R4,R2,OLDCON+EXHAND
        STORE   R4,R3,EXHAND    ; constraint_error.exhand = oldcon.exhand
        LOAD    R4,R2,OLDCON+EXAR
        STORE   R4,R3,EXAR      ; constraint_error.exar = oldcon.exar

        LEA     R3,SDTBIG
        LIL     R1,DSPST
        ADDI    R2,ARSIZE
        JSRS    R1,R1           ; dspst( "too big" );
        ADDI    R2,-ARSIZE

        ; code outside of exception handler
SDDONE:
        LEA     R3,SDCRLF
        LIL     R1,DSPST
        ADDI    R2,ARSIZE
        JSRS    R1,R1           ; dspst( "\r\n" );
        ADDI    R2,-ARSIZE

        LOADS   R1,R2
        JSRS    R1,R1           ; return

SDMSG:  ASCII   "the distance is ",0
SDUNIT: ASCII   " microns",0
SDTBIG: ASCII   "too big",0
SDCRLF: B       CR,LF,0

There are other ways to do this. Consider representing an exception with a global variable pointing to a local variable in the block that has installed the current handler. That variable, in turn, would hold the addresses of the handler, its activation record pointer, and the previous value of the global pointer.

Exercises

f) The code for SHOWDIST given here contains modest optimizations -- it avoids incrementing and decrementing R2, the activation record pointer, between many pairs of successive calls. Find and eliminate the extra increments and decrements of R2 that remain.

g) Evaluate the beneift eliminating the string SDCRLF from SHOWDIST and making the output identical to the original by adding a trailing carriage return and linefeed to the ends of the two strings SDUNIT and SDTBIG. How much smaller will the program be if this change is made? How much faster will the program run?

h) Translate the code for SHOWDIST to Ada, C++ or Java, documenting any changes you need to make because of any difference in the exception handling model of your target language.

i) Work out the code for saving the old handler and installing a new one, the code for restoring the old handler, and the code for raising an exception, using the alternative representation for exceptions suggested at the end of the section above. Does this alternative require more or less memory? Does this alternative make installing and de-installing handlers faster or slower? Does this alternative make raising exceptions faster or slower?

Traps: Exceptions Detected by Hardware

While the overflow and carry bits in the condition codes of the Hawk and similar machines such as the Pentium can be used to detect exceptions in integer arithmetic operations, the most important exception detection mechanisms of these machines center around detecting exceptions caused by illegal instructions, illegal memory references, and similar faults in the program. Most computer systems detect some or all of the following special conditions:

Hawk Trap Conditions
System Reset Someone pushed the reset button on the computer system, or the machine was just turned on.
Bus Error An attempt was made to read or write a nonexistant memory location or to write to a read-only memory location. Following an uninitialized or null pointer usually causes such a fault.
Illegal Instruction An instruction was executed that is not defined in the instruction set of this computer. Accidentally jumping to an area of memory that does not contain code usually causes such a fault.
Privilege Violation An instruction was executed that is not permitted in the current operating mode. In the case of the Hawk, the CPUGET and CPUSET instructions are only permitted if the level field of the processor status word is set to permit them.

In general, the central processors of modern computers have no understanding of the exception handling mechanisms of the programming languages being used. Instead, the central processor has a completely different model for exceptions, referred to as a trap mechanism. Trap mechanisms were introduced on computers of the 1950s and 1960s, well before the exception models of high-level languages. In almost all cases, it is the operating system that handles traps, not the applicaton program.

In the case of the Hawk, traps operate as follows: First, the instruction that caused the trap is aborted. All traps can be traced back to the execution or attempted executionj of some specific instruction. The address of this instruction in memory is saved in a special register within the Hawk processor, the TPC or trap program counter. If the trap involved a load or store instruction trying to use an illegal memory address, that address is saved in a second register, the TMA or trap memory address register. The level field of the processor status word is also saved in a special field, the old level field, and once all this information is saved, the program counter is set to a value determined by the nature of the trap, and the level field of the processor status word is set to zero (the most permissive level).

The Hawk processor status word
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
level old level BCD carry N Z V C

It is important to note that the Hawk processor guarantees that traps will always be detected before an instruction has a chance to change any of the registers within the processor. Therefore, between the old level field of the processor status word, the TPC register and the contents of registers 1 to 15, everything is just as it was immediately prior to executing the instruction that caused the trap.

When a trap occurs, the new value of the program counter is set to a value that depends on the cause of the trap. Each component of the processor that is involved in detecting traps may provide a 4-bit code; this code is provides bits 4 to 7 of the new value of the program counter, with the remaining bits set to zero. As a result, memory locations from 0 up to 10016 are reserved for trap processing. These locations constitute the trap vector of the Hawk machine. The following locations in the trap vector are used by the trap hardware described here:

The Hawk Trap Vector
System Reset 0000000016 Power-on or someone pushed reset.
Bus Error 0000001016 Illegal memory reference.
Illegal Instruction 0000002016 Use of an unimplemented opcode.
Privilege Violation 0000003016 Use of CPUGET or CPUSET when level is 11112.

Higher numbered locations in the trap vector are available for use by coprocessors, and they are used by interrupt service routines, a topic we will discuss after dealing with traps.

The final tools we need for dealing with traps are tools for examining and setting the special fields of the processor status word and the special registers, TPC and TMA. These are all manipulated using the CPUSET and CPUGET instructions. For example, CPUGET R4,TPC gets the trap program counter register into register 4, and CPUSET R4,PSW sets the processor status word to the contents of register 4. These special instructions have the potential to access up to 16 distinct special registers within the Hawk processor. In commercial processors, special registers are frequently included for diagnostic purposes, and sometimes, the interfaces for devices closely allied to the processor are included here. In the Hawk, there is also a TSV register, advertised as the trap-save register, but actually just 32 bits with no committed purpose, although, as we will see, it is essential.

When the CPUGET instruction is used to get a special register into register zero, this is interpreted as loading the program counter, and it has the side effect of restoring the level field of the processor status word to the old level. Thus, if the only instruction of a trap handler is CPUGET R0,TPC the effect would be to completely undo the effects of the trap and try, again, to execute the instruction that caused the trap. Normally, the trap service routine must do more than this, since retrying the instruction that caused the trap would just cause the trap again, putting the computer into a tight infinite loop!

Exercises

j) What special registers are available within the Hawk processor and how are they encoded for reference by the CPUSET and CPUGET instructions; you will have to look this up in the Hawk manual.

k) Why is the CPUSET instruction dangerous enough that it forces a trap when a user tries to execute it with an inappropriate level? A complete and adequate answer to this question rests on the fact that the level field is also used to control other features of the processor that we have yet to discuss. All you need to know about these is that they are essential features of a secure system.

A Trap Handler

The default trap handlers installed by the Hawk monitor simply print out the contents of the trap program counter and trap memory address registers before halting the program. This helps during debugging, but if a program needs to handle the exception, it is not enough. To handle an exception, the program must install code in the appropriate location in the trap vector to jump to its own trap handler. This handler should then translate from the Hawk's trap model to the exception handling model of your program.

Each entry in the Hawk trap vector is only 16 bytes long, which is 8 halfwords or 4 words. If we have no desire to be able to examine or restore registers, this is more than enough to allow a jump to the user's own trap service routine:

Minimalist code to intercept bus error traps
.       =       #10             ; bus error entry in the trap vector
        LIL     R1,BUSER
        JUMPS   R1              ; go to rest of handler

The weakness of this minimalist approach is that it prevents us from writing a trap handler that displays the contents of all of the registers. The Hawk monitor gets around this by using the trap-save register, TSV, to save the contents of one register before it uses that register to jump to the trap service routine. It is important to remember that the TSV register is never used by applications programs, but only in the context of trap handlers and similar code, so we never need to save and restore the old contents of TSV.

Better code to intercept bus error traps
.       =       #10             ; bus error entry in the trap vector
        CPUSET  R1,TSV          ; save R1
        LIL     R1,BUSER
        JUMPS   R1              ; go to rest of handler

The second version of the trap vector code given here uses 8 bytes for instructions. There is room to squeeze in four more halfwords of code, if we wanted to do so.

Given either of the above bits of code, we can write a trap handler to convert bus error traps into CONSTRAINT_ERROR exceptions, using the Ada convention that the exception CONSTRAINT_ERROR is to be raised whenever a program tries to use a null pointer, so logically, following an unitialized or random-valued pointer ought to raise a similar exception.

Better code to intercept bus error traps
        COMMON  CONSTRAINT_ERROR,EXSIZE

BUSERR:                ; intercept bus error exceptions
        LIL     R1,CONSTRAINT_ERROR
        LOAD    R2,R1,EXAR      ; R2 = CONSTRAINT_ERROR.EXAR
        LOAD    R1,R1,EXHAND
        CPUSET  R1,TPC
        CPUGET  R0,TPC          ; PC = CONSTRAINT_ERROR.EXHAND
                                ; note:  PSW.level is restored!

If we wanted our default trap handler to be able to print out all of the registers as they were at the time of the trap, we would have to add more code to the above to save the values of registers in some dedicated memory area before using any registers for trap handling. This will be illustrated in the next section.

Exercises

l) Modify the bus error trap handler given above so it saves copies of every register it modifies in a common block called TRAPSAVE, including the copy of R1 that was initially saved in TSV. This lets the trap handler recover this information if it is needed.

Emulation Traps and Virtual Machines

Traps have important uses other than exception handling. Of these, one of the most important is in the creation of a virtual machine that supports features not present in the actual hardware. To a user writing machine language code, a virtual machine appears to be hardware, except that some instructions take much longer to execute than others. These are the instructions that are executed by trap handlers, not hardware.

The term virtual machine borrows from terminology originally used in classical optics. In optics, systems of mirrors and lenses may cast several images. Some of these are real images, in the sense that if you put a sheet of film where the image appears to be, the film will capture that image as a photograph. Other images are said to be virtual images; this means that they look like images, but when you put film at the apparent location of the image, it will capture nothing. Virtual images are always seen through lenses, reflected in mirrors, or behind holograms.

From the programmer's perspective, a virtual machine looks like a real machine, but it is an artifact created by the cooperation of some software with a real machine. Some virtual machines are created entirely by software! The Hawk emulator is an example, and so is an IBM PC emulator that runs on an Apple Power Macintosh. Other virtual machines are mixtures of real hardware and software; these are created using trap handlers.

In the Hawk, there are several unimplemented opcodes; if one of these is used, the result is an illegal instruction trap. In addition, if the level field of the processor status word is 11112, use of the CPUSET and CPUGET instructions causes privilege violation traps. In combination with a memory management unit, this allows protected-mode operation in which an untrusted program can be securely confined to a limited domain within the computer. We will discuss the latter in more detail later.

On the Hawk, the opcode 0001dddd 1000ssss2 is unimplemented. As a halfword, with the bytes in the correct order and the register fields set to zero, this is 801016. Suppose we wanted to use this opcode as a virtual register-to-register multiply instruction. To do this, we must install a new unimplemented instruction trap handlerk. Because our software multiplication routine needs many registers, we will save everything on entry to the trap service routine and then restore it on exit.
 

Defining a Register Save Area
        COMMON  SAVEREGS,17<<2  ; save area for registers
PCSAVE  =       0               ; displacements within save area
R1SAVE  =       1<<2
R2SAVE  =       2<<2
R3SAVE  =       3<<2
R4SAVE  =       4<<2
        .
        .
        .
RESAVE  =       14<<2
RFSAVE  =       15<<2
PSWSAVE =       16<<2

 
The code to save registers in this register save area begins in the trap vector, right after the program uses the TSV register to save a copy of R2. Recall that each entry in the trap vector is only 16 bytes long. This means that we need to use the remainder of the words in the trap vector to jump to the rest of the handler, wherevere it is. It makes sense to group the pointers needed by code within the trap vector at the end of the trap vector, as suggested here.

 

Unimplemented instruction trap vector code
.       =       #20             ; unimplemented instruction trap
        CPUSET  R2,TSV          ; save R2 temporarily
        LIL     R2,SAVER
        STORE   R1,R2,R1SAVE    ; save R1 properly
        LIL     R1,UNIMP
        JUMPS   R1              ; go to the handler
        ; the above code occupies exactly 16 bytes!

 

The remainder of the trap handler is closely tied to this code. On entry, it must assume that only R1 has been completely saved, and that R2 is still incompletely saved in TSV. The fact that the Hawk LOAD and STORE instructions do not touch the condition codes is essential to the correct functioning of this code, since the PSW still needs to be saved. The remainder of the job of saving the entire CPU state can be done as follows:

 

Saving the rest of the registers
; unimplemented instruction trap handler continuation

UNIMP:                  ; on entry, R2 points to the register save area
                        ;           R1 has been saved
                        ;           TSV still holds the saved R2
                        ;           PSW (including CCs) still unsaved
        CPUGET  R1,PSW
        STORE   R1,R2,PSWSAVE   ; PSW is now properly saved
        CPUGET  R1,TSV
        STORE   R1,R2,R2SAVE    ; R1 is now properly saved
        CPUGET  R1,TPC
        STORE   R1,R2,PCSAVE    ; PC is now properly saved
        STORE   R3,R2,R3SAVE    ; continue saving R3 to R15
        STORE   R4,R2,R4SAVE
        STORE   R5,R2,R5SAVE
                .
                .
                .
        STORE   R13,R2,RDSAVE
        STORE   R14,R2,RESAVE
        STORE   R15,R2,RFSAVE   ; entire CPU state is now saved

 

The code for detecting the instruction we want to emulate goes next, but before we distract ourselves with this, let us focus on the problem of returning from the trap! We do this by restoring the registers, and then, very carefully, we end by using the CPUSET and CPUGET instrucitons to put the program counter and processor status word back.

 

 

 

Restoring the registers
; return from any trap handler
TRAPEXIT:               ; on entry, R2 points to register save area
        LOAD    R15,R2,RFSAVE   ; start restoring registers
        LOAD    R14,R2,RESAVE
        LOAD    R13,R2,RDSAVE
                .
                .
                .
        LOAD    R5,R2,R5SAVE
        LOAD    R4,R2,R4SAVE
        LOAD    R3,R2,R3SAVE    ; R15 to R3 now all restored
        LOAD    R1,R2,PCSAVE
        CPUSET  R1,TPC		; PC partially restored
        LOAD    R1,R2,PSWSAVE
        CPUSET  R1,PSW          ; PSW now restored
        LOAD    R1,R2,R1SAVE    ; R1 restored without changing CCs
        LOAD    R2,R2,R2SAVE    ; R2 restored without changing CCs
        CPUGET  R0,TPC          ; return from trap!

The above code uses the strange semantics of R0 on the Hawk machine. In the context of the CPUGET instruction, R0 refers to the program counter, so the final instruction above loads the program counter from the TPC register. This has the side effect of restoring the level field of the PSW.

The code that does the actual work of our virtual machine, between saving and restoring the registers, begins by finding out what instruction was attempted, since, if it was not the desired 0001dddd 1000ssss2, we should raise the same exception that the original handler would have raised.

Checking what instruction caused the trap
; see if the unimplemented instruction was 0001dddd 1000ssss
                ; all registers have been saved
                ; R2 points to register save area
        LOAD    R3,R2,PCSAVE    ; get the saved program counter
        LOADS   R4,R3
        EXTH    R5,R4,R3        ; the the halfword it points to
                ; R4 is the instruction that caused the trap!
        LIL     R6,#F0F0
        AND     R5,R6           ; clear all but the opcode bits
        CMPI    R5,#8010        ; is it the target instruction?
        BEQ     ISMULT

        LIL     R3,PROGERR      ; it is not the target!
        LOAD    R4,R3,EXAR
	STORE   R4,R2,R2SAVE    ; edit saved processor state
        LOAD    R4,R1,EXHAND
	STORE	R4,R2,PCSAVE
	JUMP	TRAPEXIT        ; normal trap exit code finishe it

In the above, once we separated out the instruction or instructions we intend to virtualize, the remaining protection violations are signalled using the program error exception.

With these pieces in place, we can extend the user's virtual machine by writing the code that converts gives our multiply opcode the desired semantics. This begins by getting copies of the user's source and destination registers, and after it multiplies them, it returns the result to the user's destination register. In addition, the handler must increment the saved program counter before return.
Making an unimplemented instruction do multiplication
ISMULT:         ; protection violation caused by CPUGET
                ; R2 points to register save area
                ; R3 is the saved program counter
                ; R5 is the word pointed to by PC
        MOVE    R6,R5           ; copy the instruction
        SR      R5,8
        TRUNC   R5,4            ; R5 is the src register number
        TRUNC   R6,4            ; R6 is the dst register number

        ADDSI   R3,2
        STORES  R3,R2,PCSAVE    ; increment saved PC

        ADDSL   R5,R2,2         ; R5 points to saved dst register
        ADDSL   R6,R2,2         ; R6 points to saved src register

        LOADS   R3,R5           ; R3 is the dst operand
        LOADS   R4,R6           ; R4 is the src operand

        ... code to multiply R3 = R3 * R4 ...

        STORES  R3,R5           ; update the saved dst register
        JUMP    TRAPEXIT        ; go return to user

Now that we have defined a multiply instruction, we also need to extend our assembly language with a multiply macro! This will look something like the following:

Restoring the registers
	; note: the following uses an unimplemented
	; opcode and is implemented by emulation using
	; a trap service routine.
        MACRO   TIMES   =src,=dst
          B #10 | (dst - R0)
          B #80 | (src - R0)
        ENDMAC

In this macro, we could have used dst and src instead of dst-R0 and src-R0, but by explicitly subtracting R0 from each register, we force the assembler to check that dst and src are relocated relative to the same relocation base as is used for the registers. The result is better error checking at assembly time.

Exercises

m) Find all of the opcodes in the Hawk instruction set that cause illegal instruction traps. Do this by searching the lists of opcodes in the appendices of the Hawk manual.

n) What code should you add to the start of the main program if you want user code to be able to use the TIMES instruction defined here?

o) Suppose you wanted to be able to call Hawk monitor routines from your trap handler, for example, to use the multiply or divide routines that are built into the monitor. Some of these routines need to use R2 as a stack pointer. What code would you add to the code given above above for trap handlers in order to allow this! (Hint: We used R2 as a pointer to the register save area for a good reason.)

p) Assume you are not allowed to call subroutines from the trap handler. Add the multiply code to the figure above in place of the text ... code to multiply R3 = R3 * R4 ... (You will have to add this code in-line, without calling a subroutine).

q) The multiply instruction emulation given above does not set the condition codes. Add code so that it sets the N and Z condition codes to report whether the result is negative or zero.

Interrupts

The mechanisms we have described above for trap handling serve a second purpose on essentially all modern computers, and that is handling external events signalled by input-output devices. When these mechanisms are triggered by an external device, we refer to the event as an interrupt, not a trap, but the mechanisms for handling these events are very similar. The control transfers are directed through the same trap vector, which is also called the interrupt vector, and the code to save and restor registers is the same; only the cause of the control transfer and actions we take in response are different.

In essentially all modern computers, the fetch execute cycle of the hardware is more complex than we have indicated up to this point, in part because of the need to handle exceptional conditions, and in part because of the need for interrupt handling. The Hawk processor is quite typical; here is a more honest and complete presentation of the algorithm implemented by the Hawk processor:
 

The fetch-execute cycle
int trapvector, interruptvector;
while (TRUE) do {
        try {
                fetch_and_execute_one_instruction();
        } catch( int vector ) {
                trapvector = vector;
        }
        if (trapvector == 0) {
                trapvector = interruptvector;
                interruptvector = 0;
        }
        if (trapvector != 0) {
                PSW.old_level = PSW.level;
                PSW.level = 0;
                TPC = PC;
                PC = trapvector;
                trapvector = 0;
        }
}

Under normal circumstances, if execution of an instruction raises no exceptions and if no external device requests an interrupt, the complexity at the end of this code does nothing, so it is equivalent to the naieve view of the fetch-execute cycle. If that instruction raises a trap, however, or if an external device requests an interrupt, the story is different.

Interrupts and traps both use the same trap vector. In the case of traps, it is up to the hardware inside the processor to specify which trap vector entry will be used. In the case of interrupts, it is up to the external device to specify this.

External devices should only raise their interrupt request lines (IRQ) when the deivice is ready to perform an input or output operation and only when the program running on the central processor is ready to deal with this condition. Typically, we use the ready bit in the device status register to determine when the device will attempt to request an interrupt, but we design the device so that this request will only be made if the interrupt is enabled. The Hawk keyboard interface register logic for this is typical:
Interrupt request logic in the keyboard status register
Keyboard Status Register

All modern computers have are hierarchies of interrupt enable bits. Each device has its own interrupt enable bit, and there are also one or more global interrupt enable bits. In the case of the Hawk, the global interrupt enable bits are the level field of the processor status word. If this field is 00002, all interrupts are disabled, while 11112 enables all interrupts. Intermediate values enable just some.

The Hawk level field is typical of modern processors. It determines the interrupt priority level. Higher priority devices can interrupt lower priority devices, but not the reverse. Many processors have a set of outputs that directly report the current priority level to external logic, and that logic gives meaning to these bits. In the case of the Hawk, there are two good ways to do this. First, each bit of the level field could be used to enable one group of related devices. In that case, we could have 5 levels, encoded as 00002, 00012, 00112, 01112, and 11112. This allows very simple interface hardware, but it is only suitable if there are only a few devices that use interrupts.

The other approach is to add an external priority interrupt decoder. This allows for 16 levels, encoded as a 4-bit binary number. Mixtures of these schemes are perfectly possible. For example, the most significant bit of the level field on the Hawk enables the memory management unit, So we could decode the least significant 3 bits to create 8 different interrupt levels. This mixed approach allows us to associate trap vector entries 8 to 15, at addresses 8016 to F016 with the corresponding interrupt levels.

Interrupt priority involves two distinct issues: First, if two distinct devices request interrupts at the same time, the priority determines which device wins. Second, if one interrupt service routine is running, the priority of an device requesting an interrupt determines whether that request will be granted before the first routine terminates.

On the Hawk, if two interrupt service routines use separate register save areas, then the lower priority interrupt service routine can re-enable interrupts between the time it saves its registers and the time it restores them. It must not enable its own interrupt, but it can set the level field of the processor status word (using the CPUSET instruction) to allow all higher priority interrupts.

Exercises

r) If each bit of the level field enables interrupts for one device, and if the keyboard interrupt enable bit in the level field of the processor status word is 00102, what instructions should be used just after saving all of the registers to enable all other interrupts?

s) If the least significant 3 bits of the level field of the PSW are used to encode a binary interrupt level, with 00002 meaning disable all interrupts and 01112 meaning enable all interrupts, and if keyboard interrupts are enabled whenever the interrupt level is 00102 or greater, what instructions should be used just after saving all of the registers to enable all other interrupts?

t) If interrupts were enabled within an interrupt service routine, what code must be inserted just before the code to restore the values of the registers in order to make sure that the job of restoring the registers is not itself interrupted.

u) Suppose two different devices have equal priority and they use the same trap vector entry. How can the software determine which device requested the interrupt? Hint: Each device has its own ready bit and its own interrupt enable bit.