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