# Assignment 6 Solutions

### Assignment 6, due June 30

1. Do problems 3 and 9 in Chapter 7.
3. Given that A, B and C are relocatable, in the expression (5-A)+(B+C)
a) What is the relocatable value of this expression?

(5 - (A'+R)) + ((B'+R) + (C'+R)) =
5 - A' - R + B' + R + C' + R =
(5 - A' + B' + C') + (-R + R + R) =
(5 - A' + B' + C') + R

b) Why won't most assemblers accept this expresson?

Because assemblers will try to evaluate the terms in the order indicated by the parentheses, and the term (B+C) evaluates to (B'+C'+2R) which cannot be expressed as a relocatable value.

c) Rewrite into an equivalent form that most assemblers would accept.

(5 - A' + B' + C') + R =
(5 - A' + B') + (C'+R) =
(5 - A' + B') + C =
(5 + B' - A') + C =
5 + (B' - A') + C =
5 + (B - A) + C =

Note that the term (B-A), the difference of two relocatable values, is absolute.

9. Rewrite Figure 7.1 to alow for a linkage editor as well as a loader
```                     -------------
| Source Text |
-------------
/      \      assembler's
programmer's  /        \   view of meaning
view of    /       -------------
meaning   /       | Object Code |
/         -------------
/                      \    of meaning
/              --------------------
/              | Linked Object Code |
/                --------------------
/                                \    of meaning
------------------                 --------------
| Abstract Meaning | ------------- | Machine Code |
------------------                 --------------
hardware's
view of meaning
```
2. Do problem 2 from Chapter 8, but specifically, use the C fgetc function to read individual characters from open input stream, and use it to implement mygets(), a routine that reads a line from the stream. The semantics of your mygets should match that of fgets, and you can use the Unix man command to look up both fgetc and fgets on any Unix or Linux system. You can test your code if you want to.
```	char * mygets( char * s, int size, FILE * stream )
{
char * p = s;
while (size > 0) {
int ch = fgetc( stream );
if (ch == EOF) break;
*p++ = ch;
size--;
if (ch == '\n') break;
}
if (size > 0) {
*p++ = '\0';
}
}
```
3. Write, in C, a loader for the object language given in the new machine problem. This should load directly into memory instead of producing a listing, as in the test code given above. Note that you're not likely to be able to actually run this loader.
```#include
/* this code is based on the test program from the machine problem */
char * location;
for (;;) {
int byte1;
byte1 = getchar();
if (byte1 == EOF) { puts("; normal EOF"); exit(-1); }
if (byte1 == 1) {
int byte2 = getchar();
int byte3 = getchar();
location = (char *)((byte2 << 8) + (byte3 & 0xFF));
} else if (byte1 == 2) {
int byte2 = getchar();
*location++ = byte2 & 0xFF;
} else if (byte1 == 3) {
int byte2 = getchar();
int byte3 = getchar();
*location++ = byte2 & 0xFF;
*location++ = byte3 & 0xFF;
}
}
}
```