CSc 335
Code for Implementing Write

The following code will allow your user programs to execute a basic Print command. It can't handle variables like printf can, but you can use it to print simple messages that can aid you in debugging. Thanks to Prof. Aaron Cass for providing this code.


Put the following function somewhere in exception.cc.

//Use the real printf to print the array of characters, one
//char at a time.  We need to do this char-by-char due to the
//possibility of the char array crossing page boundaries.
void printVirtualCharArray(int va, int size)
{
    int tmp;
    int i;
    
    for (i = 0; i < size-1; i++) {
        if (!machine->ReadMem(va+i, 1, &tmp)) {
            printf("%s trouble getting value at %d\n", 
                   currentThread->getName(),
                   va+i);
            return;
        }
        printf("%c", tmp);
    }
}

The following code goes into the if-else ladder in the ExceptionHandler function in exception.cc. This code catches the Write system call when invoked. It calls the printVirtualCharArray function above to get the job done. Note that the last thing this does is call a function called AdvancePC that advances the PC after the system call is done. I'm not giving you the code for AdvancePC since it is something you need to write for Project 3. So this code won't work until you write that function.

else if ((which == SyscallException) && (type == SC_Write))
    {
      DEBUG('e', "%s WRITING.....", currentThread->getName());
      int fd = machine->ReadRegister(6);
      ASSERT(fd == 1);
      int size = machine->ReadRegister(5);
      int vaddr = machine->ReadRegister(4);
      printVirtualCharArray(vaddr, size);
      AdvancePC();
    }

The following is a sample user program. The first function defines a Print function to make it easy to use the Write system call.

void print(char *msg)
{
     int n = 1;
     char *ptr = msg;

     while(*ptr != '\0')
     {
             ptr++;
             n++;
     }

     Write(msg, n, ConsoleOutput);
}

int main()
{
     print("Look ma, I'm printing!\n");
}

CSc 335 Homepage