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