41f6764d445a0c27b2218abffec0bc202f95cf01
[pintos-anon] / solutions / p2.patch
1 Index: src/threads/thread.c
2 diff -u src/threads/thread.c~ src/threads/thread.c
3 --- src/threads/thread.c~
4 +++ src/threads/thread.c
5 @@ -13,6 +13,7 @@
6  #include "threads/synch.h"
7  #ifdef USERPROG
8  #include "userprog/process.h"
9 +#include "userprog/syscall.h"
10  #endif
11  
12  /* Random value for struct thread's `magic' member.
13 @@ -251,18 +252,19 @@ thread_tid (void) 
14  void
15  thread_exit (void) 
16  {
17    ASSERT (!intr_context ());
18  
19  #ifdef USERPROG
20    process_exit ();
21  #endif
22 -
23 +  syscall_exit ();
24 +  
25    /* Remove thread from all threads list, set our status to dying,
26       and schedule another process.  That process will destroy us
27       when it calls thread_schedule_tail(). */
28    intr_disable ();
29    list_remove (&thread_current()->allelem);
30    thread_current ()->status = THREAD_DYING;
31    schedule ();
32    NOT_REACHED ();
33  }
34 @@ -400,6 +404,10 @@ init_thread (struct thread *t, const cha
35    strlcpy (t->name, name, sizeof t->name);
36    t->stack = (uint8_t *) t + PGSIZE;
37    t->priority = priority;
38 +  list_init (&t->children);
39 +  t->wait_status = NULL;
40 +  list_init (&t->fds);
41 +  t->next_handle = 2;
42    t->magic = THREAD_MAGIC;
43  }
44  
45 Index: src/threads/thread.h
46 diff -u src/threads/thread.h~ src/threads/thread.h
47 --- src/threads/thread.h~
48 +++ src/threads/thread.h
49 @@ -4,6 +4,7 @@
50  #include <debug.h>
51  #include <list.h>
52  #include <stdint.h>
53 +#include "threads/synch.h"
54  
55  /* States in a thread's life cycle. */
56  enum thread_status
57 @@ -89,6 +90,10 @@ struct thread
58      uint8_t *stack;                     /* Saved stack pointer. */
59      int priority;                       /* Priority. */
60  
61 +    /* Owned by process.c. */
62 +    struct wait_status *wait_status;    /* This process's completion status. */
63 +    struct list children;               /* Completion status of children. */
64 +
65      /* Shared between thread.c and synch.c. */
66      struct list_elem elem;              /* List element. */
67  
68 @@ -96,11 +102,31 @@ struct thread
69      /* Owned by userprog/process.c. */
70      uint32_t *pagedir;                  /* Page directory. */
71  #endif
72 +    struct file *bin_file;              /* Executable. */
73 +
74 +    /* Owned by syscall.c. */
75 +    struct list fds;                    /* List of file descriptors. */
76 +    int next_handle;                    /* Next handle value. */
77  
78      /* Owned by thread.c. */
79      unsigned magic;                     /* Detects stack overflow. */
80    };
81  
82 +/* Tracks the completion of a process.
83 +   Reference held by both the parent, in its `children' list,
84 +   and by the child, in its `wait_status' pointer. */
85 +struct wait_status
86 +  {
87 +    struct list_elem elem;              /* `children' list element. */
88 +    struct lock lock;                   /* Protects ref_cnt. */
89 +    int ref_cnt;                        /* 2=child and parent both alive,
90 +                                           1=either child or parent alive,
91 +                                           0=child and parent both dead. */
92 +    tid_t tid;                          /* Child thread id. */
93 +    int exit_code;                      /* Child exit code, if dead. */
94 +    struct semaphore dead;              /* 1=child alive, 0=child dead. */
95 +  };
96 +
97  /* If false (default), use round-robin scheduler.
98     If true, use multi-level feedback queue scheduler.
99     Controlled by kernel command-line options "-o mlfqs".
100 Index: src/userprog/exception.c
101 diff -u src/userprog/exception.c~ src/userprog/exception.c
102 --- src/userprog/exception.c~
103 +++ src/userprog/exception.c
104 @@ -150,6 +150,14 @@ page_fault (struct intr_frame *f) 
105    write = (f->error_code & PF_W) != 0;
106    user = (f->error_code & PF_U) != 0;
107  
108 +  /* Handle bad dereferences from system call implementations. */
109 +  if (!user) 
110 +    {
111 +      f->eip = (void (*) (void)) f->eax;
112 +      f->eax = 0;
113 +      return;
114 +    }
115 +
116    /* To implement virtual memory, delete the rest of the function
117       body, and replace it with code that brings in the page to
118       which fault_addr refers. */
119 Index: src/userprog/process.c
120 diff -u src/userprog/process.c~ src/userprog/process.c
121 --- src/userprog/process.c~
122 +++ src/userprog/process.c
123 @@ -14,11 +14,23 @@
124  #include "threads/init.h"
125  #include "threads/interrupt.h"
126 +#include "threads/malloc.h"
127  #include "threads/palloc.h"
128  #include "threads/thread.h"
129  #include "threads/vaddr.h"
130  
131  static thread_func start_process NO_RETURN;
132 -static bool load (const char *cmdline, void (**eip) (void), void **esp);
133 +static bool load (const char *cmd_line, void (**eip) (void), void **esp);
134 +
135 +/* Data structure shared between process_execute() in the
136 +   invoking thread and start_process() in the newly invoked
137 +   thread. */
138 +struct exec_info 
139 +  {
140 +    const char *file_name;              /* Program to load. */
141 +    struct semaphore load_done;         /* "Up"ed when loading complete. */
142 +    struct wait_status *wait_status;    /* Child process. */
143 +    bool success;                       /* Program successfully loaded? */
144 +  };
145  
146  /* Starts a new thread running a user program loaded from
147     FILE_NAME.  The new thread may be scheduled (and may even exit)
148 @@ -27,29 +39,37 @@ static bool load (const char *cmdline, v
149  tid_t
150  process_execute (const char *file_name) 
151  {
152 -  char *fn_copy;
153 +  struct exec_info exec;
154 +  char thread_name[16];
155 +  char *save_ptr;
156    tid_t tid;
157  
158 -  /* Make a copy of FILE_NAME.
159 -     Otherwise there's a race between the caller and load(). */
160 -  fn_copy = palloc_get_page (0);
161 -  if (fn_copy == NULL)
162 -    return TID_ERROR;
163 -  strlcpy (fn_copy, file_name, PGSIZE);
164 +  /* Initialize exec_info. */
165 +  exec.file_name = file_name;
166 +  sema_init (&exec.load_done, 0);
167  
168    /* Create a new thread to execute FILE_NAME. */
169 -  tid = thread_create (file_name, PRI_DEFAULT, start_process, fn_copy);
170 -  if (tid == TID_ERROR)
171 -    palloc_free_page (fn_copy); 
172 +  strlcpy (thread_name, file_name, sizeof thread_name);
173 +  strtok_r (thread_name, " ", &save_ptr);
174 +  tid = thread_create (thread_name, PRI_DEFAULT, start_process, &exec);
175 +  if (tid != TID_ERROR)
176 +    {
177 +      sema_down (&exec.load_done);
178 +      if (exec.success)
179 +        list_push_back (&thread_current ()->children, &exec.wait_status->elem);
180 +      else
181 +        tid = TID_ERROR;
182 +    }
183 +
184    return tid;
185  }
186  
187  /* A thread function that loads a user process and starts it
188     running. */
189  static void
190 -start_process (void *file_name_)
191 +start_process (void *exec_)
192  {
193 -  char *file_name = file_name_;
194 +  struct exec_info *exec = exec_;
195    struct intr_frame if_;
196    bool success;
197  
198 @@ -58,10 +78,29 @@ start_process (void *file_name_)
199    if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
200    if_.cs = SEL_UCSEG;
201    if_.eflags = FLAG_IF | FLAG_MBS;
202 -  success = load (file_name, &if_.eip, &if_.esp);
203 +  success = load (exec->file_name, &if_.eip, &if_.esp);
204 +
205 +  /* Allocate wait_status. */
206 +  if (success)
207 +    {
208 +      exec->wait_status = thread_current ()->wait_status
209 +        = malloc (sizeof *exec->wait_status);
210 +      success = exec->wait_status != NULL; 
211 +    }
212  
213 -  /* If load failed, quit. */
214 -  palloc_free_page (file_name);
215 +  /* Initialize wait_status. */
216 +  if (success) 
217 +    {
218 +      lock_init (&exec->wait_status->lock);
219 +      exec->wait_status->ref_cnt = 2;
220 +      exec->wait_status->tid = thread_current ()->tid;
221 +      exec->wait_status->exit_code = -1;
222 +      sema_init (&exec->wait_status->dead, 0);
223 +    }
224 +  
225 +  /* Notify parent thread and clean up. */
226 +  exec->success = success;
227 +  sema_up (&exec->load_done);
228    if (!success) 
229      thread_exit ();
230  
231 @@ -75,18 +113,47 @@ start_process (void *file_name_)
232    NOT_REACHED ();
233  }
234  
235 +/* Releases one reference to CS and, if it is now unreferenced,
236 +   frees it. */
237 +static void
238 +release_child (struct wait_status *cs) 
239 +{
240 +  int new_ref_cnt;
241 +  
242 +  lock_acquire (&cs->lock);
243 +  new_ref_cnt = --cs->ref_cnt;
244 +  lock_release (&cs->lock);
245 +
246 +  if (new_ref_cnt == 0)
247 +    free (cs);
248 +}
249 +
250  /* Waits for thread TID to die and returns its exit status.  If
251     it was terminated by the kernel (i.e. killed due to an
252     exception), returns -1.  If TID is invalid or if it was not a
253     child of the calling process, or if process_wait() has already
254     been successfully called for the given TID, returns -1
255 -   immediately, without waiting.
256 -
257 -   This function will be implemented in problem 2-2.  For now, it
258 -   does nothing. */
259 +   immediately, without waiting. */
260  int
261 -process_wait (tid_t child_tid UNUSED) 
262 +process_wait (tid_t child_tid) 
263  {
264 +  struct thread *cur = thread_current ();
265 +  struct list_elem *e;
266 +
267 +  for (e = list_begin (&cur->children); e != list_end (&cur->children);
268 +       e = list_next (e)) 
269 +    {
270 +      struct wait_status *cs = list_entry (e, struct wait_status, elem);
271 +      if (cs->tid == child_tid) 
272 +        {
273 +          int exit_code;
274 +          list_remove (e);
275 +          sema_down (&cs->dead);
276 +          exit_code = cs->exit_code;
277 +          release_child (cs);
278 +          return exit_code;
279 +        }
280 +    }
281    return -1;
282  }
283  
284 @@ -95,8 +162,30 @@ void
285  process_exit (void)
286  {
287    struct thread *cur = thread_current ();
288 +  struct list_elem *e, *next;
289    uint32_t *pd;
290  
291 +  /* Close executable (and allow writes). */
292 +  file_close (cur->bin_file);
293 +
294 +  /* Notify parent that we're dead. */
295 +  if (cur->wait_status != NULL) 
296 +    {
297 +      struct wait_status *cs = cur->wait_status;
298 +      printf ("%s: exit(%d)\n", cur->name, cs->exit_code);
299 +      sema_up (&cs->dead);
300 +      release_child (cs);
301 +    }
302 +
303 +  /* Free entries of children list. */
304 +  for (e = list_begin (&cur->children); e != list_end (&cur->children);
305 +       e = next) 
306 +    {
307 +      struct wait_status *cs = list_entry (e, struct wait_status, elem);
308 +      next = list_remove (e);
309 +      release_child (cs);
310 +    }
311 +  
312    /* Destroy the current process's page directory and switch back
313       to the kernel-only page directory. */
314    pd = cur->pagedir;
315 @@ -193,7 +284,7 @@ struct Elf32_Phdr
316  #define PF_W 2          /* Writable. */
317  #define PF_R 4          /* Readable. */
318  
319 -static bool setup_stack (void **esp);
320 +static bool setup_stack (const char *cmd_line, void **esp);
321  static bool validate_segment (const struct Elf32_Phdr *, struct file *);
322  static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
323                            bool writable);
324 @@ -209,13 +300,15 @@ static bool setup_stack (void **esp);
325     and its initial stack pointer into *ESP.
326     Returns true if successful, false otherwise. */
327  bool
328 -load (const char *file_name, void (**eip) (void), void **esp) 
329 +load (const char *cmd_line, void (**eip) (void), void **esp) 
330  {
331    struct thread *t = thread_current ();
332 +  char file_name[NAME_MAX + 2];
333    struct Elf32_Ehdr ehdr;
334    struct file *file = NULL;
335    off_t file_ofs;
336    bool success = false;
337 +  char *cp;
338    int i;
339  
340    /* Allocate and activate page directory. */
341 @@ -224,13 +317,22 @@ load (const char *file_name, void (**eip)
342      goto done;
343    process_activate ();
344  
345 +  /* Extract file_name from command line. */
346 +  while (*cmd_line == ' ')
347 +    cmd_line++;
348 +  strlcpy (file_name, cmd_line, sizeof file_name);
349 +  cp = strchr (file_name, ' ');
350 +  if (cp != NULL)
351 +    *cp = '\0';
352 +
353    /* Open executable file. */
354 -  file = filesys_open (file_name);
355 +  t->bin_file = file = filesys_open (file_name);
356    if (file == NULL) 
357      {
358        printf ("load: %s: open failed\n", file_name);
359        goto done; 
360      }
361 +  file_deny_write (file);
362  
363    /* Read and verify executable header. */
364    if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
365 @@ -284,7 +386,7 @@ load (const char *file_name, void (**eip)
366      }
367  
368    /* Set up stack. */
369 -  if (!setup_stack (esp))
370 +  if (!setup_stack (cmd_line, esp))
371      goto done;
372  
373    /* Start address. */
374 @@ -294,7 +396,6 @@ load (const char *file_name, void (**eip)
375  
376   done:
377    /* We arrive here whether the load is successful or not. */
378 -  file_close (file);
379    return success;
380  }
381  \f
382 @@ -393,10 +494,92 @@ load_segment (struct file *file, const s
383    return true;
384  }
385  
386 -/* Create a minimal stack by mapping a zeroed page at the top of
387 -   user virtual memory. */
388 +/* Reverse the order of the ARGC pointers to char in ARGV. */
389 +static void
390 +reverse (int argc, char **argv) 
391 +{
392 +  for (; argc > 1; argc -= 2, argv++) 
393 +    {
394 +      char *tmp = argv[0];
395 +      argv[0] = argv[argc - 1];
396 +      argv[argc - 1] = tmp;
397 +    }
398 +}
399 +
400 +/* Pushes the SIZE bytes in BUF onto the stack in KPAGE, whose
401 +   page-relative stack pointer is *OFS, and then adjusts *OFS
402 +   appropriately.  The bytes pushed are rounded to a 32-bit
403 +   boundary.
404 +
405 +   If successful, returns a pointer to the newly pushed object.
406 +   On failure, returns a null pointer. */
407 +static void *
408 +push (uint8_t *kpage, size_t *ofs, const void *buf, size_t size) 
409 +{
410 +  size_t padsize = ROUND_UP (size, sizeof (uint32_t));
411 +  if (*ofs < padsize)
412 +    return NULL;
413 +
414 +  *ofs -= padsize;
415 +  memcpy (kpage + *ofs + (padsize - size), buf, size);
416 +  return kpage + *ofs + (padsize - size);
417 +}
418 +
419 +/* Sets up command line arguments in KPAGE, which will be mapped
420 +   to UPAGE in user space.  The command line arguments are taken
421 +   from CMD_LINE, separated by spaces.  Sets *ESP to the initial
422 +   stack pointer for the process. */
423 +static bool
424 +init_cmd_line (uint8_t *kpage, uint8_t *upage, const char *cmd_line,
425 +               void **esp) 
426 +{
427 +  size_t ofs = PGSIZE;
428 +  char *const null = NULL;
429 +  char *cmd_line_copy;
430 +  char *karg, *saveptr;
431 +  int argc;
432 +  char **argv;
433 +
434 +  /* Push command line string. */
435 +  cmd_line_copy = push (kpage, &ofs, cmd_line, strlen (cmd_line) + 1);
436 +  if (cmd_line_copy == NULL)
437 +    return false;
438 +
439 +  if (push (kpage, &ofs, &null, sizeof null) == NULL)
440 +    return false;
441 +
442 +  /* Parse command line into arguments
443 +     and push them in reverse order. */
444 +  argc = 0;
445 +  for (karg = strtok_r (cmd_line_copy, " ", &saveptr); karg != NULL;
446 +       karg = strtok_r (NULL, " ", &saveptr))
447 +    {
448 +      void *uarg = upage + (karg - (char *) kpage);
449 +      if (push (kpage, &ofs, &uarg, sizeof uarg) == NULL)
450 +        return false;
451 +      argc++;
452 +    }
453 +
454 +  /* Reverse the order of the command line arguments. */
455 +  argv = (char **) (upage + ofs);
456 +  reverse (argc, (char **) (kpage + ofs));
457 +
458 +  /* Push argv, argc, "return address". */
459 +  if (push (kpage, &ofs, &argv, sizeof argv) == NULL
460 +      || push (kpage, &ofs, &argc, sizeof argc) == NULL
461 +      || push (kpage, &ofs, &null, sizeof null) == NULL)
462 +    return false;
463 +
464 +  /* Set initial stack pointer. */
465 +  *esp = upage + ofs;
466 +  return true;
467 +}
468 +
469 +/* Create a minimal stack for T by mapping a page at the
470 +   top of user virtual memory.  Fills in the page using CMD_LINE
471 +   and sets *ESP to the stack pointer. */
472  static bool
473 -setup_stack (void **esp) 
474 +setup_stack (const char *cmd_line, void **esp) 
475  {
476    uint8_t *kpage;
477    bool success = false;
478 @@ -404,9 +587,9 @@ setup_stack (void **esp) 
479    kpage = palloc_get_page (PAL_USER | PAL_ZERO);
480    if (kpage != NULL) 
481      {
482 -      success = install_page (((uint8_t *) PHYS_BASE) - PGSIZE, kpage, true);
483 -      if (success)
484 -        *esp = PHYS_BASE;
485 +      uint8_t *upage = ((uint8_t *) PHYS_BASE) - PGSIZE;
486 +      if (install_page (upage, kpage, true))
487 +        success = init_cmd_line (kpage, upage, cmd_line, esp);
488        else
489          palloc_free_page (kpage);
490      }
491 Index: src/userprog/syscall.c
492 diff -u src/userprog/syscall.c~ src/userprog/syscall.c
493 --- src/userprog/syscall.c~
494 +++ src/userprog/syscall.c
495 @@ -1,20 +1,486 @@
496  #include "userprog/syscall.h"
497  #include <stdio.h>
498 +#include <string.h>
499  #include <syscall-nr.h>
500 +#include "userprog/process.h"
501 +#include "userprog/pagedir.h"
502 +#include "devices/input.h"
503 +#include "devices/shutdown.h"
504 +#include "filesys/filesys.h"
505 +#include "filesys/file.h"
506  #include "threads/interrupt.h"
507 +#include "threads/malloc.h"
508 +#include "threads/palloc.h"
509  #include "threads/thread.h"
510 +#include "threads/vaddr.h"
511 -
512
513
514 +static int sys_halt (void);
515 +static int sys_exit (int status);
516 +static int sys_exec (const char *ufile);
517 +static int sys_wait (tid_t);
518 +static int sys_create (const char *ufile, unsigned initial_size);
519 +static int sys_remove (const char *ufile);
520 +static int sys_open (const char *ufile);
521 +static int sys_filesize (int handle);
522 +static int sys_read (int handle, void *udst_, unsigned size);
523 +static int sys_write (int handle, void *usrc_, unsigned size);
524 +static int sys_seek (int handle, unsigned position);
525 +static int sys_tell (int handle);
526 +static int sys_close (int handle);
527
528  static void syscall_handler (struct intr_frame *);
529 -
530 +static void copy_in (void *, const void *, size_t);
531
532 +/* Serializes file system operations. */
533 +static struct lock fs_lock;
534
535  void
536  syscall_init (void) 
537  {
538    intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
539 +  lock_init (&fs_lock);
540  }
541
542 +/* System call handler. */
543 +static void
544 +syscall_handler (struct intr_frame *f) 
545 +{
546 +  typedef int syscall_function (int, int, int);
547 +
548 +  /* A system call. */
549 +  struct syscall 
550 +    {
551 +      size_t arg_cnt;           /* Number of arguments. */
552 +      syscall_function *func;   /* Implementation. */
553 +    };
554 +
555 +  /* Table of system calls. */
556 +  static const struct syscall syscall_table[] =
557 +    {
558 +      {0, (syscall_function *) sys_halt},
559 +      {1, (syscall_function *) sys_exit},
560 +      {1, (syscall_function *) sys_exec},
561 +      {1, (syscall_function *) sys_wait},
562 +      {2, (syscall_function *) sys_create},
563 +      {1, (syscall_function *) sys_remove},
564 +      {1, (syscall_function *) sys_open},
565 +      {1, (syscall_function *) sys_filesize},
566 +      {3, (syscall_function *) sys_read},
567 +      {3, (syscall_function *) sys_write},
568 +      {2, (syscall_function *) sys_seek},
569 +      {1, (syscall_function *) sys_tell},
570 +      {1, (syscall_function *) sys_close},
571 +    };
572 +
573 +  const struct syscall *sc;
574 +  unsigned call_nr;
575 +  int args[3];
576 +
577 +  /* Get the system call. */
578 +  copy_in (&call_nr, f->esp, sizeof call_nr);
579 +  if (call_nr >= sizeof syscall_table / sizeof *syscall_table)
580 +    thread_exit ();
581 +  sc = syscall_table + call_nr;
582  
583 +  /* Get the system call arguments. */
584 +  ASSERT (sc->arg_cnt <= sizeof args / sizeof *args);
585 +  memset (args, 0, sizeof args);
586 +  copy_in (args, (uint32_t *) f->esp + 1, sizeof *args * sc->arg_cnt);
587 +
588 +  /* Execute the system call,
589 +     and set the return value. */
590 +  f->eax = sc->func (args[0], args[1], args[2]);
591 +}
592
593 +/* Returns true if UADDR is a valid, mapped user address,
594 +   false otherwise. */
595 +static bool
596 +verify_user (const void *uaddr) 
597 +{
598 +  return (uaddr < PHYS_BASE
599 +          && pagedir_get_page (thread_current ()->pagedir, uaddr) != NULL);
600 +}
601
602 +/* Copies a byte from user address USRC to kernel address DST.
603 +   USRC must be below PHYS_BASE.
604 +   Returns true if successful, false if a segfault occurred. */
605 +static inline bool
606 +get_user (uint8_t *dst, const uint8_t *usrc)
607 +{
608 +  int eax;
609 +  asm ("movl $1f, %%eax; movb %2, %%al; movb %%al, %0; 1:"
610 +       : "=m" (*dst), "=&a" (eax) : "m" (*usrc));
611 +  return eax != 0;
612 +}
613
614 +/* Writes BYTE to user address UDST.
615 +   UDST must be below PHYS_BASE.
616 +   Returns true if successful, false if a segfault occurred. */
617 +static inline bool
618 +put_user (uint8_t *udst, uint8_t byte)
619 +{
620 +  int eax;
621 +  asm ("movl $1f, %%eax; movb %b2, %0; 1:"
622 +       : "=m" (*udst), "=&a" (eax) : "q" (byte));
623 +  return eax != 0;
624 +}
625
626 +/* Copies SIZE bytes from user address USRC to kernel address
627 +   DST.
628 +   Call thread_exit() if any of the user accesses are invalid. */
629  static void
630 -syscall_handler (struct intr_frame *f UNUSED) 
631 +copy_in (void *dst_, const void *usrc_, size_t size) 
632 +{
633 +  uint8_t *dst = dst_;
634 +  const uint8_t *usrc = usrc_;
635
636 +  for (; size > 0; size--, dst++, usrc++) 
637 +    if (usrc >= (uint8_t *) PHYS_BASE || !get_user (dst, usrc)) 
638 +      thread_exit ();
639 +}
640
641 +/* Creates a copy of user string US in kernel memory
642 +   and returns it as a page that must be freed with
643 +   palloc_free_page().
644 +   Truncates the string at PGSIZE bytes in size.
645 +   Call thread_exit() if any of the user accesses are invalid. */
646 +static char *
647 +copy_in_string (const char *us) 
648 +{
649 +  char *ks;
650 +  size_t length;
651
652 +  ks = palloc_get_page (0);
653 +  if (ks == NULL) 
654 +    thread_exit ();
655
656 +  for (length = 0; length < PGSIZE; length++)
657 +    {
658 +      if (us >= (char *) PHYS_BASE || !get_user (ks + length, us++)) 
659 +        {
660 +          palloc_free_page (ks);
661 +          thread_exit (); 
662 +        }
663 +       
664 +      if (ks[length] == '\0')
665 +        return ks;
666 +    }
667 +  ks[PGSIZE - 1] = '\0';
668 +  return ks;
669 +}
670
671 +/* Halt system call. */
672 +static int
673 +sys_halt (void)
674 +{
675 +  shutdown_power_off ();
676 +}
677
678 +/* Exit system call. */
679 +static int
680 +sys_exit (int exit_code) 
681 +{
682 +  thread_current ()->wait_status->exit_code = exit_code;
683 +  thread_exit ();
684 +  NOT_REACHED ();
685 +}
686
687 +/* Exec system call. */
688 +static int
689 +sys_exec (const char *ufile) 
690 +{
691 +  tid_t tid;
692 +  char *kfile = copy_in_string (ufile);
693
694 +  lock_acquire (&fs_lock);
695 +  tid = process_execute (kfile);
696 +  lock_release (&fs_lock);
697
698 +  palloc_free_page (kfile);
699
700 +  return tid;
701 +}
702
703 +/* Wait system call. */
704 +static int
705 +sys_wait (tid_t child) 
706 +{
707 +  return process_wait (child);
708 +}
709
710 +/* Create system call. */
711 +static int
712 +sys_create (const char *ufile, unsigned initial_size) 
713 +{
714 +  char *kfile = copy_in_string (ufile);
715 +  bool ok;
716 +   
717 +  lock_acquire (&fs_lock);
718 +  ok = filesys_create (kfile, initial_size);
719 +  lock_release (&fs_lock);
720
721 +  palloc_free_page (kfile);
722
723 +  return ok;
724 +}
725
726 +/* Remove system call. */
727 +static int
728 +sys_remove (const char *ufile) 
729  {
730 -  printf ("system call!\n");
731 +  char *kfile = copy_in_string (ufile);
732 +  bool ok;
733 +   
734 +  lock_acquire (&fs_lock);
735 +  ok = filesys_remove (kfile);
736 +  lock_release (&fs_lock);
737
738 +  palloc_free_page (kfile);
739
740 +  return ok;
741 +}
742
743 +/* A file descriptor, for binding a file handle to a file. */
744 +struct file_descriptor
745 +  {
746 +    struct list_elem elem;      /* List element. */
747 +    struct file *file;          /* File. */
748 +    int handle;                 /* File handle. */
749 +  };
750
751 +/* Open system call. */
752 +static int
753 +sys_open (const char *ufile) 
754 +{
755 +  char *kfile = copy_in_string (ufile);
756 +  struct file_descriptor *fd;
757 +  int handle = -1;
758
759 +  fd = malloc (sizeof *fd);
760 +  if (fd != NULL)
761 +    {
762 +      lock_acquire (&fs_lock);
763 +      fd->file = filesys_open (kfile);
764 +      if (fd->file != NULL)
765 +        {
766 +          struct thread *cur = thread_current ();
767 +          handle = fd->handle = cur->next_handle++;
768 +          list_push_front (&cur->fds, &fd->elem);
769 +        }
770 +      else 
771 +        free (fd);
772 +      lock_release (&fs_lock);
773 +    }
774 +  
775 +  palloc_free_page (kfile);
776 +  return handle;
777 +}
778
779 +/* Returns the file descriptor associated with the given handle.
780 +   Terminates the process if HANDLE is not associated with an
781 +   open file. */
782 +static struct file_descriptor *
783 +lookup_fd (int handle) 
784 +{
785 +  struct thread *cur = thread_current ();
786 +  struct list_elem *e;
787 +   
788 +  for (e = list_begin (&cur->fds); e != list_end (&cur->fds);
789 +       e = list_next (e))
790 +    {
791 +      struct file_descriptor *fd;
792 +      fd = list_entry (e, struct file_descriptor, elem);
793 +      if (fd->handle == handle)
794 +        return fd;
795 +    }
796
797    thread_exit ();
798  }
799
800 +/* Filesize system call. */
801 +static int
802 +sys_filesize (int handle) 
803 +{
804 +  struct file_descriptor *fd = lookup_fd (handle);
805 +  int size;
806
807 +  lock_acquire (&fs_lock);
808 +  size = file_length (fd->file);
809 +  lock_release (&fs_lock);
810
811 +  return size;
812 +}
813
814 +/* Read system call. */
815 +static int
816 +sys_read (int handle, void *udst_, unsigned size) 
817 +{
818 +  uint8_t *udst = udst_;
819 +  struct file_descriptor *fd;
820 +  int bytes_read = 0;
821 +
822 +  /* Handle keyboard reads. */
823 +  if (handle == STDIN_FILENO) 
824 +    {
825 +      for (bytes_read = 0; (size_t) bytes_read < size; bytes_read++)
826 +        if (udst >= (uint8_t *) PHYS_BASE || !put_user (udst++, input_getc ()))
827 +          thread_exit ();
828 +      return bytes_read;
829 +    }
830 +
831 +  /* Handle all other reads. */
832 +  fd = lookup_fd (handle);
833 +  lock_acquire (&fs_lock);
834 +  while (size > 0) 
835 +    {
836 +      /* How much to read into this page? */
837 +      size_t page_left = PGSIZE - pg_ofs (udst);
838 +      size_t read_amt = size < page_left ? size : page_left;
839 +      off_t retval;
840 +
841 +      /* Check that touching this page is okay. */
842 +      if (!verify_user (udst)) 
843 +        {
844 +          lock_release (&fs_lock);
845 +          thread_exit ();
846 +        }
847 +
848 +      /* Read from file into page. */
849 +      retval = file_read (fd->file, udst, read_amt);
850 +      if (retval < 0)
851 +        {
852 +          if (bytes_read == 0)
853 +            bytes_read = -1; 
854 +          break;
855 +        }
856 +      bytes_read += retval;
857 +
858 +      /* If it was a short read we're done. */
859 +      if (retval != (off_t) read_amt)
860 +        break;
861 +
862 +      /* Advance. */
863 +      udst += retval;
864 +      size -= retval;
865 +    }
866 +  lock_release (&fs_lock);
867 +   
868 +  return bytes_read;
869 +}
870
871 +/* Write system call. */
872 +static int
873 +sys_write (int handle, void *usrc_, unsigned size) 
874 +{
875 +  uint8_t *usrc = usrc_;
876 +  struct file_descriptor *fd = NULL;
877 +  int bytes_written = 0;
878 +
879 +  /* Lookup up file descriptor. */
880 +  if (handle != STDOUT_FILENO)
881 +    fd = lookup_fd (handle);
882 +
883 +  lock_acquire (&fs_lock);
884 +  while (size > 0) 
885 +    {
886 +      /* How much bytes to write to this page? */
887 +      size_t page_left = PGSIZE - pg_ofs (usrc);
888 +      size_t write_amt = size < page_left ? size : page_left;
889 +      off_t retval;
890 +
891 +      /* Check that we can touch this user page. */
892 +      if (!verify_user (usrc)) 
893 +        {
894 +          lock_release (&fs_lock);
895 +          thread_exit ();
896 +        }
897 +
898 +      /* Do the write. */
899 +      if (handle == STDOUT_FILENO)
900 +        {
901 +          putbuf (usrc, write_amt);
902 +          retval = write_amt;
903 +        }
904 +      else
905 +        retval = file_write (fd->file, usrc, write_amt);
906 +      if (retval < 0) 
907 +        {
908 +          if (bytes_written == 0)
909 +            bytes_written = -1;
910 +          break;
911 +        }
912 +      bytes_written += retval;
913 +
914 +      /* If it was a short write we're done. */
915 +      if (retval != (off_t) write_amt)
916 +        break;
917 +
918 +      /* Advance. */
919 +      usrc += retval;
920 +      size -= retval;
921 +    }
922 +  lock_release (&fs_lock);
923
924 +  return bytes_written;
925 +}
926
927 +/* Seek system call. */
928 +static int
929 +sys_seek (int handle, unsigned position) 
930 +{
931 +  struct file_descriptor *fd = lookup_fd (handle);
932 +   
933 +  lock_acquire (&fs_lock);
934 +  if ((off_t) position >= 0)
935 +    file_seek (fd->file, position);
936 +  lock_release (&fs_lock);
937
938 +  return 0;
939 +}
940
941 +/* Tell system call. */
942 +static int
943 +sys_tell (int handle) 
944 +{
945 +  struct file_descriptor *fd = lookup_fd (handle);
946 +  unsigned position;
947 +   
948 +  lock_acquire (&fs_lock);
949 +  position = file_tell (fd->file);
950 +  lock_release (&fs_lock);
951
952 +  return position;
953 +}
954
955 +/* Close system call. */
956 +static int
957 +sys_close (int handle) 
958 +{
959 +  struct file_descriptor *fd = lookup_fd (handle);
960 +  lock_acquire (&fs_lock);
961 +  file_close (fd->file);
962 +  lock_release (&fs_lock);
963 +  list_remove (&fd->elem);
964 +  free (fd);
965 +  return 0;
966 +}
967
968 +/* On thread exit, close all open files. */
969 +void
970 +syscall_exit (void) 
971 +{
972 +  struct thread *cur = thread_current ();
973 +  struct list_elem *e, *next;
974 +   
975 +  for (e = list_begin (&cur->fds); e != list_end (&cur->fds); e = next)
976 +    {
977 +      struct file_descriptor *fd;
978 +      fd = list_entry (e, struct file_descriptor, elem);
979 +      next = list_next (e);
980 +      lock_acquire (&fs_lock);
981 +      file_close (fd->file);
982 +      lock_release (&fs_lock);
983 +      free (fd);
984 +    }
985 +}
986 Index: src/userprog/syscall.h
987 diff -u src/userprog/syscall.h~ src/userprog/syscall.h
988 --- src/userprog/syscall.h~
989 +++ src/userprog/syscall.h
990 @@ -2,5 +2,6 @@
991  #define USERPROG_SYSCALL_H
992  
993  void syscall_init (void);
994 +void syscall_exit (void);
995  
996  #endif /* userprog/syscall.h */