added btthreadall to dump all threads
[pintos-anon] / doc / userprog.texi
1 @node Project 2--User Programs
2 @chapter Project 2: User Programs
3
4 Now that you've worked with Pintos and are becoming familiar with its
5 infrastructure and thread package, it's time to start working on the
6 parts of the system that allow running user programs.
7 The base code already supports loading and
8 running user programs, but no I/O or interactivity
9 is possible.  In this project, you will enable programs to interact with
10 the OS via system calls.
11
12 You will be working out of the @file{userprog} directory for this
13 assignment, but you will also be interacting with almost every
14 other part of Pintos.  We will describe the
15 relevant parts below.
16
17 You can build project 2 on top of your project 1 submission or you can
18 start fresh.  No code from project 1 is required for this
19 assignment.  The ``alarm clock'' functionality may be useful in
20 projects 3 and 4, but it is not strictly required.
21
22 You might find it useful to go back and reread how to run the tests
23 (@pxref{Testing}).
24
25 @menu
26 * Project 2 Background::        
27 * Project 2 Suggested Order of Implementation::  
28 * Project 2 Requirements::      
29 * Project 2 FAQ::               
30 * 80x86 Calling Convention::    
31 @end menu
32
33 @node Project 2 Background
34 @section Background
35
36 Up to now, all of the code you have run under Pintos has been part
37 of the operating system kernel.  This means, for example, that all the
38 test code from the last assignment ran as part of the kernel, with
39 full access to privileged parts of the system.  Once we start running
40 user programs on top of the operating system, this is no longer true.
41 This project deals with the consequences.
42
43 We allow more than one process to run at a time.  Each process has one
44 thread (multithreaded processes are not supported).  User programs are
45 written under the illusion that they have the entire machine.  This
46 means that when you load and run multiple processes at a time, you must
47 manage memory, scheduling, and other state correctly to maintain this
48 illusion.
49
50 In the previous project, we compiled our test code directly into your
51 kernel, so we had to require certain specific function interfaces within
52 the kernel.  From now on, we will test your operating system by running
53 user programs.  This gives you much greater freedom.  You must make sure
54 that the user program interface meets the specifications described here,
55 but given that constraint you are free to restructure or rewrite kernel
56 code however you wish.
57
58 @menu
59 * Project 2 Source Files::      
60 * Using the File System::       
61 * How User Programs Work::      
62 * Virtual Memory Layout::       
63 * Accessing User Memory::       
64 @end menu
65
66 @node Project 2 Source Files
67 @subsection Source Files
68
69 The easiest way to get an overview of the programming you will be
70 doing is to simply go over each part you'll be working with.  In
71 @file{userprog}, you'll find a small number of files, but here is
72 where the bulk of your work will be:
73
74 @table @file
75 @item process.c
76 @itemx process.h
77 Loads ELF binaries and starts processes.
78
79 @item pagedir.c
80 @itemx pagedir.h
81 A simple manager for 80@var{x}86 hardware page tables.
82 Although you probably won't want to modify this code for this project,
83 you may want to call some of its functions.
84 @xref{Page Tables}, for more information.
85
86 @item syscall.c
87 @itemx syscall.h
88 Whenever a user process wants to access some kernel functionality, it
89 invokes a system call.  This is a skeleton system call
90 handler.  Currently, it just prints a message and terminates the user
91 process.  In part 2 of this project you will add code to do everything
92 else needed by system calls.
93
94 @item exception.c
95 @itemx exception.h
96 When a user process performs a privileged or prohibited operation, it
97 traps into the kernel as an ``exception'' or ``fault.''@footnote{We
98 will treat these terms as synonyms.  There is no standard
99 distinction between them, although Intel processor manuals make 
100 a minor distinction between them on 80@var{x}86.}  These files handle
101 exceptions.  Currently all exceptions simply print a message and
102 terminate the process.  Some, but not all, solutions to project 2
103 require modifying @func{page_fault} in this file.
104
105 @item gdt.c
106 @itemx gdt.h
107 The 80@var{x}86 is a segmented architecture.  The Global Descriptor
108 Table (GDT) is a table that describes the segments in use.  These
109 files set up the GDT.  You should not need to modify these
110 files for any of the projects.  You can read the code if
111 you're interested in how the GDT works.
112
113 @item tss.c
114 @itemx tss.h
115 The Task-State Segment (TSS) is used for 80@var{x}86 architectural
116 task switching.  Pintos uses the TSS only for switching stacks when a
117 user process enters an interrupt handler, as does Linux.  You
118 should not need to modify these files for any of the projects.
119 You can read the code if you're interested in how the TSS
120 works.
121 @end table
122
123 @node Using the File System
124 @subsection Using the File System
125
126 You will need to interface to the file system code for this project,
127 because
128 user programs are loaded from the file system and many of the
129 system calls you must implement deal with the file system.  However,
130 the focus of this project is not the file system, so we have
131 provided a simple but complete file system in the @file{filesys}
132 directory.  You
133 will want to look over the @file{filesys.h} and @file{file.h}
134 interfaces to understand how to use the file system, and especially
135 its many limitations.
136
137 There is no need to modify the file system code for this project, and so
138 we recommend that you do not.  Working on the file system is likely to
139 distract you from this project's focus.
140
141 Proper use of the file system routines now
142 will make life much easier for project 4, when you improve the file
143 system implementation.  Until then, you will have to tolerate the
144 following limitations:
145
146 @itemize @bullet
147 @item
148 No internal synchronization.  Concurrent accesses will interfere with one
149 another.  You should use synchronization to ensure that only one process at a
150 time is executing file system code.
151
152 @item
153 File size is fixed at creation time.  The root directory is
154 represented as a file, so the number of files that may be created is also
155 limited.
156
157 @item
158 File data is allocated as a single extent, that is, data in a single
159 file must occupy a contiguous range of sectors on disk.  External
160 fragmentation can therefore become a serious problem as a file system is
161 used over time.
162
163 @item
164 No subdirectories.
165
166 @item
167 File names are limited to 14 characters.
168
169 @item
170 A system crash mid-operation may corrupt the disk in a way
171 that cannot be repaired automatically.  There is no file system repair
172 tool anyway.
173 @end itemize
174
175 One important feature is included:
176
177 @itemize @bullet
178 @item
179 Unix-like semantics for @func{filesys_remove} are implemented.
180 That is, if a file is open when it is removed, its blocks
181 are not deallocated and it may still be accessed by any
182 threads that have it open, until the last one closes it.  @xref{Removing
183 an Open File}, for more information.
184 @end itemize
185
186 You need to be able to create a simulated disk with a file system
187 partition.  The @command{pintos-mkdisk} program provides this
188 functionality.  From the @file{userprog/build} directory, execute
189 @code{pintos-mkdisk filesys.dsk --filesys-size=2}.  This command
190 creates a simulated disk named @file{filesys.dsk} that contains a @w{2
191 MB} Pintos file system partition.  Then format the file system
192 partition by passing @option{-f -q} on the kernel's command line:
193 @code{pintos -f -q}.  The @option{-f} option causes the file system to
194 be formatted, and @option{-q} causes Pintos to exit as soon as the
195 format is done.
196
197 You'll need a way to copy files in and out of the simulated file system.
198 The @code{pintos} @option{-p} (``put'') and @option{-g} (``get'')
199 options do this.  To copy @file{@var{file}} into the
200 Pintos file system, use the command @file{pintos -p @var{file} -- -q}.
201 (The @samp{--} is needed because @option{-p} is for the @command{pintos}
202 script, not for the simulated kernel.)  To copy it to the Pintos file
203 system under the name @file{@var{newname}}, add @option{-a
204 @var{newname}}: @file{pintos -p @var{file} -a @var{newname} -- -q}.  The
205 commands for copying files out of a VM are similar, but substitute
206 @option{-g} for @option{-p}.
207
208 Incidentally, these commands work by passing special commands
209 @command{extract} and @command{append} on the kernel's command line and copying
210 to and from a special simulated ``scratch'' partition.  If you're very
211 curious, you can look at the @command{pintos} script as well as
212 @file{filesys/fsutil.c} to learn the implementation details.
213
214 Here's a summary of how to create a disk with a file system partition,
215 format the file system, copy the @command{echo} program into the new
216 disk, and then run @command{echo}, passing argument @code{x}.
217 (Argument passing won't work until you implemented it.)  It assumes
218 that you've already built the examples in @file{examples} and that the
219 current directory is @file{userprog/build}:
220
221 @example
222 pintos-mkdisk filesys.dsk --filesys-size=2
223 pintos -f -q
224 pintos -p ../../examples/echo -a echo -- -q
225 pintos -q run 'echo x'
226 @end example
227
228 The three final steps can actually be combined into a single command:
229
230 @example
231 pintos-mkdisk filesys.dsk --filesys-size=2
232 pintos -p ../../examples/echo -a echo -- -f -q run 'echo x'
233 @end example
234
235 If you don't want to keep the file system disk around for later use or
236 inspection, you can even combine all four steps into a single command.
237 The @code{--filesys-size=@var{n}} option creates a temporary file
238 system partition
239 approximately @var{n} megabytes in size just for the duration of the
240 @command{pintos} run.  The Pintos automatic test suite makes extensive
241 use of this syntax:
242
243 @example
244 pintos --filesys-size=2 -p ../../examples/echo -a echo -- -f -q run 'echo x'
245 @end example
246
247 You can delete a file from the Pintos file system using the @code{rm
248 @var{file}} kernel action, e.g.@: @code{pintos -q rm @var{file}}.  Also,
249 @command{ls} lists the files in the file system and @code{cat
250 @var{file}} prints a file's contents to the display.
251
252 @node How User Programs Work
253 @subsection How User Programs Work
254
255 Pintos can run normal C programs, as long as they fit into memory and use
256 only the system calls you implement.  Notably, @func{malloc} cannot be
257 implemented because none of the system calls required for this project
258 allow for memory allocation.  Pintos also can't run programs that use
259 floating point operations, since the kernel doesn't save and restore the
260 processor's floating-point unit when switching threads.
261
262 The @file{src/examples} directory contains a few sample user
263 programs.  The @file{Makefile} in this directory
264 compiles the provided examples, and you can edit it
265 compile your own programs as well.  Some of the example programs will
266 only work once projects 3 or 4 have been implemented.
267
268 Pintos can load @dfn{ELF} executables with the loader provided for you
269 in @file{userprog/process.c}.  ELF is a file format used by Linux,
270 Solaris, and many other operating systems for object files,
271 shared libraries, and executables.  You can actually use any compiler
272 and linker that output 80@var{x}86 ELF executables to produce programs
273 for Pintos.  (We've provided compilers and linkers that should do just
274 fine.)
275
276 You should realize immediately that, until you copy a
277 test program to the simulated file system, Pintos will be unable to do
278 useful work.  You won't be able to do
279 interesting things until you copy a variety of programs to the file system.
280 You might want to create a clean reference file system disk and copy that
281 over whenever you trash your @file{filesys.dsk} beyond a useful state,
282 which may happen occasionally while debugging.
283
284 @node Virtual Memory Layout
285 @subsection Virtual Memory Layout
286
287 Virtual memory in Pintos is divided into two regions: user virtual
288 memory and kernel virtual memory.  User virtual memory ranges from
289 virtual address 0 up to @code{PHYS_BASE}, which is defined in
290 @file{threads/vaddr.h} and defaults to @t{0xc0000000} (3 GB).  Kernel
291 virtual memory occupies the rest of the virtual address space, from
292 @code{PHYS_BASE} up to 4 GB.
293
294 User virtual memory is per-process.
295 When the kernel switches from one process to another, it
296 also switches user virtual address spaces by changing the processor's
297 page directory base register (see @func{pagedir_activate} in
298 @file{userprog/pagedir.c}).  @struct{thread} contains a pointer to a
299 process's page table.
300
301 Kernel virtual memory is global.  It is always mapped the same way,
302 regardless of what user process or kernel thread is running.  In
303 Pintos, kernel virtual memory is mapped one-to-one to physical
304 memory, starting at @code{PHYS_BASE}.  That is, virtual address
305 @code{PHYS_BASE} accesses physical
306 address 0, virtual address @code{PHYS_BASE} + @t{0x1234} accesses
307 physical address @t{0x1234}, and so on up to the size of the machine's
308 physical memory.
309
310 A user program can only access its own user virtual memory.  An attempt to
311 access kernel virtual memory causes a page fault, handled by
312 @func{page_fault} in @file{userprog/exception.c}, and the process
313 will be terminated.  Kernel threads can access both kernel virtual
314 memory and, if a user process is running, the user virtual memory of
315 the running process.  However, even in the kernel, an attempt to
316 access memory at an unmapped user virtual address
317 will cause a page fault.
318
319 @menu
320 * Typical Memory Layout::       
321 @end menu
322
323 @node Typical Memory Layout
324 @subsubsection Typical Memory Layout
325
326 Conceptually, each process is
327 free to lay out its own user virtual memory however it
328 chooses.  In practice, user virtual memory is laid out like this:
329
330 @html
331 <CENTER>
332 @end html
333 @example
334 @group
335    PHYS_BASE +----------------------------------+
336              |            user stack            |
337              |                 |                |
338              |                 |                |
339              |                 V                |
340              |          grows downward          |
341              |                                  |
342              |                                  |
343              |                                  |
344              |                                  |
345              |           grows upward           |
346              |                 ^                |
347              |                 |                |
348              |                 |                |
349              +----------------------------------+
350              | uninitialized data segment (BSS) |
351              +----------------------------------+
352              |     initialized data segment     |
353              +----------------------------------+
354              |           code segment           |
355   0x08048000 +----------------------------------+
356              |                                  |
357              |                                  |
358              |                                  |
359              |                                  |
360              |                                  |
361            0 +----------------------------------+
362 @end group
363 @end example
364 @html
365 </CENTER>
366 @end html
367
368 In this project, the user stack is fixed in size, but in project 3 it
369 will be allowed to grow.  Traditionally, the size of the uninitialized
370 data segment can be adjusted with a system call, but you will not have
371 to implement this.
372
373 The code segment in Pintos starts at user virtual address
374 @t{0x08084000}, approximately 128 MB from the bottom of the address
375 space.  This value is specified in @bibref{SysV-i386} and has no deep
376 significance.
377
378 The linker sets the layout of a user program in memory, as directed by a
379 ``linker script'' that tells it the names and locations of the various
380 program segments.  You can learn more about linker scripts by reading
381 the ``Scripts'' chapter in the linker manual, accessible via @samp{info
382 ld}.
383
384 To view the layout of a particular executable, run @command{objdump}
385 (80@var{x}86) or @command{i386-elf-objdump} (SPARC) with the @option{-p}
386 option.
387
388 @node Accessing User Memory
389 @subsection Accessing User Memory
390
391 As part of a system
392 call, the kernel must often access memory through pointers provided by a user
393 program.  The kernel must be very careful about doing so, because
394 the user can pass a null pointer, a pointer to
395 unmapped virtual memory, or a pointer to kernel virtual address space
396 (above @code{PHYS_BASE}).  All of these types of invalid pointers must
397 be rejected without harm to the kernel or other running processes, by
398 terminating the offending process and freeing its resources.
399
400 There are at least two reasonable ways to do this correctly.  The
401 first method is to verify
402 the validity of a user-provided pointer, then dereference it.  If you
403 choose this route, you'll want to look at the functions in
404 @file{userprog/pagedir.c} and in @file{threads/vaddr.h}.  This is the
405 simplest way to handle user memory access.
406
407 The second method is to check only that a user
408 pointer points below @code{PHYS_BASE}, then dereference it.
409 An invalid user pointer will cause a ``page fault'' that you can
410 handle by modifying the code for @func{page_fault} in
411 @file{userprog/exception.c}.  This technique is normally faster
412 because it takes advantage of the processor's MMU, so it tends to be
413 used in real kernels (including Linux).
414
415 In either case, you need to make sure not to ``leak'' resources.  For
416 example, suppose that your system call has acquired a lock or
417 allocated memory with @func{malloc}.  If you encounter an invalid user pointer
418 afterward, you must still be sure to release the lock or free the page
419 of memory.  If you choose to verify user pointers before dereferencing
420 them, this should be straightforward.  It's more difficult to handle
421 if an invalid pointer causes a page fault,
422 because there's no way to return an error code from a memory access.
423 Therefore, for those who want to try the latter technique, we'll
424 provide a little bit of helpful code:
425
426 @verbatim
427 /* Reads a byte at user virtual address UADDR.
428    UADDR must be below PHYS_BASE.
429    Returns the byte value if successful, -1 if a segfault
430    occurred. */
431 static int
432 get_user (const uint8_t *uaddr)
433 {
434   int result;
435   asm ("movl $1f, %0; movzbl %1, %0; 1:"
436        : "=&a" (result) : "m" (*uaddr));
437   return result;
438 }
439  
440 /* Writes BYTE to user address UDST.
441    UDST must be below PHYS_BASE.
442    Returns true if successful, false if a segfault occurred. */
443 static bool
444 put_user (uint8_t *udst, uint8_t byte)
445 {
446   int error_code;
447   asm ("movl $1f, %0; movb %b2, %1; 1:"
448        : "=&a" (error_code), "=m" (*udst) : "q" (byte));
449   return error_code != -1;
450 }
451 @end verbatim
452
453 Each of these functions assumes that the user address has already been
454 verified to be below @code{PHYS_BASE}.  They also assume that you've
455 modified @func{page_fault} so that a page fault in the kernel merely
456 sets @code{eax} to @t{0xffffffff} and copies its former value
457 into @code{eip}.
458
459 @node Project 2 Suggested Order of Implementation
460 @section Suggested Order of Implementation
461
462 We suggest first implementing the following, which can happen in
463 parallel:
464
465 @itemize
466 @item
467 Argument passing (@pxref{Argument Passing}).  Every user program will
468 page fault immediately until argument passing is implemented.
469
470 For now, you may simply wish to change
471 @example
472 *esp = PHYS_BASE;
473 @end example
474 @noindent to
475 @example
476 *esp = PHYS_BASE - 12;
477 @end example
478 in @func{setup_stack}.  That will work for any test program that doesn't
479 examine its arguments, although its name will be printed as
480 @code{(null)}.
481
482 Until you implement argument passing, you should only run programs
483 without passing command-line arguments.  Attempting to pass arguments to
484 a program will include those arguments in the name of the program, which
485 will probably fail.
486
487 @item
488 User memory access (@pxref{Accessing User Memory}).  All system calls
489 need to read user memory.  Few system calls need to write to user
490 memory.
491
492 @item
493 System call infrastructure (@pxref{System Calls}).  Implement enough
494 code to read the system call number from the user stack and dispatch to
495 a handler based on it.
496
497 @item
498 The @code{exit} system call.  Every user program that finishes in the
499 normal way calls @code{exit}.  Even a program that returns from
500 @func{main} calls @code{exit} indirectly (see @func{_start} in
501 @file{lib/user/entry.c}).
502
503 @item
504 The @code{write} system call for writing to fd 1, the system console.
505 All of our test programs write to the console (the user process version
506 of @func{printf} is implemented this way), so they will all malfunction
507 until @code{write} is available.
508
509 @item
510 For now, change @func{process_wait} to an infinite loop (one that waits
511 forever).  The provided implementation returns immediately, so Pintos
512 will power off before any processes actually get to run.  You will
513 eventually need to provide a correct implementation.
514 @end itemize
515
516 After the above are implemented, user processes should work minimally.
517 At the very least, they can write to the console and exit correctly.
518 You can then refine your implementation so that some of the tests start
519 to pass.
520
521 @node Project 2 Requirements
522 @section Requirements
523
524 @menu
525 * Project 2 Design Document::   
526 * Process Termination Messages::  
527 * Argument Passing::            
528 * System Calls::                
529 * Denying Writes to Executables::  
530 @end menu
531
532 @node Project 2 Design Document
533 @subsection Design Document
534
535 Before you turn in your project, you must copy @uref{userprog.tmpl, ,
536 the project 2 design document template} into your source tree under the
537 name @file{pintos/src/userprog/DESIGNDOC} and fill it in.  We recommend
538 that you read the design document template before you start working on
539 the project.  @xref{Project Documentation}, for a sample design document
540 that goes along with a fictitious project.
541
542 @node Process Termination Messages
543 @subsection Process Termination Messages
544
545 Whenever a user process terminates, because it called @code{exit}
546 or for any other reason, print the process's name
547 and exit code, formatted as if printed by @code{printf ("%s:
548 exit(%d)\n", @dots{});}.  The name printed should be the full name
549 passed to @func{process_execute}, omitting command-line arguments.
550 Do not print these messages when a kernel thread that is not a user
551 process terminates, or
552 when the @code{halt} system call is invoked.  The message is optional
553 when a process fails to load.
554
555 Aside from this, don't print any other
556 messages that Pintos as provided doesn't already print.  You may find
557 extra messages useful during debugging, but they will confuse the
558 grading scripts and thus lower your score.
559
560 @node Argument Passing
561 @subsection Argument Passing
562
563 Currently, @func{process_execute} does not support passing arguments to
564 new processes.  Implement this functionality, by extending
565 @func{process_execute} so that instead of simply taking a program file
566 name as its argument, it divides it into words at spaces.  The first
567 word is the program name, the second word is the first argument, and so
568 on.  That is, @code{process_execute("grep foo bar")} should run
569 @command{grep} passing two arguments @code{foo} and @code{bar}.
570
571 Within a command line, multiple spaces are equivalent to a single
572 space, so that @code{process_execute("grep @w{ }foo @w{ }@w{ }bar")}
573 is equivalent to our original example.  You can impose a reasonable
574 limit on the length of the command line arguments.  For example, you
575 could limit the arguments to those that will fit in a single page (4
576 kB).  (There is an unrelated limit of 128 bytes on command-line
577 arguments that the @command{pintos} utility can pass to the kernel.)
578
579 You can parse argument strings any way you like.  If you're lost,
580 look at @func{strtok_r}, prototyped in @file{lib/string.h} and
581 implemented with thorough comments in @file{lib/string.c}.  You can
582 find more about it by looking at the man page (run @code{man strtok_r}
583 at the prompt).
584
585 @xref{Program Startup Details}, for information on exactly how you
586 need to set up the stack.
587
588 @node System Calls
589 @subsection System Calls
590
591 Implement the system call handler in @file{userprog/syscall.c}.  The
592 skeleton implementation we provide ``handles'' system calls by
593 terminating the process.  It will need to retrieve the system call
594 number, then any system call arguments, and carry out appropriate actions.
595
596 Implement the following system calls.  The prototypes listed are those
597 seen by a user program that includes @file{lib/user/syscall.h}.  (This
598 header, and all others in @file{lib/user}, are for use by user
599 programs only.)  System call numbers for each system call are defined in
600 @file{lib/syscall-nr.h}:
601
602 @deftypefn {System Call} void halt (void)
603 Terminates Pintos by calling @func{power_off} (declared in
604 @file{threads/init.h}).  This should be seldom used, because you lose
605 some information about possible deadlock situations, etc.
606 @end deftypefn
607
608 @deftypefn {System Call} void exit (int @var{status})
609 Terminates the current user program, returning @var{status} to the
610 kernel.  If the process's parent @code{wait}s for it (see below), this
611 is the status
612 that will be returned.  Conventionally, a @var{status} of 0 indicates
613 success and nonzero values indicate errors.
614 @end deftypefn
615
616 @deftypefn {System Call} pid_t exec (const char *@var{cmd_line})
617 Runs the executable whose name is given in @var{cmd_line}, passing any
618 given arguments, and returns the new process's program id (pid).  Must
619 return pid -1, which otherwise should not be a valid pid, if
620 the program cannot load or run for any reason.
621 Thus, the parent process cannot return from the @code{exec} until it
622 knows whether the child process successfully loaded its executable.
623 You must use appropriate synchronization to ensure this.
624 @end deftypefn
625
626 @deftypefn {System Call} int wait (pid_t @var{pid})
627 Waits for a child process @var{pid} and retrieves the child's exit status.
628
629 If @var{pid} is still alive, waits until it terminates.  Then, returns
630 the status that @var{pid} passed to @code{exit}.  If @var{pid} did not
631 call @code{exit()}, but was terminated by the kernel (e.g.@: killed
632 due to an exception), @code{wait(pid)} must return -1.  It is perfectly
633 legal for a parent process to wait for child processes that have already
634 terminated by the time the parent calls @code{wait}, but the kernel must
635 still allow the parent to retrieve its child's exit status, or learn
636 that the child was terminated by the kernel.
637
638 @code{wait} must fail and return -1 immediately if any of the
639 following conditions is true:
640 @itemize @bullet
641 @item
642 @var{pid} does not refer to a direct child of the calling process.
643 @var{pid} is a direct child of the calling process if and
644 only if the calling process received @var{pid} as a return value
645 from a successful call to @code{exec}.
646
647 Note that children are not inherited: if @var{A} spawns child @var{B}
648 and @var{B} spawns child process @var{C}, then @var{A} cannot wait for
649 @var{C}, even if @var{B} is dead.  A call to @code{wait(C)} by process
650 @var{A} must fail.  Similarly, orphaned processes are not assigned to
651 a new parent if their parent process exits before they do.
652
653 @item
654 The process that calls @code{wait} has already called @code{wait} on
655 @var{pid}.  That is, a process may wait for any given child at most
656 once.
657 @end itemize
658
659 Processes may spawn any number of children, wait for them in any order,
660 and may even exit without having waited for some or all of their children.
661 Your design should consider all the ways in which waits can occur.
662 All of a process's resources, including its @struct{thread}, must be
663 freed whether its parent ever waits for it or not, and regardless of
664 whether the child exits before or after its parent.
665
666 You must ensure that Pintos does not terminate until the initial
667 process exits.  The supplied Pintos code tries to do this by calling
668 @func{process_wait} (in @file{userprog/process.c}) from @func{main}
669 (in @file{threads/init.c}).  We suggest that you implement
670 @func{process_wait} according to the comment at the top of the
671 function and then implement the @code{wait} system call in terms of
672 @func{process_wait}.
673
674 Implementing this system call requires considerably more work than any
675 of the rest.
676 @end deftypefn
677
678 @deftypefn {System Call} bool create (const char *@var{file}, unsigned @var{initial_size})
679 Creates a new file called @var{file} initially @var{initial_size} bytes
680 in size.  Returns true if successful, false otherwise.
681 Creating a new file does not open it: opening the new file is a
682 separate operation which would require a @code{open} system call.
683 @end deftypefn
684
685 @deftypefn {System Call} bool remove (const char *@var{file})
686 Deletes the file called @var{file}.  Returns true if successful, false
687 otherwise.
688 A file may be removed regardless of whether it is open or closed, and
689 removing an open file does not close it.  @xref{Removing an Open
690 File}, for details.
691 @end deftypefn
692
693 @deftypefn {System Call} int open (const char *@var{file})
694 Opens the file called @var{file}.  Returns a nonnegative integer handle
695 called a ``file descriptor'' (fd), or -1 if the file could not be
696 opened.  
697
698 File descriptors numbered 0 and 1 are reserved for the console: fd 0
699 (@code{STDIN_FILENO}) is standard input, fd 1 (@code{STDOUT_FILENO}) is
700 standard output.  The @code{open} system call will never return either
701 of these file descriptors, which are valid as system call arguments only
702 as explicitly described below.
703
704 Each process has an independent set of file descriptors.  File
705 descriptors are not inherited by child processes.
706
707 When a single file is opened more than once, whether by a single
708 process or different processes, each @code{open} returns a new file
709 descriptor.  Different file descriptors for a single file are closed
710 independently in separate calls to @code{close} and they do not share
711 a file position.
712 @end deftypefn
713
714 @deftypefn {System Call} int filesize (int @var{fd})
715 Returns the size, in bytes, of the file open as @var{fd}.
716 @end deftypefn
717
718 @deftypefn {System Call} int read (int @var{fd}, void *@var{buffer}, unsigned @var{size})
719 Reads @var{size} bytes from the file open as @var{fd} into
720 @var{buffer}.  Returns the number of bytes actually read (0 at end of
721 file), or -1 if the file could not be read (due to a condition other
722 than end of file).  Fd 0 reads from the keyboard using
723 @func{input_getc}.
724 @end deftypefn
725
726 @deftypefn {System Call} int write (int @var{fd}, const void *@var{buffer}, unsigned @var{size})
727 Writes @var{size} bytes from @var{buffer} to the open file @var{fd}.
728 Returns the number of bytes actually written, which may be less than
729 @var{size} if some bytes could not be written.
730
731 Writing past end-of-file would normally extend the file, but file growth
732 is not implemented by the basic file system.  The expected behavior is
733 to write as many bytes as possible up to end-of-file and return the
734 actual number written, or 0 if no bytes could be written at all.
735
736 Fd 1 writes to the console.  Your code to write to the console should
737 write all of @var{buffer} in one call to @func{putbuf}, at least as
738 long as @var{size} is not bigger than a few hundred bytes.  (It is
739 reasonable to break up larger buffers.)  Otherwise,
740 lines of text output by different processes may end up interleaved on
741 the console, confusing both human readers and our grading scripts.
742 @end deftypefn
743
744 @deftypefn {System Call} void seek (int @var{fd}, unsigned @var{position})
745 Changes the next byte to be read or written in open file @var{fd} to
746 @var{position}, expressed in bytes from the beginning of the file.
747 (Thus, a @var{position} of 0 is the file's start.)
748
749 A seek past the current end of a file is not an error.  A later read
750 obtains 0 bytes, indicating end of file.  A later write extends the
751 file, filling any unwritten gap with zeros.  (However, in Pintos files
752 have a fixed length until project 4 is complete, so writes past end of
753 file will return an error.)  These semantics are implemented in the
754 file system and do not require any special effort in system call
755 implementation.
756 @end deftypefn
757
758 @deftypefn {System Call} unsigned tell (int @var{fd})
759 Returns the position of the next byte to be read or written in open
760 file @var{fd}, expressed in bytes from the beginning of the file.
761 @end deftypefn
762
763 @deftypefn {System Call} void close (int @var{fd})
764 Closes file descriptor @var{fd}.  
765 Exiting or terminating a process implicitly closes all its open file
766 descriptors, as if by calling this function for each one.
767 @end deftypefn
768
769 The file defines other syscalls.  Ignore them for now.  You will
770 implement some of them in project 3 and the rest in project 4, so be
771 sure to design your system with extensibility in mind.
772
773 To implement syscalls, you need to provide ways to read and write data
774 in user virtual address space.
775 You need this ability before you can
776 even obtain the system call number, because the system call number is
777 on the user's stack in the user's virtual address space.
778 This can be a bit tricky: what if the user provides an invalid
779 pointer, a pointer into kernel memory, or a block
780 partially in one of those regions?  You should handle these cases by
781 terminating the user process.  We recommend
782 writing and testing this code before implementing any other system
783 call functionality.  @xref{Accessing User Memory}, for more information.
784
785 You must synchronize system calls so that
786 any number of user processes can make them at once.  In particular, it
787 is not safe to call into the file system code provided in the
788 @file{filesys} directory from multiple threads at once.  Your system
789 call implementation must treat the file system code as a critical
790 section.  Don't forget
791 that @func{process_execute} also accesses files.  For now, we
792 recommend against modifying code in the @file{filesys} directory.
793
794 We have provided you a user-level function for each system call in
795 @file{lib/user/syscall.c}.  These provide a way for user processes to
796 invoke each system call from a C program.  Each uses a little inline
797 assembly code to invoke the system call and (if appropriate) returns the
798 system call's return value.
799
800 When you're done with this part, and forevermore, Pintos should be
801 bulletproof.  Nothing that a user program can do should ever cause the
802 OS to crash, panic, fail an assertion, or otherwise malfunction.  It is
803 important to emphasize this point: our tests will try to break your
804 system calls in many, many ways.  You need to think of all the corner
805 cases and handle them.  The sole way a user program should be able to
806 cause the OS to halt is by invoking the @code{halt} system call.
807
808 If a system call is passed an invalid argument, acceptable options
809 include returning an error value (for those calls that return a
810 value), returning an undefined value, or terminating the process.
811
812 @xref{System Call Details}, for details on how system calls work.
813
814 @node Denying Writes to Executables
815 @subsection Denying Writes to Executables
816
817 Add code to deny writes to files in use as executables.  Many OSes do
818 this because of the unpredictable results if a process tried to run code
819 that was in the midst of being changed on disk.  This is especially
820 important once virtual memory is implemented in project 3, but it can't
821 hurt even now.
822
823 You can use @func{file_deny_write} to prevent writes to an open file.
824 Calling @func{file_allow_write} on the file will re-enable them (unless
825 the file is denied writes by another opener).  Closing a file will also
826 re-enable writes.  Thus, to deny writes to a process's executable, you
827 must keep it open as long as the process is still running.
828
829 @node Project 2 FAQ
830 @section FAQ
831
832 @table @asis
833 @item How much code will I need to write?
834
835 Here's a summary of our reference solution, produced by the
836 @command{diffstat} program.  The final row gives total lines inserted
837 and deleted; a changed line counts as both an insertion and a deletion.
838
839 The reference solution represents just one possible solution.  Many
840 other solutions are also possible and many of those differ greatly from
841 the reference solution.  Some excellent solutions may not modify all the
842 files modified by the reference solution, and some may modify files not
843 modified by the reference solution.
844
845 @verbatim
846  threads/thread.c     |   13 
847  threads/thread.h     |   26 +
848  userprog/exception.c |    8 
849  userprog/process.c   |  247 ++++++++++++++--
850  userprog/syscall.c   |  468 ++++++++++++++++++++++++++++++-
851  userprog/syscall.h   |    1 
852  6 files changed, 725 insertions(+), 38 deletions(-)
853 @end verbatim
854
855 @item The kernel always panics when I run @code{pintos -p @var{file} -- -q}.
856
857 Did you format the file system (with @samp{pintos -f})?
858
859 Is your file name too long?  The file system limits file names to 14
860 characters.  A command like @samp{pintos -p ../../examples/echo -- -q}
861 will exceed the limit.  Use @samp{pintos -p ../../examples/echo -a echo
862 -- -q} to put the file under the name @file{echo} instead.
863
864 Is the file system full?
865
866 Does the file system already contain 16 files?  The base Pintos file
867 system has a 16-file limit.
868
869 The file system may be so fragmented that there's not enough contiguous
870 space for your file.
871
872 @item When I run @code{pintos -p ../file --}, @file{file} isn't copied.
873
874 Files are written under the name you refer to them, by default, so in
875 this case the file copied in would be named @file{../file}.  You
876 probably want to run @code{pintos -p ../file -a file --} instead.
877
878 You can list the files in your file system with @code{pintos -q ls}.
879
880 @item All my user programs die with page faults.
881
882 This will happen if you haven't implemented argument passing
883 (or haven't done so correctly).  The basic C library for user programs tries
884 to read @var{argc} and @var{argv} off the stack.  If the stack
885 isn't properly set up, this causes a page fault.
886
887 @item All my user programs die with @code{system call!}
888
889 You'll have to implement system calls before you see anything else.
890 Every reasonable program tries to make at least one system call
891 (@func{exit}) and most programs make more than that.  Notably,
892 @func{printf} invokes the @code{write} system call.  The default system
893 call handler just prints @samp{system call!} and terminates the program.
894 Until then, you can use @func{hex_dump} to convince yourself that
895 argument passing is implemented correctly (@pxref{Program Startup Details}).
896
897 @item How can I disassemble user programs?
898
899 The @command{objdump} (80@var{x}86) or @command{i386-elf-objdump}
900 (SPARC) utility can disassemble entire user
901 programs or object files.  Invoke it as @code{objdump -d
902 @var{file}}.  You can use GDB's
903 @code{disassemble} command to disassemble individual functions
904 (@pxref{GDB}).
905
906 @item Why do many C include files not work in Pintos programs?
907 @itemx Can I use lib@var{foo} in my Pintos programs?
908
909 The C library we provide is very limited.  It does not include many of
910 the features that are expected of a real operating system's C library.
911 The C library must be built specifically for the operating system (and
912 architecture), since it must make system calls for I/O and memory
913 allocation.  (Not all functions do, of course, but usually the library
914 is compiled as a unit.)
915
916 The chances are good that the library you want uses parts of the C library
917 that Pintos doesn't implement.  It will probably take at least some
918 porting effort to make it work under Pintos.  Notably, the Pintos
919 user program C library does not have a @func{malloc} implementation.
920
921 @item How do I compile new user programs?
922
923 Modify @file{src/examples/Makefile}, then run @command{make}.
924
925 @item Can I run user programs under a debugger?
926
927 Yes, with some limitations.  @xref{GDB}.
928
929 @item What's the difference between @code{tid_t} and @code{pid_t}?
930
931 A @code{tid_t} identifies a kernel thread, which may have a user
932 process running in it (if created with @func{process_execute}) or not
933 (if created with @func{thread_create}).  It is a data type used only
934 in the kernel.
935
936 A @code{pid_t} identifies a user process.  It is used by user
937 processes and the kernel in the @code{exec} and @code{wait} system
938 calls.
939
940 You can choose whatever suitable types you like for @code{tid_t} and
941 @code{pid_t}.  By default, they're both @code{int}.  You can make them
942 a one-to-one mapping, so that the same values in both identify the
943 same process, or you can use a more complex mapping.  It's up to you.
944 @end table
945
946 @menu
947 * Argument Passing FAQ::        
948 * System Calls FAQ::            
949 @end menu
950
951 @node Argument Passing FAQ
952 @subsection Argument Passing FAQ
953
954 @table @asis
955 @item Isn't the top of stack in kernel virtual memory?
956
957 The top of stack is at @code{PHYS_BASE}, typically @t{0xc0000000}, which
958 is also where kernel virtual memory starts.
959 But before the processor pushes data on the stack, it decrements the stack
960 pointer.  Thus, the first (4-byte) value pushed on the stack
961 will be at address @t{0xbffffffc}.
962
963 @item Is @code{PHYS_BASE} fixed?
964
965 No.  You should be able to support @code{PHYS_BASE} values that are
966 any multiple of @t{0x10000000} from @t{0x80000000} to @t{0xf0000000},
967 simply via recompilation.
968 @end table
969
970 @node System Calls FAQ
971 @subsection System Calls FAQ
972
973 @table @asis
974 @item Can I just cast a @code{struct file *} to get a file descriptor?
975 @itemx Can I just cast a @code{struct thread *} to a @code{pid_t}?
976
977 You will have to make these design decisions yourself.
978 Most operating systems do distinguish between file
979 descriptors (or pids) and the addresses of their kernel data
980 structures.  You might want to give some thought as to why they do so
981 before committing yourself.
982
983 @item Can I set a maximum number of open files per process?
984
985 It is better not to set an arbitrary limit.  You may impose a limit of
986 128 open files per process, if necessary.
987
988 @item What happens when an open file is removed?
989 @anchor{Removing an Open File}
990
991 You should implement the standard Unix semantics for files.  That is, when
992 a file is removed any process which has a file descriptor for that file
993 may continue to use that descriptor.  This means that
994 they can read and write from the file.  The file will not have a name,
995 and no other processes will be able to open it, but it will continue
996 to exist until all file descriptors referring to the file are closed
997 or the machine shuts down.
998
999 @item How can I run user programs that need more than 4 kB stack space?
1000
1001 You may modify the stack setup code to allocate more than one page of
1002 stack space for each process.  In the next project, you will implement a
1003 better solution.
1004
1005 @item What should happen if an @code{exec} fails midway through loading?
1006
1007 @code{exec} should return -1 if the child process fails to load for
1008 any reason.  This includes the case where the load fails part of the
1009 way through the process (e.g.@: where it runs out of memory in the
1010 @code{multi-oom} test).  Therefore, the parent process cannot return
1011 from the @code{exec} system call until it is established whether the
1012 load was successful or not.  The child must communicate this
1013 information to its parent using appropriate synchronization, such as a
1014 semaphore (@pxref{Semaphores}), to ensure that the information is
1015 communicated without race conditions.
1016 @end table
1017
1018 @node 80x86 Calling Convention
1019 @section 80@var{x}86 Calling Convention
1020
1021 This section summarizes important points of the convention used for
1022 normal function calls on 32-bit 80@var{x}86 implementations of Unix.
1023 Some details are omitted for brevity.  If you do want all the details,
1024 refer to @bibref{SysV-i386}.
1025
1026 The calling convention works like this:
1027
1028 @enumerate 1
1029 @item
1030 The caller pushes each of the function's arguments on the stack one by
1031 one, normally using the @code{PUSH} assembly language instruction.
1032 Arguments are pushed in right-to-left order.
1033
1034 The stack grows downward: each push decrements the stack pointer, then
1035 stores into the location it now points to, like the C expression
1036 @samp{*--sp = @var{value}}.
1037
1038 @item
1039 The caller pushes the address of its next instruction (the @dfn{return
1040 address}) on the stack and jumps to the first instruction of the callee.
1041 A single 80@var{x}86 instruction, @code{CALL}, does both.
1042
1043 @item
1044 The callee executes.  When it takes control, the stack pointer points to
1045 the return address, the first argument is just above it, the second
1046 argument is just above the first argument, and so on.
1047
1048 @item
1049 If the callee has a return value, it stores it into register @code{EAX}.
1050
1051 @item
1052 The callee returns by popping the return address from the stack and
1053 jumping to the location it specifies, using the 80@var{x}86 @code{RET}
1054 instruction.
1055
1056 @item
1057 The caller pops the arguments off the stack.
1058 @end enumerate
1059
1060 Consider a function @func{f} that takes three @code{int} arguments.
1061 This diagram shows a sample stack frame as seen by the callee at the
1062 beginning of step 3 above, supposing that @func{f} is invoked as
1063 @code{f(1, 2, 3)}.  The initial stack address is arbitrary:
1064
1065 @html
1066 <CENTER>
1067 @end html
1068 @example
1069                              +----------------+
1070                   0xbffffe7c |        3       |
1071                   0xbffffe78 |        2       |
1072                   0xbffffe74 |        1       |
1073 stack pointer --> 0xbffffe70 | return address |
1074                              +----------------+
1075 @end example
1076 @html
1077 </CENTER>
1078 @end html
1079
1080 @menu
1081 * Program Startup Details::     
1082 * System Call Details::         
1083 @end menu
1084
1085 @node Program Startup Details
1086 @subsection Program Startup Details
1087
1088 The Pintos C library for user programs designates @func{_start}, in
1089 @file{lib/user/entry.c}, as the entry point for user programs.  This
1090 function is a wrapper around @func{main} that calls @func{exit} if
1091 @func{main} returns:
1092
1093 @example
1094 void
1095 _start (int argc, char *argv[]) 
1096 @{
1097   exit (main (argc, argv));
1098 @}
1099 @end example
1100
1101 The kernel must put the arguments for the initial function on the stack
1102 before it allows the user program to begin executing.  The arguments are
1103 passed in the same way as the normal calling convention (@pxref{80x86
1104 Calling Convention}).
1105
1106 Consider how to handle arguments for the following example command:
1107 @samp{/bin/ls -l foo bar}.
1108 First, break the command into words: @samp{/bin/ls},
1109 @samp{-l}, @samp{foo}, @samp{bar}.  Place the words at the top of the
1110 stack.  Order doesn't matter, because they will be referenced through
1111 pointers.
1112
1113 Then, push the address of each string plus a null pointer sentinel, on
1114 the stack, in right-to-left order.  These are the elements of
1115 @code{argv}.  The null pointer sentinel ensures that @code{argv[argc]}
1116 is a null pointer, as required by the C standard.  The order ensures
1117 that @code{argv[0]} is at the lowest virtual address.  Word-aligned
1118 accesses are faster than unaligned accesses, so for best performance
1119 round the stack pointer down to a multiple of 4 before the first push.
1120
1121 Then, push @code{argv} (the address of @code{argv[0]}) and @code{argc},
1122 in that order.  Finally, push a fake ``return address'': although the
1123 entry function will never return, its stack frame must have the same
1124 structure as any other.
1125
1126 The table below shows the state of the stack and the relevant registers
1127 right before the beginning of the user program, assuming
1128 @code{PHYS_BASE} is @t{0xc0000000}:
1129
1130 @html
1131 <CENTER>
1132 @end html
1133 @multitable {@t{0xbfffffff}} {return address} {@t{/bin/ls\0}} {@code{void (*) ()}}
1134 @item Address @tab Name @tab Data @tab Type
1135 @item @t{0xbffffffc} @tab @code{argv[3][@dots{}]} @tab @samp{bar\0} @tab @code{char[4]}
1136 @item @t{0xbffffff8} @tab @code{argv[2][@dots{}]} @tab @samp{foo\0} @tab @code{char[4]}
1137 @item @t{0xbffffff5} @tab @code{argv[1][@dots{}]} @tab @samp{-l\0} @tab @code{char[3]}
1138 @item @t{0xbfffffed} @tab @code{argv[0][@dots{}]} @tab @samp{/bin/ls\0} @tab @code{char[8]}
1139 @item @t{0xbfffffec} @tab word-align @tab 0 @tab @code{uint8_t}
1140 @item @t{0xbfffffe8} @tab @code{argv[4]} @tab @t{0} @tab @code{char *}
1141 @item @t{0xbfffffe4} @tab @code{argv[3]} @tab @t{0xbffffffc} @tab @code{char *}
1142 @item @t{0xbfffffe0} @tab @code{argv[2]} @tab @t{0xbffffff8} @tab @code{char *}
1143 @item @t{0xbfffffdc} @tab @code{argv[1]} @tab @t{0xbffffff5} @tab @code{char *}
1144 @item @t{0xbfffffd8} @tab @code{argv[0]} @tab @t{0xbfffffed} @tab @code{char *}
1145 @item @t{0xbfffffd4} @tab @code{argv} @tab @t{0xbfffffd8} @tab @code{char **}
1146 @item @t{0xbfffffd0} @tab @code{argc} @tab 4 @tab @code{int}
1147 @item @t{0xbfffffcc} @tab return address @tab 0 @tab @code{void (*) ()}
1148 @end multitable
1149 @html
1150 </CENTER>
1151 @end html
1152
1153 In this example, the stack pointer would be initialized to
1154 @t{0xbfffffcc}.
1155
1156 As shown above, your code should start the stack at the very top of
1157 the user virtual address space, in the page just below virtual address
1158 @code{PHYS_BASE} (defined in @file{threads/vaddr.h}).
1159
1160 You may find the non-standard @func{hex_dump} function, declared in
1161 @file{<stdio.h>}, useful for debugging your argument passing code.
1162 Here's what it would show in the above example:
1163
1164 @verbatim
1165 bfffffc0                                      00 00 00 00 |            ....|
1166 bfffffd0  04 00 00 00 d8 ff ff bf-ed ff ff bf f5 ff ff bf |................|
1167 bfffffe0  f8 ff ff bf fc ff ff bf-00 00 00 00 00 2f 62 69 |............./bi|
1168 bffffff0  6e 2f 6c 73 00 2d 6c 00-66 6f 6f 00 62 61 72 00 |n/ls.-l.foo.bar.|
1169 @end verbatim
1170
1171 @node System Call Details
1172 @subsection System Call Details
1173
1174 The first project already dealt with one way that the operating system
1175 can regain control from a user program: interrupts from timers and I/O
1176 devices.  These are ``external'' interrupts, because they are caused
1177 by entities outside the CPU (@pxref{External Interrupt Handling}).
1178
1179 The operating system also deals with software exceptions, which are
1180 events that occur in program code (@pxref{Internal Interrupt
1181 Handling}).  These can be errors such as a page fault or division by
1182 zero.  Exceptions are also the means by which a user program
1183 can request services (``system calls'') from the operating system.
1184
1185 In the 80@var{x}86 architecture, the @samp{int} instruction is the
1186 most commonly used means for invoking system calls.  This instruction
1187 is handled in the same way as other software exceptions.  In Pintos,
1188 user programs invoke @samp{int $0x30} to make a system call.  The
1189 system call number and any additional arguments are expected to be
1190 pushed on the stack in the normal fashion before invoking the
1191 interrupt (@pxref{80x86 Calling Convention}).
1192
1193 Thus, when the system call handler @func{syscall_handler} gets control,
1194 the system call number is in the 32-bit word at the caller's stack
1195 pointer, the first argument is in the 32-bit word at the next higher
1196 address, and so on.  The caller's stack pointer is accessible to
1197 @func{syscall_handler} as the @samp{esp} member of the
1198 @struct{intr_frame} passed to it.  (@struct{intr_frame} is on the kernel
1199 stack.)
1200
1201 The 80@var{x}86 convention for function return values is to place them
1202 in the @code{EAX} register.  System calls that return a value can do
1203 so by modifying the @samp{eax} member of @struct{intr_frame}.
1204
1205 You should try to avoid writing large amounts of repetitive code for
1206 implementing system calls.  Each system call argument, whether an
1207 integer or a pointer, takes up 4 bytes on the stack.  You should be able
1208 to take advantage of this to avoid writing much near-identical code for
1209 retrieving each system call's arguments from the stack.