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