Update docs.
[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 familiar with its
5 infrastructure and thread package, it's time to start working on the
6 parts of the system that will allow users to run programs on top of
7 your operating system.  The base code already supports loading and
8 running a single user program at a time with little interactivity
9 possible.  You will allow multiple programs to be loaded in at once,
10 and to interact with 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. If you are confident in your HW1 code, you can
16 build on top of it.  However, if you wish you can start with a fresh
17 copy of the code and re-implement @code{thread_join()}, which is the
18 only part of project #1 required for this assignment.  Your submission
19 should define @code{THREAD_JOIN_IMPLEMENTED} in @file{constants.h}
20 (@pxref{Conditional Compilation}).
21
22 Up to now, all of the code you have written for Pintos has been part
23 of the operating system kernel.  This means, for example, that all the
24 test code from the last assignment ran as part of the kernel, with
25 full access to privileged parts of the system.  Once we start running
26 user programs on top of the operating system, this is no longer true.
27 This project deals with consequences of the change.
28
29 We allow more than one user program to run at a time.  Because user
30 programs are written and compiled to work under the illusion that they
31 have the entire machine, when you load into memory and run more than
32 one process at a time, you must manage things correctly to maintain
33 this illusion.
34
35 Before we delve into the details of the new code that you'll be
36 working with, you should probably undo the test cases from project 1.
37 All you need to do is make sure the original @file{threads/test.c} is
38 in place.  This will stop the tests from being run.
39
40 @menu
41 * Project 2 Code::              
42 * Using the File System::       
43 * How User Programs Work::      
44 * Virtual Memory Layout::       
45 * Global Requirements::         
46 * Problem 2-1 Argument Passing::  
47 * Problem 2-2 System Calls::    
48 * User Programs FAQ::           
49 * 80x86 Calling Convention::    
50 * System Calls::                
51 @end menu
52
53 @node Project 2 Code
54 @section Code
55
56 The easiest way to get an overview of the programming you will be
57 doing is to simply go over each part you'll be working with.  In
58 @file{userprog}, you'll find a small number of files, but here is
59 where the bulk of your work will be:
60
61 @table @file
62 @item process.c
63 @itemx process.h
64 Loads ELF binaries and starts processes.
65
66 @item pagedir.c
67 @itemx pagedir.h
68 A simple manager for 80@var{x} page directories and page tables.
69 Although you probably won't want to modify this code for this project,
70 you may want to call some of its functions.  In particular,
71 @code{pagedir_get_page()} may be helpful for accessing user memory.
72
73 @item syscall.c
74 @itemx syscall.h
75 Whenever a user process wants to access some kernel functionality, it
76 needs to do so via a system call.  This is a skeleton system call
77 handler.  Currently, it just prints a message and terminates the user
78 process.  In part 2 of this project you will add code to do everything
79 else needed by system calls.
80
81 @item exception.c
82 @itemx exception.h
83 When a user process performs a privileged or prohibited operation, it
84 traps into the kernel as an ``exception'' or ``fault.''@footnote{We
85 will treat these terms as synonymous.  There is no standard
86 distinction between them, although the Intel processor manuals define
87 them slightly differently on 80@var{x}86.}  These files handle
88 exceptions.  Currently all exceptions simply print a message and
89 terminate the process.  Some, but not all, solutions to project 2
90 require modifying @code{page_fault()} in this file.
91
92 @item gdt.c
93 @itemx gdt.c
94 The 80@var{x}86 is a segmented architecture.  The Global Descriptor
95 Table (GDT) is a table that describes the segments in use.  These
96 files set up the GDT.  @strong{You should not need to modify these
97 files for any of the projects.}  However, you can read the code if
98 you're interested in how the GDT works.
99
100 @item tss.c
101 @itemx tss.c
102 The Task-State Segment (TSS) is used for 80@var{x}86 architectural
103 task switching.  Pintos uses the TSS only for switching stacks when a
104 user process enters an interrupt handler, as does Linux.  @strong{You
105 should not need to modify these files for any of the projects.}
106 However, you can read the code if you're interested in how the GDT
107 works.
108 @end table
109
110 Finally, in @file{lib/kernel}, you might want to use
111 @file{bitmap.[ch]}.  A bitmap is basically an array of bits, each of
112 which can be true or false.  Bitmaps are typically used to keep track
113 of the usage of a large array of (identical) resources: if resource
114 @var{n} is in use, then bit @var{n} of the bitmap is true.  You might
115 find it useful for tracking memory pages, for example.
116
117 @node Using the File System
118 @section Using the File System
119
120 You will need to use some file system code for this project.  First,
121 user programs are loaded from the file system.  Second, many of the
122 system calls you must implement deal with the file system.  However,
123 the focus of this project is not on the file system code, so we have
124 provided a simple file system in the @file{filesys} directory.  You
125 will want to look over the @file{filesys.h} and @file{file.h}
126 interfaces to understand how to use the file system, and especially
127 its many limitations.  @strong{You should not modify the file system
128 code for this project}.  Proper use of the file system routines now
129 will make life much easier for project 4, when you improve the file
130 system implementation.
131
132 You need to be able to create and format simulated disks.  The
133 @command{pintos} program provides this functionality with its
134 @option{make-disk} command.  From the @file{filesys/build} directory,
135 execute @code{pintos make-disk fs.dsk 2}.  This command creates a 2 MB
136 simulated disk named @file{fs.dsk}.  (It does not actually start
137 Pintos.)  Then format the disk by passing the @option{-f} option to
138 Pintos on the kernel's command line: @code{pintos run -f}.
139
140 You'll need a way to get files in and out of the simulated file
141 system.  The @code{pintos} @option{put} and @option{get} commands are
142 designed for this.  To copy @file{@var{file}} into the Pintos file
143 system, use the command @file{pintos put @var{file}}.  To copy it to
144 the Pintos file system under the name @file{@var{newname}}, add the
145 new name to the end of the command: @file{pintos put @var{file}
146 @var{newname}}.  The commands for copying files out of a VM are
147 similar, but substitute @option{get} for @option{get}.
148
149 Incidentally, these commands work by passing special options
150 @option{-ci} and @option{-co} on the kernel's command line and copying
151 to and from a special simulated disk named @file{scratch.dsk}.  If
152 you're very curious, you can look at the @command{pintos} program as
153 well as @file{filesys/fsutil.c} to learn the implementation details,
154 but it's really not relevant for this project.
155
156 You can delete a file from the Pintos file system using the @option{-r
157 @var{file}} kernel option, e.g.@: @code{pintos run -r @var{file}}.
158 Also, @option{-ls} lists the files in the file system and @option{-p
159 @var{file}} prints a file's contents to the display.
160
161 @node How User Programs Work
162 @section How User Programs Work
163
164 Pintos can run normal C programs.  In fact, it can run any program you
165 want, provided it's compiled into the proper file format, and uses
166 only the system calls you implement.  (For example, @code{malloc()}
167 makes use of functionality that isn't provided by any of the syscalls
168 we require you to support.)  The only other limitation is that Pintos
169 can't run programs using floating point operations, since it doesn't
170 include the necessary kernel functionality to save and restore the
171 processor's floating-point unit when switching threads.  You can look
172 in @file{tests/userprog} directory for some examples.
173
174 Pintos loads ELF executables, where ELF is an executable format used
175 by Linux, Solaris, and many other Unix and Unix-like systems.
176 Therefore, you can use any compiler and linker that produce
177 80@var{x}86 ELF executables to produce programs for Pintos.  We
178 recommend using the tools we provide in the @file{tests/userprog}
179 directory.  By default, the @file{Makefile} in this directory will
180 compile the test programs we provide.  You can edit the
181 @file{Makefile} to compile your own test programs as well.
182
183 One thing you should realize immediately is that, until you use the
184 above operation to copy a test program to the emulated disk, Pintos
185 will be unable to do very much useful work.  You will also find that
186 you won't be able to do interesting things until you copy a variety of
187 programs to the disk.  A useful technique is to create a clean
188 reference disk and copy that over whenever you trash your
189 @file{fs.dsk} beyond a useful state, which may happen occasionally
190 while debugging.
191
192 @node Virtual Memory Layout
193 @section Virtual Memory Layout
194
195 Virtual memory in Pintos is divided into two regions: user virtual
196 memory and kernel virtual memory.  User virtual memory ranges from
197 virtual address 0 up to @code{PHYS_BASE}, which is defined in
198 @file{threads/mmu.h} and defaults to @t{0xc0000000} (3 GB).  Kernel
199 virtual memory occupies the rest of the virtual address space, from
200 @code{PHYS_BASE} up to 4 GB.
201
202 User virtual memory is per-process.  Conceptually, each process is
203 free to use the entire space of user virtual memory however it
204 chooses.  When the kernel switches from one process to another, it
205 also switches user virtual address spaces by switching the processor's
206 page directory base register (see @code{pagedir_activate() in
207 @file{userprog/pagedir.c}}.
208
209 Kernel virtual memory is global.  It is always mapped the same way,
210 regardless of what user process or kernel thread is running.  In
211 Pintos, kernel virtual memory is mapped one-to-one to physical
212 memory.  That is, virtual address @code{PHYS_ADDR} accesses physical
213 address 0, virtual address @code{PHYS_ADDR} + @t{0x1234} access
214 physical address @t{0x1234}, and so on up to the size of the machine's
215 physical memory.
216
217 User programs can only access user virtual memory.  An attempt to
218 access kernel virtual memory will cause a page fault, handled by
219 @code{page_fault()} in @file{userprog/exception.c}, and the process
220 will be terminated.  Kernel threads can access both kernel virtual
221 memory and, if a user process is running, the user virtual memory of
222 the running process.  However, even in the kernel, an attempt to
223 access memory at a user virtual address that doesn't have a page
224 mapped into it will cause a page fault.
225
226 @node Global Requirements
227 @section Global Requirements
228
229 For testing and grading purposes, we have some simple requirements for
230 your output.  The kernel should print out the program's name and exit
231 status whenever a process exits, e.g.@: @code{shell: exit(-1)}.  Aside
232 from this, it should print out no other messages.  You may understand
233 all those debug messages, but we won't, and it just clutters our
234 ability to see the stuff we care about.
235
236 Additionally, while it may be useful to hard-code which process will
237 run at startup while debugging, before you submit your code you must
238 make sure that it takes the start-up process name and arguments from
239 the @samp{-ex} argument.  For example, running @code{pintos run -ex
240 "testprogram 1 2 3 4"} will spawn @samp{testprogram 1 2 3 4} as the
241 first process.
242
243 @node Problem 2-1 Argument Passing
244 @section Problem 2-1: Argument Passing
245
246 Currently, @code{process_execute()} does not support passing arguments
247 to new processes.  UNIX and other operating systems do allow passing
248 command line arguments to a program, which accesses them via the argc,
249 argv arguments to main.  You must implement this functionality by
250 extending @code{process_execute()} so that instead of simply taking a
251 program file name, it can take a program name with arguments as a
252 single string.  That is, @code{process_execute("grep foo *.c")} should
253 be a legal call.  @xref{80x86 Calling Convention}, for information on
254 exactly how this works.
255
256 @strong{This functionality is extremely important.}  Almost all our
257 test cases rely on being able to pass arguments, so if you don't get
258 this right, a lot of things will not appear to work correctly with our
259 tests.  If the tests fail, so do you.  Fortunately, this part
260 shouldn't be too hard.
261
262 @node Problem 2-2 System Calls
263 @section Problem 2-2: System Calls
264
265 Implement the system call handler in @file{userprog/syscall.c} to
266 properly deal with all the system calls described below.  Currently,
267 it ``handles'' system calls by terminating the process.  You will need
268 to decipher system call arguments and take the appropriate action for
269 each.
270
271 You are required to support the following system calls, whose syscall
272 numbers are defined in @file{lib/syscall-nr.h} and whose C functions
273 called by user programs are prototyped in @file{lib/user/syscall.h}:
274
275 @table @code
276 @item SYS_halt
277 @itemx void halt (void)
278 Stops Pintos and prints out performance statistics.  Note that this
279 should be seldom used, since then you lose some information about
280 possible deadlock situations, etc.
281
282 @item SYS_exit
283 @itemx void exit (int @var{status})
284 Terminates the current user program, returning @var{status} to the
285 kernel.  A @var{status} of 0 indicates a successful exit.  Other
286 values may be used to indicate user-defined error conditions.
287
288 @item SYS_exec
289 @itemx pid_t exec (const char *@var{file})
290 Run the executable in @var{file} and return the new process's program
291 id (pid).  If there is an error loading this program, returns pid -1,
292 which otherwise should not be a valid id number.
293
294 @item SYS_join
295 @itemx int join (pid_t @var{pid})
296 Joins the process @var{pid}, using the join rules from the last
297 assignment, and returns the process's exit status.  If the process was
298 terminated by the kernel (i.e.@: killed due to an exception), the exit
299 status should be -1.  If the process was not a child of the calling
300 process, the return value is undefined (but kernel operation must not
301 be disrupted).
302
303 @item SYS_create
304 @itemx bool create (const char *@var{file})
305 Create a new file called @var{file}.  Returns -1 if failed, 0 if OK.
306
307 @item SYS_remove
308 @itemx bool remove (const char *@var{file})
309 Delete the file called @var{file}.  Returns -1 if failed, 0 if OK.
310
311 @item SYS_open
312 @itemx int open (const char *@var{file})
313 Open the file called @var{file}.  Returns a nonnegative integer handle
314 called a ``file descriptor'' (fd), or -1 if the file could not be
315 opened.  File descriptors numbered 0 and 1 are reserved for the
316 console.  All open files associated with a process should be closed
317 when the process exits or is terminated.
318
319 @item SYS_filesize
320 @itemx int filesize (int @var{fd})
321 Returns the size, in bytes, of the file open as @var{fd}, or -1 if the
322 file is invalid.
323
324 @item SYS_read
325 @itemx int read (int @var{fd}, void *@var{buffer}, unsigned @var{size})
326 Read @var{size} bytes from the file open as @var{fd} into
327 @var{buffer}.  Returns the number of bytes actually read, or -1 if the
328 file could not be read.
329
330 @item SYS_write
331 @itemx int write (int @var{fd}, const void *@var{buffer}, unsigned @var{size})
332 Write @var{size} bytes from @var{buffer} to the open file @var{fd}.
333 Returns the number of bytes actually written, or -1 if the file could
334 not be written.
335
336 @item SYS_seek
337 @itemx void seek (int @var{fd}, unsigned @var{position})
338 Changes the next byte to be read or written in open file @var{fd} to
339 @var{position}, expressed in bytes from the beginning of the file.
340 (Thus, a @var{position} of 0 is the file's start.)
341
342 @item SYS_tell
343 @itemx unsigned tell (int @var{fd})
344 Returns the position of the next byte to be read or written in open
345 file @var{fd}, expressed in bytes from the beginning of the file.
346
347 @item SYS_close
348 @itemx void close (int @var{fd})
349 Close file descriptor @var{fd}.
350 @end table
351
352 The file defines other syscalls.  Ignore them for now.  You will
353 implement some of them in project 3 and the rest in project 4, so be
354 sure to design your system with extensibility in mind.
355
356 To implement syscalls, you will need to provide a way of copying data
357 from the user's virtual address space into the kernel and vice versa.
358 This can be a bit tricky: what if the user provides an invalid
359 pointer, a pointer into kernel memory, or points to a block that is
360 partially in one of those regions?  You should handle these cases by
361 terminating the user process.  You will need this code before you can
362 even obtain the system call number, because the system call number is
363 on the user's stack in the user's virtual address space.  We recommend
364 writing and testing this code before implementing any other system
365 call functionality.
366
367 You must make sure that system calls are properly synchronized so that
368 any number of user processes can make them at once.  In particular, it
369 is not safe to call into the filesystem code provided in the
370 @file{filesys} directory from multiple threads at once.  For now, we
371 recommend adding a single lock that controls access to the filesystem
372 code.  You should acquire this lock before calling any functions in
373 the @file{filesys} directory, and release it afterward.  Don't forget
374 that @file{process_execute()} also accesses files.  @strong{For now, we
375 recommend against modifying code in the @file{filesys} directory.}
376
377 We have provided you a function for each system call in
378 @file{lib/user/syscall.c}.  These provide a way for user processes to
379 invoke each system call from a C program.  Each of them calls an
380 assembly language routine in @file{lib/user/syscall-stub.S}, which in
381 turn invokes the system call interrupt and returns.
382
383 When you're done with this part, and forevermore, Pintos should be
384 bulletproof.  Nothing that a user program can do should ever cause the
385 OS to crash, halt, assert fail, or otherwise stop running.  The sole
386 exception is a call to the @code{halt} system call.
387
388 @xref{System Calls}, for more information on how syscalls work.
389
390 @node User Programs FAQ
391 @section FAQ
392
393 @enumerate 1
394 @item General FAQs
395
396 @enumerate 1
397 @item
398 @b{Do we need a working project 1 to implement project 2?}
399
400 You may find the code for @code{thread_join()} to be useful in
401 implementing the join syscall, but besides that, you can use
402 the original code provided for project 1.
403
404 @item
405 @b{Is there a way I can disassemble user programs?}
406
407 The @command{i386-elf-objdump} utility can disassemble entire user
408 programs or object files.  Invoke it as @code{i386-elf-objdump -d
409 @var{file}}.  You can also use @code{i386-elf-gdb}'s
410 @command{disassemble} command to disassemble individual functions in
411 object files compiled with debug information.
412
413 @item
414 @b{Why can't I use many C include files in my Pintos programs?}
415
416 The C library we provide is very limited.  It does not include many of
417 the features that are expected of a real operating system's C library.
418 The C library must be built specifically for the operating system (and
419 architecture), since it must make system calls for I/O and memory
420 allocation.  (Not all functions do, of course, but usually the library
421 is compiled as a unit.)  If you wish to port libraries to Pintos, feel
422 free.
423
424 @item
425 @b{How do I compile new user programs? How do I make 'echo' compile?}
426
427 You need to modify @file{tests/Makefile}.
428
429 @item
430 @b{What's the difference between @code{tid_t} and @code{pid_t}?}
431
432 A @code{tid_t} identifies a kernel thread, which may have a user
433 process running in it (if created with @code{process_execute()}) or not
434 (if created with @code{thread_create()}).  It is a data type used only
435 in the kernel.
436
437 A @code{pid_t} identifies a user process.  It is used by user
438 processes and the kernel in the @code{exec} and @code{join} system
439 calls.
440
441 You can choose whatever suitable types you like for @code{tid_t} and
442 @code{pid_t}.  By default, they're both @code{int}.  You can make them
443 a one-to-one mapping, so that the same values in both identify the
444 same process, or you can use a more complex mapping.  It's up to you.
445
446 @item
447 @b{I can't seem to figure out how to read from and write to user
448 memory. What should I do?}
449
450 The kernel must treat user memory delicately.  As part of a system
451 call, the user can pass to the kernel a null pointer, a pointer to
452 unmapped virtual memory, or a pointer to kernel virtual address space
453 (above @code{PHYS_BASE}).  All of these types of invalid pointers must
454 be rejected without harm to the kernel or other running processes.  At
455 your option, the kernel may handle invalid pointers by terminating the
456 process or returning from the system call with an error.
457
458 There are at least two reasonable ways to do this correctly.  The
459 first method is to ``verify then access'':@footnote{These terms are
460 made up for this document.  They are not standard terminology.} verify
461 the validity of a user-provided pointer, then dereference it.  If you
462 choose this route, you'll want to look at the functions in
463 @file{userprog/pagedir.c} and in @file{threads/mmu.h}.  This is the
464 simplest way to handle user memory access.
465
466 The second method is to ``assume and react'': directly dereference
467 user pointers, after checking that they point below @code{PHYS_BASE}.
468 Invalid user pointers will then cause a ``page fault'' that you can
469 handle by modifying the code for @code{page_fault()} in
470 @file{userprog/exception.cc}.  This technique is normally faster
471 because it takes advantage of the processor's MMU, so it tends to be
472 used in real kernels (including Linux).
473
474 In either case, you need to make sure not to ``leak'' resources.  For
475 example, suppose that your system call has acquired a lock or
476 allocated a page of memory.  If you encounter an invalid user pointer
477 afterward, you must still be sure to release the lock or free the page
478 of memory.  If you choose to ``verify then access,'' then this should
479 be straightforward, but for ``assume and react'' it's more difficult,
480 because there's no way to return an error code from a memory access.
481 Therefore, for those who want to try the latter technique, we'll
482 provide a little bit of helpful code:
483
484 @example
485 /* Tries to copy a byte from user address USRC to kernel address DST.
486    Returns true if successful, false if USRC is invalid. */
487 static inline bool get_user (uint8_t *dst, const uint8_t *usrc) @{
488   int eax;
489   asm ("movl $1f, %%eax; movb %2, %%al; movb %%al, %0; 1:"
490        : "=m" (*dst), "=&a" (eax) : "m" (*usrc));
491   return eax != 0;
492 @}
493
494 /* Tries write BYTE to user address UDST.
495    Returns true if successful, false if UDST is invalid. */
496 static inline bool put_user (uint8_t *udst, uint8_t byte) @{
497   int eax;
498   asm ("movl $1f, %%eax; movb %b2, %0; 1:"
499        : "=m" (*udst), "=&a" (eax) : "r" (byte));
500   return eax != 0;
501 @}
502 @end example
503
504 Each of these functions assumes that the user address has already been
505 verified to be below @code{PHYS_BASE}.  They also assume that you've
506 modified @code{page_fault()} so that a page fault in the kernel causes
507 @code{eax} to be set to 0 and its former value copied into @code{eip}.
508
509 @item
510 @b{I'm also confused about reading from and writing to the stack. Can
511 you help?}
512
513 @itemize @bullet
514 @item
515 Only non-@samp{char} values will have issues when writing them to
516 memory.  If a digit is in a string, it is considered a character.
517 However, the value of @code{argc} would be a non-char.
518
519 @item
520 You will need to write characters and non-characters into main memory.
521
522 @item
523 When you add items to the stack, you will be decrementing the stack
524 pointer.  You'll need to decrement the stack pointer before writing to
525 the location.
526
527 @item
528 Each character is 1 byte.
529 @end itemize
530
531 @item
532 @b{Why doesn't keyboard input work with @option{-v}?}
533
534 Serial input isn't implemented.  Don't use @option{-v} if you want to
535 use the shell or otherwise type at the keyboard.
536 @end enumerate
537
538 @item Argument Passing FAQs
539
540 @enumerate 1
541 @item
542 @b{What will be the format of command line arguments?}
543
544 You should assume that command line arguments are delimited by white
545 space.
546
547 @item
548 @b{What is the maximum length of the command line arguments?}
549
550 You can impose some reasonable maximum as long as you're prepared to
551 defend it in your @file{DESIGNDOC}.
552
553 @item
554 @b{How do I parse all these argument strings?}
555
556 You're welcome to use any technique you please, as long as it works.
557 If you're lost, look at @code{strtok_r()}, prototyped in
558 @file{lib/string.h} and implemented with thorough comments in
559 @file{lib/string.c}.  You can find more about it by looking at the man
560 page (run @code{man strtok_r} at the prompt).
561
562 @item
563 @b{Why is the top of the stack at @t{0xc0000000}?  Isn't that off the
564 top of user virtual memory?  Shouldn't it be @t{0xbfffffff}?}
565
566 When the processor pushes data on the stack, it decrements the stack
567 pointer first.  Thus, the first (4-byte) value pushed on the stack
568 will be at address @t{0xbffffffc}.
569
570 Also, the stack should always be aligned to a 4-byte boundary, but
571 @t{0xbfffffff} isn't.
572
573 @item
574 @b{Is @code{PHYS_BASE} fixed?}
575
576 No.  You should be able to support @code{PHYS_BASE} values that are
577 any multiple of @t{0x10000000} from @t{0x80000000} to @t{0xc0000000},
578 simply via recompilation.
579 @end enumerate
580
581 @item System Calls FAQs
582
583 @enumerate 1
584 @item
585 @b{What should I do with the parameter passed to @code{exit()}?}
586
587 This value, the exit status of the process, must be returned to the
588 thread's parent when @code{join()} is called.
589
590 @item
591 @b{Can I just cast a pointer to a @code{struct file} object to get a
592 unique file descriptor?  Can I just cast a @code{struct thread *} to a
593 @code{pid_t}?  It's so much simpler that way!}
594
595 This is a design decision you will have to make for yourself.
596 However, note that most operating systems do distinguish between file
597 descriptors (or pids) and the addresses of their kernel data
598 structures.  You might want to give some thought as to why they do so
599 before committing yourself.
600
601 @item
602 @b{Can I set a maximum number of open files per process?}
603
604 From a design standpoint, it would be better not to set an arbitrary
605 maximum.  That said, if your design calls for it, you may impose a
606 limit of 128 open files per process (as the Solaris machines here do).
607
608 @item
609 @b{What happens when two (or more) processes have a file open and one of
610 them removes it?}
611
612 You should copy the standard Unix semantics for files.  That is, when
613 a file is removed an process which has a file descriptor for that file
614 may continue to do operations on that descriptor.  This means that
615 they can read and write from the file.  The file will not have a name,
616 and no other processes will be able to open it, but it will continue
617 to exist until all file descriptors referring to the file are closed
618 or the machine shuts down.
619
620 @item
621 @b{What happens if a system call is passed an invalid argument, such
622 as Open being called with an invalid filename?}
623
624 Pintos should not crash.  Acceptable options include returning an
625 error value (for those calls that return a value), returning an
626 undefined value, or terminating the process.
627
628 @item
629 @b{I've discovered that some of my user programs need more than one 4
630 kB page of stack space.  What should I do?}
631
632 You may modify the stack setup code to allocate more than one page of
633 stack space for each process.
634
635 @item
636 @b{What do I need to print on thread completion?}
637
638 You should print the complete thread name (as specified in the
639 @code{SYS_exec} call) followed by the exit status code,
640 e.g.@: @samp{example 1 2 3 4: 0}.
641 @end enumerate
642 @end enumerate
643
644 @node 80x86 Calling Convention
645 @section 80@var{x}86 Calling Convention
646
647 What follows is a quick and dirty discussion of the 80@var{x}86
648 calling convention.  Some of the basics should be familiar from CS
649 107, and if you've already taken CS 143 or EE 182, then you should
650 have seen even more of it.  I've omitted some of the complexity, since
651 this isn't a class in how function calls work, so don't expect this to
652 be exactly correct in full, gory detail.  If you do want all the
653 details, you can refer to @cite{[SysV-i386]}.
654
655 Whenever a function call happens, you need to put the arguments on the
656 call stack for that function, before the code for that function
657 executes, so that the callee has access to those values.  The caller
658 has to be responsible for this (be sure you understand why).
659 Therefore, when you compile a program, the assembly code emitted will
660 have in it, before every function call, a bunch of instructions that
661 prepares for the call in whatever manner is conventional for the
662 machine you're working on.  This includes saving registers as needed,
663 putting stuff on the stack, saving the location to return to somewhere
664 (so that when the callee finishes, it knows where the caller code is),
665 and some other bookkeeping stuff.  Then you do the jump to the
666 callee's code, and it goes along, assuming that the stack and
667 registers are prepared in the appropriate manner.  When the callee is
668 done, it looks at the return location as saved earlier, and jumps back
669 to that location.  The caller may then have to do some cleanup:
670 clearing arguments and the return value off the stack, restoring
671 registers that were saved before the call, and so on.
672
673 If you think about it, some of these things should remind you of
674 context switching.
675
676 As an aside, in general, function calls are not cheap.  You have to do
677 a bunch of memory writes to prepare the stack, you need to save and
678 restore registers before and after a function call, you need to write
679 the stack pointer, you have a couple of jumps which probably wrecks
680 some of your caches.  This is why inlining code can be much faster.
681
682 @menu
683 * Argument Passing to main::    
684 @end menu
685
686 @node Argument Passing to main
687 @subsection Argument Passing to @code{main()}
688
689 In @code{main()}'s case, there is no caller to prepare the stack
690 before it runs.  Therefore, the kernel needs to do it.  Fortunately,
691 since there's no caller, there are no registers to save, no return
692 address to deal with, etc.  The only difficult detail to take care of,
693 after loading the code, is putting the arguments to @code{main()} on
694 the stack.
695
696 (The above is a small lie: most compilers will emit code where main
697 isn't strictly speaking the first function.  This isn't an important
698 detail.  If you want to look into it more, try disassembling a program
699 and looking around a bit.  However, you can just act as if
700 @code{main()} is the very first function called.)
701
702 Pintos is written for the 80@var{x}86 architecture.  Therefore, we
703 need to adhere to the 80@var{x}86 calling convention.  Basically, you
704 put all the arguments on the stack and move the stack pointer
705 appropriately.  You also need to insert space for the function's
706 ``return address'': even though the initial function doesn't really
707 have a caller, its stack frame must have the same layout as any other
708 function's.  The program will assume that the stack has been laid out
709 this way when it begins running.
710
711 So, what are the arguments to @code{main()}? Just two: an @samp{int}
712 (@code{argc}) and a @samp{char **} (@code{argv}).  @code{argv} is an
713 array of strings, and @code{argc} is the number of strings in that
714 array.  However, the hard part isn't these two things.  The hard part
715 is getting all the individual strings in the right place.  As we go
716 through the procedure, let us consider the following example command:
717 @samp{/bin/ls -l *.h *.c}.
718
719 The first thing to do is to break the command line into individual
720 strings: @samp{/bin/ls}, @samp{-l}, @samp{*.h}, and @samp{*.c}.  These
721 constitute the arguments of the command, including the program name
722 itself (which belongs in @code{argv[0]}).
723
724 These individual, null-terminated strings should be placed on the user
725 stack.  They may be placed in any order, as you'll see shortly,
726 without affecting how main works, but for simplicity let's assume they
727 are in reverse order (keeping in mind that the stack grows downward on
728 an 80@var{x}86 machine).  As we copy the strings onto the stack, we
729 record their (virtual) stack addresses.  These addresses will become
730 important when we write the argument vector (two paragraphs down).
731
732 After we push all of the strings onto the stack, we adjust the stack
733 pointer so that it is word-aligned: that is, we move it down to the
734 next 4-byte boundary.  This is required because we will next be
735 placing several words of data on the stack, and they must be aligned
736 in order to be read correctly.  In our example, as you'll see below,
737 the strings start at address @t{0xffed}.  One word below that would be
738 at @t{0xffe9}, so we could in theory put the next word on the stack
739 there.  However, since the stack pointer should always be
740 word-aligned, we instead leave the stack pointer at @t{0xffe8}.
741
742 Once we align the stack pointer, we then push the elements of the
743 argument vector, that is, a null pointer, then the addresses of the
744 strings @samp{/bin/ls}, @samp{-l}, @samp{*.h}, and @samp{*.c}) onto
745 the stack.  This must be done in reverse order, such that
746 @code{argv[0]} is at the lowest virtual address, again because the
747 stack is growing downward.  (The null pointer pushed first is because
748 @code{argv[argc]} must be a null pointer.)  This is because we are now
749 writing the actual array of strings; if we write them in the wrong
750 order, then the strings will be in the wrong order in the array.  This
751 is also why, strictly speaking, it doesn't matter what order the
752 strings themselves are placed on the stack: as long as the pointers
753 are in the right order, the strings themselves can really be anywhere.
754 After we finish, we note the stack address of the first element of the
755 argument vector, which is @code{argv} itself.
756
757 Then we push @code{argv} (that is, the address of the first element of
758 the @code{argv} array) onto the stack, along with the length of the
759 argument vector (@code{argc}, 4 in this example).  This must also be
760 done in this order, since @code{argc} is the first argument to
761 @code{main()} and therefore is on first (smaller address) on the
762 stack.  Finally, we push a fake ``return address'' and leave the stack
763 pointer to point to its location.
764
765 All this may sound very confusing, so here's a picture which will
766 hopefully clarify what's going on. This represents the state of the
767 stack and the relevant registers right before the beginning of the
768 user program (assuming for this example that the stack bottom is
769 @t{0xc0000000}):
770
771 @html
772 <CENTER>
773 @end html
774 @multitable {@t{0xbfffffff}} {``return address''} {@t{/bin/ls\0}}
775 @item Address @tab Name @tab Data
776 @item @t{0xbffffffc} @tab @code{*argv[3]} @tab @samp{*.c\0}
777 @item @t{0xbffffff8} @tab @code{*argv[2]} @tab @samp{*.h\0}
778 @item @t{0xbffffff5} @tab @code{*argv[1]} @tab @samp{-l\0}
779 @item @t{0xbfffffed} @tab @code{*argv[0]} @tab @samp{/bin/ls\0}
780 @item @t{0xbfffffec} @tab word-align @tab @samp{\0}
781 @item @t{0xbfffffe8} @tab @code{argv[4]} @tab @t{0}
782 @item @t{0xbfffffe4} @tab @code{argv[3]} @tab @t{0xbffffffc}
783 @item @t{0xbfffffe0} @tab @code{argv[2]} @tab @t{0xbffffff8}
784 @item @t{0xbfffffdc} @tab @code{argv[1]} @tab @t{0xbffffff5}
785 @item @t{0xbfffffd8} @tab @code{argv[0]} @tab @t{0xbfffffed}
786 @item @t{0xbfffffd4} @tab @code{argv} @tab @t{0xbffffffd8}
787 @item @t{0xbfffffd0} @tab @code{argc} @tab 4
788 @item @t{0xbfffffcc} @tab ``return address'' @tab 0
789 @end multitable
790 @html
791 </CENTER>
792 @end html
793
794 In this example, the stack pointer would be initialized to
795 @t{0xbfffffcc}.
796
797 As shown above, your code should start the stack at the very top of
798 the user virtual address space, in the page just below virtual address
799 @code{PHYS_BASE} (defined in @file{threads/mmu.h}).
800
801 You may find the non-standard @code{hex_dump()} function, declared in
802 @file{<stdio.h>}, useful for debugging your argument passing code.
803 Here's what it would show in the above example, given that
804 @code{PHYS_BASE} is @t{0xc0000000}:
805
806 @example
807 bfffffc0                                      00 00 00 00 |            ....|
808 bfffffd0  04 00 00 00 d8 ff ff bf-ed ff ff bf f5 ff ff bf |................|
809 bfffffe0  f8 ff ff bf fc ff ff bf-00 00 00 00 00 2f 62 69 |............./bi|
810 bffffff0  6e 2f 6c 73 00 2d 6c 00-2a 2e 68 00 2a 2e 63 00 |n/ls.-l.*.h.*.c.|
811 @end example
812
813 @node System Calls
814 @section System Calls
815
816 We have already been dealing with one way that the operating system
817 can regain control from a user program: interrupts from timers and I/O
818 devices.  These are ``external'' interrupts, because they are caused
819 by entities outside the CPU.
820
821 The operating system is also called to deal with software exceptions,
822 which are events generated in response to the code.  These can be
823 errors such as a page fault or division by zero.  However, exceptions
824 are also the means by which a user program can request services
825 (``system calls'') from the operating system.
826
827 In the 80@var{x}86 architecture, the @samp{int} instruction is the
828 most commonly used means for invoking system calls.  This instruction
829 is handled in the same way as other software exceptions.  In Pintos,
830 user programs invoke @samp{int $0x30} to make a system call.  The
831 system call number and any additional arguments are expected to be
832 pushed on the stack in the normal fashion before invoking the
833 interrupt.
834
835 The normal calling convention pushes function arguments on the stack
836 from right to left and the stack grows downward.  Thus, when the
837 system call handler @code{syscall_handler()} gets control, the system
838 call number is in the 32-bit word at the caller's stack pointer, the
839 first argument is in the 32-bit word at the next higher address, and
840 so on.  The caller's stack pointer is accessible to
841 @code{syscall_handler()} as the @samp{esp} member of the @code{struct
842 intr_frame} passed to it.
843
844 Here's an example stack frame for calling a system call numbered 10
845 with three arguments passed as 1, 2, and 3.  The stack addresses are
846 arbitrary:
847
848 @html
849 <CENTER>
850 @end html
851 @multitable {Address} {Value}
852 @item Address @tab Value
853 @item @t{0xbffffe7c} @tab 3
854 @item @t{0xbffffe78} @tab 2
855 @item @t{0xbffffe74} @tab 1
856 @item @t{0xbffffe70} @tab 10
857 @end multitable
858 @html
859 </CENTER>
860 @end html
861
862 In this example, the caller's stack pointer would be at
863 @t{0xbffffe70}.
864
865 The 80@var{x}86 convention for function return values is to place them
866 in the @samp{EAX} register.  System calls that return a value can do
867 so by modifying the @samp{eax} member of @code{struct intr_frame}.