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