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