A more elaborate variant of traceme: tracemefd

Hard

xv6 book Sect 2.3 Kernel organization

xv6 book Sect 2.5 Process overview

Now, we will add a slightly more elaborate variant of traceme: void tracemefd(int tracefd). Instead of printing to the standard output, tracemefd writes the trace message to an open pipe, passed as a file descriptor.

In sys_tracemefd

  • Implement tracemefd as a new system call: the traceme system call from before should continue to work unmodified.
  • When tracemefd is called, we first need to check that the file descriptor tracefd is 1) a valid open file, and 2) a pipe, and 3) is writable. (We give you this part in the skeleton below.)
  • p->ofile contains the list of open files opened by the process p. You can index it with the file descriptor tracefd to access the corresponding file, as shown in the skeleton below.
  • Save tracefd in struct proc.

You can start from the following code skeleton:

#include "file.h" // Defines struct file and FD_PIPE

...

uint64
sys_tracemefd(void)
{
  // Get tracefd argument
  // TODO

  // Validate the file descriptor
  if (tracefd >= NOFILE ||
      !p->ofile[tracefd] ||
      p->ofile[tracefd]->type != FD_PIPE ||
      !p->ofile[tracefd]->writable) {
    p->tracefd = -1;
    return -1;
  }

  // Save fd to proc
  // TODO

  return 0;
}

When a syscall occurs

  • Create a struct tracemsg (see below) that will hold the relevant information to write to the pipe. Think about where to declare this type!
struct tracemsg {
  int pid;
  int syscall;
};
  • When a syscall occurs and tracefd is not -1, write a struct tracemsg to tracefd via pipewrite (set user_src to 0 to indicate that the input is in kernel space). You can get the pipe with p->ofile[p->tracefd]->pipe. The addr argument should point to your struct tracemsg, and n should be set to the size of a struct tracemsg.

Testing

Create a user-space program tracemefd that takes an executable as an argument and calls this executable with the tracemefd functionality enabled.

  • Create a pipe to send struct tracemsg from child to parent
  • Use fork to create a child process:
    • In the child: use tracemefd on one end of the pipe, and use exec (similar to traceme exercise)
    • In the parent: read from the other end of the pipe, and print the received struct tracemsg

This site uses Just the Docs, a documentation theme for Jekyll.