2574c31d7d91737c7f57194ed2571544bd21a039
[pintos-anon] / src / userprog / addrspace.c
1 #include "addrspace.h"
2 #include <inttypes.h>
3 #include "debug.h"
4 #include "file.h"
5 #include "filesys.h"
6 #include "init.h"
7 #include "lib.h"
8 #include "mmu.h"
9 #include "paging.h"
10 #include "palloc.h"
11 #include "thread.h"
12 #include "tss.h"
13
14 /* We load ELF binaries.  The following definitions are taken
15    from the ELF specification, [ELF1], more-or-less verbatim.  */
16
17 /* ELF types.  See [ELF1] 1-2. */
18 typedef uint32_t Elf32_Word, Elf32_Addr, Elf32_Off;
19 typedef uint16_t Elf32_Half;
20
21 /* For use with ELF types in printk(). */
22 #define PE32Wx PRIx32   /* Print Elf32_Word in hexadecimal. */
23 #define PE32Ax PRIx32   /* Print Elf32_Addr in hexadecimal. */
24 #define PE32Ox PRIx32   /* Print Elf32_Off in hexadecimal. */
25 #define PE32Hx PRIx16   /* Print Elf32_Half in hexadecimal. */
26
27 /* Executable header.  See [ELF1] 1-4 to 1-8.
28    This appears at the very beginning of an ELF binary. */
29 struct Elf32_Ehdr
30   {
31     unsigned char e_ident[16];
32     Elf32_Half    e_type;
33     Elf32_Half    e_machine;
34     Elf32_Word    e_version;
35     Elf32_Addr    e_entry;
36     Elf32_Off     e_phoff;
37     Elf32_Off     e_shoff;
38     Elf32_Word    e_flags;
39     Elf32_Half    e_ehsize;
40     Elf32_Half    e_phentsize;
41     Elf32_Half    e_phnum;
42     Elf32_Half    e_shentsize;
43     Elf32_Half    e_shnum;
44     Elf32_Half    e_shstrndx;
45   };
46
47 /* Program header.  See [ELF1] 2-2 to 2-4.
48    There are e_phnum of these, starting at file offset e_phoff
49    (see [ELF1] 1-6). */
50 struct Elf32_Phdr
51   {
52     Elf32_Word p_type;
53     Elf32_Off  p_offset;
54     Elf32_Addr p_vaddr;
55     Elf32_Addr p_paddr;
56     Elf32_Word p_filesz;
57     Elf32_Word p_memsz;
58     Elf32_Word p_flags;
59     Elf32_Word p_align;
60   };
61
62 /* Values for p_type.  See [ELF1] 2-3. */
63 #define PT_NULL    0            /* Ignore. */
64 #define PT_LOAD    1            /* Loadable segment. */
65 #define PT_DYNAMIC 2            /* Dynamic linking info. */
66 #define PT_INTERP  3            /* Name of dynamic loader. */
67 #define PT_NOTE    4            /* Auxiliary info. */
68 #define PT_SHLIB   5            /* Reserved. */
69 #define PT_PHDR    6            /* Program header table. */
70 #define PT_STACK   0x6474e551   /* Stack segment. */
71
72 /* Flags for p_flags.  See [ELF3] 2-3 and 2-4. */
73 #define PF_X 1          /* Executable. */
74 #define PF_W 2          /* Writable. */
75 #define PF_R 4          /* Readable. */
76
77 static bool load_segment (struct thread *, struct file *,
78                           const struct Elf32_Phdr *);
79 static bool setup_stack (struct thread *);
80
81 /* Aborts loading an executable, with an error message. */
82 #define LOAD_ERROR(MSG)                                         \
83         do {                                                    \
84                 printk ("addrspace_load: %s: ", filename);      \
85                 printk MSG;                                     \
86                 printk ("\n");                                  \
87                 goto done;                                     \
88         } while (0)
89
90 /* Loads an ELF executable from FILENAME into T,
91    and stores the executable's entry point into *START.
92    Returns true if successful, false otherwise. */
93 bool
94 addrspace_load (struct thread *t, const char *filename, void (**start) (void)) 
95 {
96   struct Elf32_Ehdr ehdr;
97   struct file file;
98   bool file_open = false;
99   off_t file_ofs;
100   bool success = false;
101   int i;
102
103   /* Allocate page directory. */
104   t->pagedir = pagedir_create ();
105   if (t->pagedir == NULL)
106     LOAD_ERROR (("page directory allocation failed"));
107
108   /* Open executable file. */
109   file_open = filesys_open (filename, &file);
110   if (!file_open)
111     LOAD_ERROR (("open failed"));
112
113   /* Read and verify executable header. */
114   if (file_read (&file, &ehdr, sizeof ehdr) != sizeof ehdr) 
115     LOAD_ERROR (("error reading executable header"));
116   if (memcmp (ehdr.e_ident, "\177ELF\1\1\1", 7) != 0)
117     LOAD_ERROR (("file is not ELF"));
118   if (ehdr.e_type != 2)
119     LOAD_ERROR (("ELF file is not an executable"));
120   if (ehdr.e_machine != 3)
121     LOAD_ERROR (("ELF executable is not x86"));
122   if (ehdr.e_version != 1)
123     LOAD_ERROR (("ELF executable hasunknown version %d",
124                  (int) ehdr.e_version));
125   if (ehdr.e_phentsize != sizeof (struct Elf32_Phdr))
126     LOAD_ERROR (("bad ELF program header size"));
127   if (ehdr.e_phnum > 1024)
128     LOAD_ERROR (("too many ELF program headers"));
129
130   /* Read program headers. */
131   file_ofs = ehdr.e_phoff;
132   for (i = 0; i < ehdr.e_phnum; i++) 
133     {
134       struct Elf32_Phdr phdr;
135
136       file_seek (&file, file_ofs);
137       if (file_read (&file, &phdr, sizeof phdr) != sizeof phdr)
138         LOAD_ERROR (("error reading program header"));
139       file_ofs += sizeof phdr;
140       switch (phdr.p_type) 
141         {
142         case PT_NULL:
143         case PT_NOTE:
144         case PT_PHDR:
145         case PT_STACK:
146           /* Ignore this segment. */
147           break;
148         case PT_DYNAMIC:
149         case PT_INTERP:
150         case PT_SHLIB:
151           /* Reject the executable. */
152           LOAD_ERROR (("unsupported ELF segment type %d\n", phdr.p_type));
153           break;
154         default:
155           printk ("unknown ELF segment type %08x\n", phdr.p_type);
156           break;
157         case PT_LOAD:
158           if (!load_segment (t, &file, &phdr))
159             goto done;
160           break;
161         }
162     }
163
164   /* Set up stack. */
165   if (!setup_stack (t))
166     goto done;
167
168   /* Start address. */
169   *start = (void (*) (void)) ehdr.e_entry;
170
171   success = true;
172
173  done:
174   /* We arrive here whether the load is successful or not.
175      We can distinguish based on `success'. */
176   if (file_open)
177     file_close (&file);
178   if (!success) 
179     addrspace_destroy (t);
180   return success;
181 }
182
183 /* Destroys the user address space in T and frees all of its
184    resources. */
185 void
186 addrspace_destroy (struct thread *t)
187 {
188   if (t->pagedir != NULL) 
189     {
190       pagedir_destroy (t->pagedir);
191       t->pagedir = NULL; 
192     }
193 }
194
195 /* Sets up the CPU for running user code in thread T, if any. */
196 void
197 addrspace_activate (struct thread *t)
198 {
199   ASSERT (t != NULL);
200
201   /* Activate T's page tables. */
202   pagedir_activate (t->pagedir);
203
204   /* Set T's kernel stack for use in processing interrupts. */
205   tss_set_esp0 ((uint8_t *) t + PGSIZE);
206 }
207 \f
208 /* addrspace_load() helpers. */
209
210 static bool install_page (struct thread *, void *upage, void *kpage);
211
212 /* Loads the segment described by PHDR from FILE into thread T's
213    user address space.  Return true if successful, false
214    otherwise. */
215 static bool
216 load_segment (struct thread *t, struct file *file,
217               const struct Elf32_Phdr *phdr) 
218 {
219   void *start, *end;  /* Page-rounded segment start and end. */
220   uint8_t *upage;     /* Iterator from start to end. */
221   off_t filesz_left;  /* Bytes left of file data (as opposed to
222                          zero-initialized bytes). */
223
224   ASSERT (t != NULL);
225   ASSERT (file != NULL);
226   ASSERT (phdr != NULL);
227   ASSERT (phdr->p_type == PT_LOAD);
228
229   /* [ELF1] 2-2 says that p_offset and p_vaddr must be congruent
230      modulo PGSIZE. */
231   if (phdr->p_offset % PGSIZE != phdr->p_vaddr % PGSIZE) 
232     {
233       printk ("%#08"PE32Ox" and %#08"PE32Ax" not congruent modulo %#x\n",
234               phdr->p_offset, phdr->p_vaddr, (unsigned) PGSIZE);
235       return false; 
236     }
237
238   /* [ELF1] 2-3 says that p_memsz must be at least as big as
239      p_filesz. */
240   if (phdr->p_memsz < phdr->p_filesz) 
241     {
242       printk ("p_memsz (%08"PE32Wx") < p_filesz (%08"PE32Wx")\n",
243               phdr->p_memsz, phdr->p_filesz);
244       return false; 
245     }
246
247   /* Validate virtual memory region to be mapped.
248      The region must both start and end within the user address
249      space range starting at 0 and ending at PHYS_BASE (typically
250      3 GB == 0xc0000000). */
251   start = pg_round_down ((void *) phdr->p_vaddr);
252   end = pg_round_up ((void *) (phdr->p_vaddr + phdr->p_memsz));
253   if (start >= PHYS_BASE || end >= PHYS_BASE || end < start) 
254     {
255       printk ("bad virtual region %08lx...%08lx\n",
256               (unsigned long) start, (unsigned long) end);
257       return false; 
258     }
259
260   /* Load the segment page-by-page into memory. */
261   filesz_left = phdr->p_filesz + (phdr->p_vaddr & PGMASK);
262   file_seek (file, ROUND_DOWN (phdr->p_offset, PGSIZE));
263   for (upage = start; upage < (uint8_t *) end; upage += PGSIZE) 
264     {
265       /* We want to read min(PGSIZE, filesz_left) bytes from the
266          file into the page and zero the rest. */
267       size_t read_bytes = filesz_left >= PGSIZE ? PGSIZE : filesz_left;
268       size_t zero_bytes = PGSIZE - read_bytes;
269       uint8_t *kpage = palloc_get (0);
270       if (kpage == NULL)
271         return false;
272
273       /* Do the reading and zeroing. */
274       if (file_read (file, kpage, read_bytes) != (int) read_bytes) 
275         {
276           palloc_free (kpage);
277           return false; 
278         }
279       memset (kpage + read_bytes, 0, zero_bytes);
280       filesz_left -= read_bytes;
281
282       /* Add the page to the process's address space. */
283       if (!install_page (t, upage, kpage)) 
284         {
285           palloc_free (kpage);
286           return false; 
287         }
288     }
289
290   return true;
291 }
292
293 /* Create a minimal stack for T by mapping a zeroed page at the
294    top of user virtual memory. */
295 static bool
296 setup_stack (struct thread *t) 
297 {
298   uint8_t *kpage;
299   bool success = false;
300
301   kpage = palloc_get (PAL_ZERO);
302   if (kpage != NULL) 
303     {
304       success = install_page (t, ((uint8_t *) PHYS_BASE) - PGSIZE, kpage);
305       if (!success)
306         palloc_free (kpage);
307     }
308   else
309     printk ("failed to allocate process stack\n");
310
311   return success;
312 }
313
314 /* Adds a mapping from user virtual address UPAGE to kernel
315    virtual address KPAGE to T's page tables.  Fails if UPAGE is
316    already mapped or if memory allocation fails. */
317 static bool
318 install_page (struct thread *t, void *upage, void *kpage)
319 {
320   /* Verify that there's not already a page at that virtual
321      address, then map our page there. */
322   return (pagedir_get_page (t->pagedir, upage) == NULL
323           && pagedir_set_page (t->pagedir, upage, kpage, true));
324 }