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