% FINAL EXAM (with and without answers), v22.0201.002, Fall 1997, Yap
% -- To get answers printed or suppressed,
%	simply redefine the ignoreAlt command!
%
%	BUG: this doesn't quite work, because programs (in verbatim mode) cannot
%	be inside an argument.  Yikes.  Instead, these programs
%	are put inside the \ignore command.  Unfortunately,
%	you cannot redefine \ignore to bring back these programs.
%	INSTEAD, you have to comment out the \ignore commands...

\documentclass{article}
\input{mac}
\setlength{\oddsidemargin}{0pt}
\setlength{\evensidemargin}{0pt}
\setlength{\topmargin}{-.5in}
\setlength{\textwidth}{6.1in}
\setlength{\textheight}{8.5in}
\def\baselinestretch{1.6}

\newcommand{\ignoreAlt}[2]{#2}

\newcommand{\pts}[1]{{\bf\ (#1 POINTS)\\}}
\newcommand{\ans}{{\bf ANSWER: }}
\newcommand{\lline}[1]{\hspace*{0.1in} \hrulefill\hspace*{#1in}\\ }

\begin{document}
\begin{center}
\large
\hfill    V22.0201, Computer Systems Organization I  \hfill    Fall 1997\\
\end{center}

NYU ID: \ \hrulefill\quad NAME: \ \hrulefill\\
SEAT NO: \ \hrulefill\quad PROFESSOR: \hrulefill\\

% \begin{center}
% \Large
% FINAL EXAM\\
% Write directly on the exam.
% You are allowed 8 pages (=4 sheets) of 8.5''x11'' set of prepared notes.
% \end{center}

\begin{center} \bf
\fbox{
\begin{minipage}{5in}
This is VERSION B of the Exam
(students randomly receive one of several versions).
Write directly on this exam question sheets.
For full credit, show all workings and justifications
on THIS exam sheet.
Exam workbooks are provided for rough work only, but these
must also be turned in with the exam sheets.
\\
NOTE: in your programs, feel free to use macros
in the textbook or in our ``basic.mac'' file,
provided you first ``include'' the macro file.
\end{minipage}
}
\end{center}

\normalsize

% \def\baselinestretch{1.8}
\begin{enumerate}

\item
\pts{5+5+5}
(i) Illustrate and briefly explain the 
``based indexed addressing mode''.
\\
\ignoreAlt{
\ans\ \lline{.6}
\ \lline{.5}\ \  
\ \lline{.5}\ \  
}{
\ans\ 
E.g. mov ax,[var+bx+si+4].
This addressing mode uses a based register (bp or bx)
and an index register (si or di).  It could
optionally use a variable offset and a constant.
}%ignoreAlt
%
\\
(ii) Illustrate and briefly explain the idea of segment override.
\\
\ignoreAlt{
\ans\
\lline{.6}
\ \lline{.5}
\ \lline{.5}
}{
\ans\ 
E.g., mov ax,es:[si].  The default segment of SI is
DS, but this is overridden by ES.
}%ignoreAlt
%
\\
(iii) What is a palette, and why are palettes used in video
graphics?
\\
\ignoreAlt{
\ans\
\lline{.6}
\lline{.5}
\lline{.5}
}{
\ans\ 
A palette is a suite of colors (out of a much larger set
of possible colors) that can be used simultaneously.
It is used because we typically can address much fewer
colors than the total number of possible colors.  E.g.
using one byte per pixel, we can only address 256 potential colors
while the number of possible colors may be 16 million, say.
}%ignoreAlt

\item
\pts{5+5+5+5}
{\bf Circle the correct answer (True or False).
Brief reasoning can be accomodated (write in margin).
You receive up to $-3$ points for a wrong
answer, and $0$ points if you leave the answer blank.}
\\ (i) {\bf True or False:} 
Using just the logical operations (AND, OR, NOT, XOR), together
with shifts, rotates, moves and conditional jump instructions,
it is possible to write a procedure
to add two numbers stored in AL, BL (say).
In other words, we can avoid using the arithmetic
operations (ADD, SUB, MUL, IMUL, DIV, IDIV).
%
\\ (ii) {\bf True or False:}
The reason we use INTERRUPT ROUTINES is because we do not
want to waste CPU time for executing these routines.
%
\\ (iii) {\bf True or False:}
The EQU instruction is translated into
an assembler instruction for execution at run time.
%
\\ (iv) {\bf True or False:}
It is possible for two variables (say, VAR1 and VAR2)
to refer to the same memory location.
%
\ignoreAlt{\ 
}{
\\ \ans\\
(i) TRUE: you can practically do anything using these
operations.  Only they are inconvenient and slow.
\\
(ii) FALSE: interrupt routines are still processed by
the CPU.
\\
(iii) FALSE: EQU's are simply replaced by constants
in the assembled programs.  There is no run-time instructions.
\\
(iv) TRUE: yes, you can use the LABEL pseudo instruction to
get two or more variables to refer to the same location.
} %ignore
 
\item
\pts{8+8}
Consider the bit pattern $0CADh$, written in hex.
What is its value when viewed
(i) as an unsigned number, 
(ii) as a signed 12-bit number?
Write your answers in decimal.
\\
\ignoreAlt{
\ans (i)
\lline{2}
\lline{1.1}
\ans (ii)
\lline{2}
\lline{1.1}
}{
\ans\
(i) $3245$, (ii) $-851$.
}%ignoreAlt

\item
\pts{10}
The following code has an error because the conditional
jump instruction causes a jump over a distance of more than 127 bytes.
Modify it so that it works correctly: 

        \begin{single}
        \begin{center}
	\fbox{
	\begin{minipage}{4in}\tt
\hspace*{1in}         ...
\\\hspace*{.5in}    AGAIN:
\\\hspace*{1in}          ...
\\\hspace*{1in}          (over 127 bytes of code here)
\\\hspace*{1in}          ...
\\\hspace*{1in}          CMP AX,BX
\\\hspace*{1in}          JZ AGAIN
\\\hspace*{1in}          ...
	\end{minipage}
	}
        \end{center}
        \end{single}
%
\ignoreAlt{
\ans\
\ \vspace*{1in}\\
\ \vspace*{1in}\\
}{
\ans\ 
        \begin{single}
        \begin{center}
	\fbox{
        \begin{minipage}{4in}\tt
\hspace*{1in}        ... 
\\ \hspace*{.5in}   AGAIN: 
\\ \hspace*{1in}        ... 
\\ \hspace*{1in}        (over 127 bytes of code here)
\\ \hspace*{1in}        ... 
\\ \hspace*{1in}        CMP AX,BX 
\\ \hspace*{1in}        JZ GO_BACK 
\\ \hspace*{1in}        JMP CONTD
\\ \hspace*{.5in}   GO_BACK:
\\ \hspace*{1in}        JMP AGAIN
\\ \hspace*{.5in}   CONTD:
        \end{minipage}
	}
        \end{center}
        \end{single}
NOTE: some people tried to create an intermediate label
to break up the portion of code that you have to jump over.
But that is not a general solution: what if you have more than
256 bytes of code to jump over? Then you need two intermediate
labels to jump to, etc.
} %ignoreAlt

\item
\pts{20+20}
In this question, you are to write
two modules entitled ``MAIN'' and ``SUM'' (respectively).
They are to be tlinked together: TLINK MAIN+SUM.
Use the (standard) small model.
PLEASE COMMENT YOUR CODE AND IT SHOULD BE
COMPLETE (i.e., ready to assemble and run).
\\
(i)
The module ``SUM'' contains
only one procedure called ``SUM'', which
is intended to be called from some other module. 
Procedure SUM takes three arguments which are
passed on the stack.  The first two arguments
are integers, and the third argument is the offset
of a word variable.  The procedure SUM must add up
the first two arguments and store the result in the
variable of the third argument.  Upon return,
we want SUM to pop the arguments off the stack.
HINT:
It is good programming practice to
use EQU's to refer to the arguments on the stack.
\\(ii)
The MAIN module contains a procedure called MAIN which simply calls
the SUM procedure with the arguments
	\begin{center}
	2, 3, Offset X
	\end{center}
where X is a word variable.  On return from
the procedure call, the variable X should contain the value 5.
NOTE: We do not ask you to do any outputs, so this
program is not doing anything useful.  
\\
\ignoreAlt{
\ans\ (Please use the reverse side of the previous page for more space)\\
% \lline{1}
% \lline{.5}
\ \vspace*{2in}\\
\ \vspace*{2in}\\
\ \vspace*{2in}
}{
\ans\
}%ignoreAlt
% \ignore{
(i) SUM MODULE
	\begin{center}
	\begin{single}\tt
	\begin{verbatim}
	title SUM
	public SUM      ; make SUM known to other modules
	.model small
	if1
		include ..\mac\basic.mac
	endif
	.code
	; we use EQU's to name the 3 arguments on the stack
	arg1	EQU word ptr [bp+8]
	arg2	EQU word ptr [bp+6]
	result	EQU word ptr [bp+4]

	SUM proc 
	  push bp	; save bp
	  mov bp,sp	; set bp to Top of Stack
	  save <ax,bx>	; macro, save registers
	  mov ax,arg1	; get first argument
	  add ax,arg2	; add the second argument
	  mov bx,result ; get offset of result variable
	  mov [bx],ax   ; store the result in third argument
	  restore <bx,ax> ; restore registers
	  mov sp,bp	; restore sp
	  pop bp	; restore bp
	  ret 6		; return, and pop off arguments
	SUM endp	
	end		; end of module
	\end{verbatim}
	\end{single}
	\end{center}

(ii) MAIN MODULE
        \begin{center}
        \begin{single}
        \begin{verbatim}
	title MAIN
	extrn SUM:near	; proc SUM is defined elsewhere
	.model small
	if1
          include ..\mac\basic.mac  ; macro file
	endif
	.stack 100h
	.data
	X dw ?
	.code
	MAIN proc
	  initdata	; macro to initialize DS
	  push 2	; first argument
	  push 3	; second argument
	  lea ax,X
	  push ax	; third argument
	  call sum
	  ;
	  exitdos	; macro to exit to DOS
	MAIN endp
	end MAIN	; begin executing at MAIN
        \end{verbatim}
        \end{single}
        \end{center}
% }%ignore

\item
\pts{20+10+8}
Recall that in HW4, we programmed a very simple {\bf text editor}
in video mode 3 (CGA text mode).  You could move your
{\bf text cursor} (using the arrow keys), toggle between
the APPEND or REPLACE modes (using INS key),
insert text in the current mode,
mark the current text cursor position (using F1),
and jump to the marked position (using F2).
\\
(i)
The {\bf mouse pointer} is different from the
{\bf (text) cursor}: in mode 3, both are shown as white rectangles
but only the text cursor blinks (this is the default setup).
You can move the mouse pointer anywhere much
faster than the arrow keys can move the text cursor.
Hence, we want to make the text cursor jump
to the current position of the mouse pointer whenever
function key F3 is pressed.
Assume that our editor program has been modified so that
the mouse is initialized properly, and it
calls a procedure called {\bf mov\_2\_mse} whenver F3 is pressed.
Write this procedure {\bf mov\_2\_mse} (which takes no arguments).
\\
HINTS: The necessary interrupts
are provided below.  Also recall that the mouse pointer position
is measured in pixels (on a screen of size 320x200)
but the text cursor position is measured
in character-size blocks (on a screen with 80x25 characters).
Divide the pixel distances by 8 to convert to character block distances.
\\
(ii)
Instead of using F3, a better solution is to
allow the user to click a mouse button to accomplish
the same effect as part (i).  We now want to use 
the procedure {\bf mov\_2\_mse} as a mouse interrupt
routine.  Describe in words what you need to
modify in your answer to part (i)?
\\
(iii)
Write those lines of code needed to install {\bf mov\_2\_mse}
routine from part (ii) as the mouse interrupt function
to be called whenever the left or the right mouse
buttons are released.  Where should this code be placed
in the editor program?
\\
\ignoreAlt{
\ans\ (Please use the reverse side of this page for more space)\\
% \lline{4.5}
% \lline{5}
\ \vspace*{2in}\\
% \ \vspace*{2in}
}{
\ans\
} %ignoreAlt

% \ignore{
(i)
        \begin{center}
        \begin{single}
        \begin{verbatim}
   .386			;directive
   mov_2_mse proc
        mov ax,3        ;fn=get mse ptr location in pixels
        int 33h
        shr cx,3        ;div by 8 gives corresponding text cursor x-pos
        shr dx,3	;div by 8 gives corresponding text cursoe y-pos
        push dx
        mov dl,cl       ;dl specifies tne new text cursor col (0-79)
        pop cx
        mov dh,cl       ;dh specifies the new text cursor row (0-24)
        xor bh,bh       ;page 0
        mov ah,2        ;fn=move cursor
        int 10h
        ret
   mov_2_mse endp
        \end{verbatim}
        \end{single}
        \end{center}
(ii) 
Changes to mov\_2\_mse:
\\
(a) You need to replace "ret" by "iret".
\\
(b) Also, the {\bf mov\_2\_mse} procedure is now called by
the mouse interrupt which will provide the mouse pointer position
(in registers CX and DX, so that you no longer need to call int 33h, fcn=3.
\\
(c) As usual, in all interrupt routines,
we have to make sure that all the
registers are properly restored
at the end of the procedure.
\\
(d) Make the procedure a far procedure.
\\
(e) REMARK: It is not needed in our case, but in general, you would
need to initialize DS if you use any variables.
(iii)
\\
NOTE: THIS DOES NOT WORK UNDER WinNT???
\\
We only need to call INT 33h, Function 0Ch.
Put the following instructions in
the editor program, right after the initialization of the mouse:
	\begin{center}
        \begin{single}
        \begin{verbatim}
	mov ax,seg mov_2_mse
	mov es,ax		; set up ES
	lea dx,mov_2_mse	; or, mov dx,offset mov_2_mse
	xor ch,ch		; set up CX as event mask
	mov cl,00010100b	; left- and right-button release events only
	mov ax,0ch		; fcn=install interrupt handler
	int 33h
        \end{verbatim}
        \end{single}
        \end{center}

%} %ignore


\end{enumerate}


% \ignore{
\newpage

\begin{single}
\begin{verbatim}
INTERRUPTS THAT MAY BE USEFUL FOR YOUR PROGRAMS
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

|============================================|
|  MOUSE INTERRUPTS (INT 33H)                |
|     (The function number is loaded in AX)  |
|============================================|
Function 0 -- Initialize Mouse
        Input:
        Output:
                AX = mouse status  -1 = installed
                                0 = not installed
                BX = number of buttons
                OTHER ACTIONS: mouse pointer made invisible
                        and placed at center of screen.

Function 1 -- Show Mouse Pointer
        Input:
        Output: none

Function 3 -- Get CURRENT Button and Pointer Status
        Input: 
        Output: BX=status of buttons
                   -- Bit 0 refers to left button
                   -- Bit 1 refers to right button
                   -- Bit 2 refers to center button
                   If a bit is set, the corresponding button is pressed.
                CX= x-coordinate in pixels
                DX= y-coordinate in pixels
                   (Divide pixel counts by 2 for medium resolution
                   and divide by 8 for text modes)

Function 0Ch -- Install user interrupt function for mouse events
        Output: none
        Input:
                ES:DX= address of user interrupt routine
                CX=event mask (set those bits corresponding to events
                        that the routine must handle):
                        bit 0=mouse pointer has moved
                        bit 1=left button pressed
                        bit 2=left button released
                        bit 3=right button pressed
                        bit 4=right button released
                        bit 5=center button pressed
                        bit 6=center button released
        NOTE: the user interrupt routine should save all registers
        and initialize DS to your own data segment if necessary.
        Before IRET, you should pop all registers.  The routine
        will be called with the following inputs:
                AX=events that caused this interrupt to be called.
                        The bits are associated with events as 
                        indicated for CX above.
                        E.g., bit 4 is set if this is caused by
                        the right button being released.
                BX=current button status:
                        Bits 0/1/2 correspond to
                        left/right/center Buttons, respectively.
                CX:DX=the X- and Y-coordinates of mouse pointer
                SI:DI=the last vertical and horizontal mickey counts
                DS=data segment for mouse driver

|==============================================|
|  VIDEO INTERRUPTS (INT 10H)                  |
|      (The function number is loaded in AH)   |
|--============================================|

Function 0 -- Select Display Mode
        Input:
                AL=mode number
        Output:	None

Function 2 -- Set Cursor Position
        Input:
                DH = row (0-24)
                DL = col (0-79)
                BH = 0 (the video page)
        Output: the cursor is placed

Function 0Fh -- Get Video Mode
        Input:
        Output:	AH = number of screen columns
                AL = display mode
                BH = active display page

\end{verbatim}
\end{single}
% }% ignore



\end{document}

