CS202: HW 8: Virtual memory reinforcement

CS202: HW 8: Virtual memory reinforcement

mmap()

Consider the following code excerpt that uses mmap():

int main(int argc, char* argv[]) {
    // ...
    // readme.txt is a file that is 5KB in length.
    int fd = open("readme.txt", O_RDWR, 0);

    char *map1 = (char*)mmap(NULL, 5120, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    char *map2 = (char*)mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    // assume that neither mmap call fails

    char x = 0;
    char y = 0;
    // Line 1
    for (int i = 0; i < 5120; i++) {
        x = map1[i];
        y = map2[i % 4096]; 
    }
    // Line 2
    // ...
}

// The signature of mmap is:
//
//   void* mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset);
//   
// If addr is NULL, the kernel chooses the start virtual address.
//
// If not already in memory, disk blocks are fetched into physical pages on access.
//
// Each separate call to mmap() with the same fd maps the file in a separate
// location and does not undo prior mappings. This means that in the example
// above, the file can be read and written from multiple virtual addresses
// within the same address space.

Assume the operating system minimizes the number of virtual and physical pages required in order to implement mmap().

  1. How many last-level (level-4) page table entries are created or modified as a result of the two mmap() calls?

  2. At line 2, how many physical pages are mapped into the process as a result of the mmap() calls?

Detecting overruns

In this problem, you will describe how the implementation of malloc() can exploit paging so that the system (as a whole) can detect certain kinds of out of bound accesses; an out of bound access is when a process references memory that is outside an allocated range. In this problem we focus on overruns. Consider this code:

      int *a = malloc(sizeof(int) * 100); /* allocates space for 100 ints */
      a[0] = 5;    /* This is a legal memory reference */
      a[99] = 5;   /* This is also a legal memory reference */
      a[100] = 6;  /* This is an overrun, and is an illegal memory reference. */

When the above executes, the process would ideally page fault as a result of an illegal memory reference, at which point the kernel would end the process.

Assume that malloc() can maniuplate the virtual address space of the process (for example, using mmap(), or else you can assume that malloc() itself is a system call so its implementation is inside the operating system).

  • Describe how the implementation of malloc() can arrange for page faults when there are overruns like the one above. Do not write more than three sentences.

Handing in the homework

Use Gradescope; you can enroll in our course with entry code JBGJKG. (And please feel free to send us feedback about Gradescope.)