Lab Solution

Assignment Task: memory dump (Lab1-w1)

Objective: Implement memdump(char *fmt, char *data) to print memory contents based on specific format characters.

1. Full Code Solution (user/memdump.c)

void
memdump(char *fmt, char *data)
{
  char *p = data;

  for (int i = 0; fmt[i] != 0; i++) {
    switch (fmt[i]) {
      case 'i': { // 4 bytes as 32-bit decimal integer 
        int v = *(int *)p;
        printf("%d\n", v);
        p += sizeof(int);
        break;
      }
      case 'p': { // 8 bytes as 64-bit hex integer
        // Print each of the 8 bytes from highest address to lowest
        for (int j = 7; j >= 0; j--) {
          unsigned char b = p[j];
          // Print each byte as 2 hex digits
          // We use a small helper or manual hex math since xv6 printf is limited
          char *hex = "0123456789abcdef";
          printf("%c%c", hex[b >> 4], hex[b & 0x0f]);
        }
        printf("\n");
        p += 8;
        break;
      }
      // this version prints the 0x infront
      // case 'p': { // 8 bytes as 64-bit hex integer [cite: 49]
      //   uint64 v = *(uint64 *)p;
      //   printf("%p\n", (void *)v);
      //   p += sizeof(uint64);
      //   break;
      // }
      case 'h': { // 2 bytes as 16-bit decimal integer [cite: 50]
        short v = *(short *)p;
        printf("%d\n", v);
        p += sizeof(short);
        break;
      }
      case 'c': { // 1 byte as ASCII character [cite: 51]
        char v = *p;
        printf("%c\n", v);
        p += 1;
        break;
      }
      case 's': { // 8-byte pointer to a C string 
        char *sp = *(char **)p;
        printf("%s\n", sp);
        p += sizeof(char *);
        break;
      }
      case 'S': { // Null-terminated C string 
        char *sp = p;
        printf("%s\n", sp);
        return; 
      }
    }
  }
}

2. Setup Instructions

  • Modify Makefile: Add _memdump to the UPROGS list.

Last updated