Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.63 KB | None | 0 0
  1. #include "userprog/process.h"
  2. #include <debug.h>
  3. #include <inttypes.h>
  4. #include <round.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include "userprog/gdt.h"
  9. #include "userprog/pagedir.h"
  10. #include "userprog/tss.h"
  11. #include "filesys/directory.h"
  12. #include "filesys/file.h"
  13. #include "filesys/filesys.h"
  14. #include "threads/flags.h"
  15. #include "threads/init.h"
  16. #include "threads/interrupt.h"
  17. #include "threads/palloc.h"
  18. #include "threads/thread.h"
  19. #include "threads/vaddr.h"
  20. #include "threads/synch.h"
  21.  
  22. static thread_func start_process NO_RETURN;
  23. static bool load (const char *cmdline, void (**eip) (void), void **esp);
  24. //new declarations
  25. int cmnd_parse(char *,char **);
  26. void add_params_to_stack(char *, void **);
  27. struct thread *get_thread_status (struct thread *t , tid_t tid);
  28. char thread_params_buffer[200];
  29. struct semaphore *toWake;
  30. bool child_succeeded;
  31. //end of new declarations
  32.  
  33.  
  34. /* Starts a new thread running a user program loaded from
  35. FILENAME. The new thread may be scheduled (and may even exit)
  36. before process_execute() returns. Returns the new process's
  37. thread id, or TID_ERROR if the thread cannot be created. */
  38. tid_t
  39. process_execute (const char *file_name)
  40. {
  41. char *fn_copy;
  42. tid_t tid = TID_ERROR;
  43.  
  44. /* Make a copy of params.
  45. Otherwise there's a race between the caller and load(). */
  46. fn_copy = palloc_get_page (0);
  47. if (fn_copy == NULL)
  48. return TID_ERROR;
  49. strlcpy (fn_copy, file_name, PGSIZE);
  50.  
  51. //changes
  52. char *args[200];
  53. cmnd_parse(fn_copy,args);
  54. fn_copy = args[0];
  55.  
  56. /* Saving command line to be used to setup the stack. */
  57. strlcpy(thread_params_buffer, file_name, PGSIZE);
  58. /* Create a new thread to execute FILE_NAME. */
  59. struct thread *cur = thread_current();
  60. tid = thread_create (fn_copy, PRI_DEFAULT, start_process, fn_copy);
  61. /* The current thread is blocked untill the child file gets loaded */
  62. toWake = &cur->sync_sema;
  63. sema_down(&cur->sync_sema);
  64. /* If the child fild is not successfully read then TID_ERROR is returned */
  65. if(!child_succeeded || tid == TID_ERROR){
  66. return TID_ERROR;
  67. }
  68. return tid;
  69.  
  70. }
  71.  
  72. /* A thread function that loads a user process and starts it
  73. running. */
  74. static void
  75. start_process (void *file_name_)
  76. {
  77. char *file_name = file_name_;
  78. struct intr_frame if_;
  79. bool success;
  80.  
  81. /* Initialize interrupt frame and load executable. */
  82. memset (&if_, 0, sizeof if_);
  83. if_.gs = if_.fs = if_.es = if_.ds = if_.ss = SEL_UDSEG;
  84. if_.cs = SEL_UCSEG;
  85. if_.eflags = FLAG_IF | FLAG_MBS;
  86. success = load (file_name, &if_.eip, &if_.esp);
  87. /* Saving whether this thread file is successfully loaded or not */
  88. child_succeeded = success;
  89. /* Wakes up the parent process */
  90. sema_up(toWake);
  91. sema_down(&thread_current()->sync_sema);
  92. /* If load failed, quit. */
  93. palloc_free_page (file_name);
  94. if (!success)
  95. thread_exit ();
  96.  
  97. /* Start the user process by simulating a return from an
  98. interrupt, implemented by intr_exit (in
  99. threads/intr-stubs.S). Because intr_exit takes all of its
  100. arguments on the stack in the form of a `struct intr_frame',
  101. we just point the stack pointer (%esp) to our stack frame
  102. and jump to it. */
  103. asm volatile ("movl %0, %%esp; jmp intr_exit" : : "g" (&if_) : "memory");
  104. NOT_REACHED ();
  105. }
  106.  
  107. struct thread *get_thread_status (struct thread *t , tid_t tid) {
  108. struct thread *ret = NULL;
  109. struct list_elem *e;
  110. for(e = list_begin(&(t->children)); e != list_end(&(t->children));
  111. e = list_next(e)) {
  112. ret = list_entry(e, struct thread, elem);
  113. if(ret != NULL && ret->tid == tid)
  114. return ret;
  115. }
  116. return NULL;
  117. }
  118.  
  119. /* Waits for thread TID to die and returns its exit status. If
  120. it was terminated by the kernel (i.e. killed due to an
  121. exception), returns -1. If TID is invalid or if it was not a
  122. child of the calling process, or if process_wait() has already
  123. been successfully called for the given TID, returns -1
  124. immediately, without waiting.
  125.  
  126. This function will be implemented in problem 2-2. For now, it
  127. does nothing. */
  128. int
  129. process_wait (tid_t child_tid)
  130. {
  131. struct thread *child = get_thread_status(thread_current(), child_tid);
  132.  
  133. if(child == NULL) return -1;
  134.  
  135. sema_up(&(child->sync_sema));
  136.  
  137. thread_current() -> current_waiting = child -> tid;
  138. sema_down(&(thread_current()->sync_sema));
  139.  
  140. return thread_current() -> child_exit_status;
  141. }
  142.  
  143. /* Free the current process's resources. */
  144. void
  145. process_exit (void)
  146. {
  147. struct thread *cur = thread_current ();
  148. uint32_t *pd;
  149.  
  150. if(cur->parent != NULL && cur->parent->current_waiting == cur->tid) {
  151. cur->parent->child_exit_status = cur->exit_status;
  152. sema_up(&((cur->parent)->sync_sema));
  153. }
  154.  
  155. // Allow write to exe
  156. if(cur->exec_file != NULL){
  157. file_allow_write(cur->exec_file);
  158. cur->exec_file = NULL;
  159. file_close(cur->exec_file);
  160. }
  161.  
  162. /* Destroy the current process's page directory and switch back
  163. to the kernel-only page directory. */
  164. pd = cur->pagedir;
  165. if (pd != NULL)
  166. {
  167. /* Correct ordering here is crucial. We must set
  168. cur->pagedir to NULL before switching page directories,
  169. so that a timer interrupt can't switch back to the
  170. process page directory. We must activate the base page
  171. directory before destroying the process's page
  172. directory, or our active page directory will be one
  173. that's been freed (and cleared). */
  174. cur->pagedir = NULL;
  175. pagedir_activate (NULL);
  176. pagedir_destroy (pd);
  177. }
  178. }
  179.  
  180. /* Sets up the CPU for running user code in the current
  181. thread.
  182. This function is called on every context switch. */
  183. void
  184. process_activate (void)
  185. {
  186. struct thread *t = thread_current ();
  187.  
  188. /* Activate thread's page tables. */
  189. pagedir_activate (t->pagedir);
  190.  
  191. /* Set thread's kernel stack for use in processing
  192. interrupts. */
  193. tss_update ();
  194. }
  195.  
  196. /* We load ELF binaries. The following definitions are taken
  197. from the ELF specification, [ELF1], more-or-less verbatim. */
  198.  
  199. /* ELF types. See [ELF1] 1-2. */
  200. typedef uint32_t Elf32_Word, Elf32_Addr, Elf32_Off;
  201. typedef uint16_t Elf32_Half;
  202.  
  203. /* For use with ELF types in printf(). */
  204. #define PE32Wx PRIx32 /* Print Elf32_Word in hexadecimal. */
  205. #define PE32Ax PRIx32 /* Print Elf32_Addr in hexadecimal. */
  206. #define PE32Ox PRIx32 /* Print Elf32_Off in hexadecimal. */
  207. #define PE32Hx PRIx16 /* Print Elf32_Half in hexadecimal. */
  208.  
  209. /* Executable header. See [ELF1] 1-4 to 1-8.
  210. This appears at the very beginning of an ELF binary. */
  211. struct Elf32_Ehdr
  212. {
  213. unsigned char e_ident[16];
  214. Elf32_Half e_type;
  215. Elf32_Half e_machine;
  216. Elf32_Word e_version;
  217. Elf32_Addr e_entry;
  218. Elf32_Off e_phoff;
  219. Elf32_Off e_shoff;
  220. Elf32_Word e_flags;
  221. Elf32_Half e_ehsize;
  222. Elf32_Half e_phentsize;
  223. Elf32_Half e_phnum;
  224. Elf32_Half e_shentsize;
  225. Elf32_Half e_shnum;
  226. Elf32_Half e_shstrndx;
  227. };
  228.  
  229. /* Program header. See [ELF1] 2-2 to 2-4.
  230. There are e_phnum of these, starting at file offset e_phoff
  231. (see [ELF1] 1-6). */
  232. struct Elf32_Phdr
  233. {
  234. Elf32_Word p_type;
  235. Elf32_Off p_offset;
  236. Elf32_Addr p_vaddr;
  237. Elf32_Addr p_paddr;
  238. Elf32_Word p_filesz;
  239. Elf32_Word p_memsz;
  240. Elf32_Word p_flags;
  241. Elf32_Word p_align;
  242. };
  243.  
  244. /* Values for p_type. See [ELF1] 2-3. */
  245. #define PT_NULL 0 /* Ignore. */
  246. #define PT_LOAD 1 /* Loadable segment. */
  247. #define PT_DYNAMIC 2 /* Dynamic linking info. */
  248. #define PT_INTERP 3 /* Name of dynamic loader. */
  249. #define PT_NOTE 4 /* Auxiliary info. */
  250. #define PT_SHLIB 5 /* Reserved. */
  251. #define PT_PHDR 6 /* Program header table. */
  252. #define PT_STACK 0x6474e551 /* Stack segment. */
  253.  
  254. /* Flags for p_flags. See [ELF3] 2-3 and 2-4. */
  255. #define PF_X 1 /* Executable. */
  256. #define PF_W 2 /* Writable. */
  257. #define PF_R 4 /* Readable. */
  258.  
  259. static bool setup_stack (void **esp);
  260. static bool validate_segment (const struct Elf32_Phdr *, struct file *);
  261. static bool load_segment (struct file *file, off_t ofs, uint8_t *upage,
  262. uint32_t read_bytes, uint32_t zero_bytes,
  263. bool writable);
  264.  
  265. /* Loads an ELF executable from FILE_NAME into the current thread.
  266. Stores the executable's entry point into *EIP
  267. and its initial stack pointer into *ESP.
  268. Returns true if successful, false otherwise. */
  269. bool
  270. load (const char *file_name, void (**eip) (void), void **esp)
  271. {
  272.  
  273. struct thread *t = thread_current ();
  274. struct Elf32_Ehdr ehdr;
  275. struct file *file = NULL;
  276. off_t file_ofs;
  277. bool success = false;
  278. int i;
  279.  
  280. /* Allocate and activate page directory. */
  281. t->pagedir = pagedir_create ();
  282. if (t->pagedir == NULL)
  283. goto done;
  284. process_activate ();
  285.  
  286. /* Open executable file. */
  287. file = filesys_open (file_name);
  288. if (file == NULL)
  289. {
  290. printf ("load: %s: open failed\n", file_name);
  291. goto done;
  292. }
  293.  
  294. /* Read and verify executable header. */
  295. if (file_read (file, &ehdr, sizeof ehdr) != sizeof ehdr
  296. || memcmp (ehdr.e_ident, "\177ELF\1\1\1", 7)
  297. || ehdr.e_type != 2
  298. || ehdr.e_machine != 3
  299. || ehdr.e_version != 1
  300. || ehdr.e_phentsize != sizeof (struct Elf32_Phdr)
  301. || ehdr.e_phnum > 1024)
  302. {
  303. printf ("load: %s: error loading executable\n", file_name);
  304. goto done;
  305. }
  306.  
  307. /* Read program headers. */
  308. file_ofs = ehdr.e_phoff;
  309. for (i = 0; i < ehdr.e_phnum; i++)
  310. {
  311. struct Elf32_Phdr phdr;
  312.  
  313. if (file_ofs < 0 || file_ofs > file_length (file))
  314. goto done;
  315. file_seek (file, file_ofs);
  316.  
  317. if (file_read (file, &phdr, sizeof phdr) != sizeof phdr)
  318. goto done;
  319. file_ofs += sizeof phdr;
  320. switch (phdr.p_type)
  321. {
  322. case PT_NULL:
  323. case PT_NOTE:
  324. case PT_PHDR:
  325. case PT_STACK:
  326. default:
  327. /* Ignore this segment. */
  328. break;
  329. case PT_DYNAMIC:
  330. case PT_INTERP:
  331. case PT_SHLIB:
  332. goto done;
  333. case PT_LOAD:
  334. if (validate_segment (&phdr, file))
  335. {
  336. bool writable = (phdr.p_flags & PF_W) != 0;
  337. uint32_t file_page = phdr.p_offset & ~PGMASK;
  338. uint32_t mem_page = phdr.p_vaddr & ~PGMASK;
  339. uint32_t page_offset = phdr.p_vaddr & PGMASK;
  340. uint32_t read_bytes, zero_bytes;
  341. if (phdr.p_filesz > 0)
  342. {
  343. /* Normal segment.
  344. Read initial part from disk and zero the rest. */
  345. read_bytes = page_offset + phdr.p_filesz;
  346. zero_bytes = (ROUND_UP (page_offset + phdr.p_memsz, PGSIZE)
  347. - read_bytes);
  348. }
  349. else
  350. {
  351. /* Entirely zero.
  352. Don't read anything from disk. */
  353. read_bytes = 0;
  354. zero_bytes = ROUND_UP (page_offset + phdr.p_memsz, PGSIZE);
  355. }
  356. if (!load_segment (file, file_page, (void *) mem_page,
  357. read_bytes, zero_bytes, writable))
  358. goto done;
  359. }
  360. else
  361. goto done;
  362. break;
  363. }
  364. }
  365.  
  366. /* Set up stack. */
  367. if (!setup_stack (esp))
  368. goto done;
  369. else{
  370. add_params_to_stack(thread_params_buffer,esp);
  371. }
  372. /* Start address. */
  373. *eip = (void (*) (void)) ehdr.e_entry;
  374.  
  375. success = true;
  376.  
  377. done:
  378. /* We arrive here whether the load is successful or not. */
  379.  
  380. if(success){
  381. file_deny_write(file);
  382. thread_current()->exec_file = file;
  383. }
  384. else file_close (file);
  385.  
  386. return success;
  387. }
  388.  
  389. /* load() helpers. */
  390.  
  391. static bool install_page (void *upage, void *kpage, bool writable);
  392.  
  393. /* Checks whether PHDR describes a valid, loadable segment in
  394. FILE and returns true if so, false otherwise. */
  395. static bool
  396. validate_segment (const struct Elf32_Phdr *phdr, struct file *file)
  397. {
  398. /* p_offset and p_vaddr must have the same page offset. */
  399. if ((phdr->p_offset & PGMASK) != (phdr->p_vaddr & PGMASK))
  400. return false;
  401.  
  402. /* p_offset must point within FILE. */
  403. if (phdr->p_offset > (Elf32_Off) file_length (file))
  404. return false;
  405.  
  406. /* p_memsz must be at least as big as p_filesz. */
  407. if (phdr->p_memsz < phdr->p_filesz)
  408. return false;
  409.  
  410. /* The segment must not be empty. */
  411. if (phdr->p_memsz == 0)
  412. return false;
  413.  
  414. /* The virtual memory region must both start and end within the
  415. user address space range. */
  416. if (!is_user_vaddr ((void *) phdr->p_vaddr))
  417. return false;
  418. if (!is_user_vaddr ((void *) (phdr->p_vaddr + phdr->p_memsz)))
  419. return false;
  420.  
  421. /* The region cannot "wrap around" across the kernel virtual
  422. address space. */
  423. if (phdr->p_vaddr + phdr->p_memsz < phdr->p_vaddr)
  424. return false;
  425.  
  426. /* Disallow mapping page 0.
  427. Not only is it a bad idea to map page 0, but if we allowed
  428. it then user code that passed a null pointer to system calls
  429. could quite likely panic the kernel by way of null pointer
  430. assertions in memcpy(), etc. */
  431. if (phdr->p_vaddr < PGSIZE)
  432. return false;
  433.  
  434. /* It's okay. */
  435. return true;
  436. }
  437.  
  438. /* Loads a segment starting at offset OFS in FILE at address
  439. UPAGE. In total, READ_BYTES + ZERO_BYTES bytes of virtual
  440. memory are initialized, as follows:
  441.  
  442. - READ_BYTES bytes at UPAGE must be read from FILE
  443. starting at offset OFS.
  444.  
  445. - ZERO_BYTES bytes at UPAGE + READ_BYTES must be zeroed.
  446.  
  447. The pages initialized by this function must be writable by the
  448. user process if WRITABLE is true, read-only otherwise.
  449.  
  450. Return true if successful, false if a memory allocation error
  451. or disk read error occurs. */
  452. static bool
  453. load_segment (struct file *file, off_t ofs, uint8_t *upage,
  454. uint32_t read_bytes, uint32_t zero_bytes, bool writable)
  455. {
  456. ASSERT ((read_bytes + zero_bytes) % PGSIZE == 0);
  457. ASSERT (pg_ofs (upage) == 0);
  458. ASSERT (ofs % PGSIZE == 0);
  459.  
  460. file_seek (file, ofs);
  461. while (read_bytes > 0 || zero_bytes > 0)
  462. {
  463. /* Calculate how to fill this page.
  464. We will read PAGE_READ_BYTES bytes from FILE
  465. and zero the final PAGE_ZERO_BYTES bytes. */
  466. size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE;
  467. size_t page_zero_bytes = PGSIZE - page_read_bytes;
  468.  
  469. /* Get a page of memory. */
  470. uint8_t *kpage = palloc_get_page (PAL_USER);
  471. if (kpage == NULL)
  472. return false;
  473.  
  474. /* Load this page. */
  475. if (file_read (file, kpage, page_read_bytes) != (int) page_read_bytes)
  476. {
  477. palloc_free_page (kpage);
  478. return false;
  479. }
  480. memset (kpage + page_read_bytes, 0, page_zero_bytes);
  481.  
  482. /* Add the page to the process's address space. */
  483. if (!install_page (upage, kpage, writable))
  484. {
  485. palloc_free_page (kpage);
  486. return false;
  487. }
  488.  
  489. /* Advance. */
  490. read_bytes -= page_read_bytes;
  491. zero_bytes -= page_zero_bytes;
  492. upage += PGSIZE;
  493. }
  494. return true;
  495. }
  496.  
  497. /* Create a minimal stack by mapping a zeroed page at the top of
  498. user virtual memory. */
  499. static bool
  500. setup_stack (void **esp)
  501. {
  502. uint8_t *kpage;
  503. bool success = false;
  504.  
  505. kpage = palloc_get_page (PAL_USER | PAL_ZERO);
  506. if (kpage != NULL)
  507. {
  508. success = install_page (((uint8_t *) PHYS_BASE) - PGSIZE, kpage, true);
  509. if (success)
  510. *esp = PHYS_BASE;
  511. else
  512. palloc_free_page (kpage);
  513. }
  514. return success;
  515. }
  516.  
  517. /* Adds a mapping from user virtual address UPAGE to kernel
  518. virtual address KPAGE to the page table.
  519. If WRITABLE is true, the user process may modify the page;
  520. otherwise, it is read-only.
  521. UPAGE must not already be mapped.
  522. KPAGE should probably be a page obtained from the user pool
  523. with palloc_get_page().
  524. Returns true on success, false if UPAGE is already mapped or
  525. if memory allocation fails. */
  526. static bool
  527. install_page (void *upage, void *kpage, bool writable)
  528. {
  529. struct thread *t = thread_current ();
  530.  
  531. /* Verify that there's not already a page at that virtual
  532. address, then map our page there. */
  533. return (pagedir_get_page (t->pagedir, upage) == NULL
  534. && pagedir_set_page (t->pagedir, upage, kpage, writable));
  535. }
  536. int
  537. cmnd_parse(char *line, char **argv)
  538. {
  539. int cnt = 0;
  540. while (*line != '\0') { /* if not the end of line ....... */
  541. while (*line == ' ' || *line == '\t' || *line == '\n')
  542. *line++ = '\0'; /* replace white spaces with 0 */
  543. *argv++ = line; /* save the argument position */
  544. cnt++;
  545. while (*line != '\0' && *line != ' ' &&
  546. *line != '\t' && *line != '\n')
  547. line++; /* skip the argument until ... */
  548. }
  549. *argv = '\0'; /* mark the end of argument list */
  550. return cnt;
  551. }
  552.  
  553. /* Argument Passing: Saving args into the user stack followed by pushing
  554. their addresses. */
  555. void add_params_to_stack(char *params,void **esp){
  556.  
  557. char *args[199]; /* Pointers to the start of each parameter */
  558. void *addr[200]; /* Array to store addresses of each parameter in the stack */
  559.  
  560. /* Parses the cmnd_line and splits it on white spaces. */
  561. int cnt = cmnd_parse(params,args) -1;
  562. int i = cnt;
  563. /* Copies the strings from the cmnd line into the stack
  564. and saving their new addresses in the stack */
  565. while(i >= 0){
  566. int sz = strlen(args[i])+1;
  567. *esp = (void *)((int)*esp - sz);
  568. addr[i] = *esp;
  569. strlcpy((char *)*esp,(const char *)args[i],sz);
  570. i--;
  571. }
  572.  
  573. /* Adding null characters to align words containing addresses. */
  574. while((int)*esp % 4 != 0){
  575. *esp = (void *)((int)*esp - 1);
  576. char align = '\0';
  577. strlcpy((char *)*esp,(const char *)&align,1);
  578. }
  579.  
  580.  
  581. /* Pushing null address to terminate the args */
  582. *esp = (void *)((int)*esp - 4);
  583. int terminator = 0;
  584. memcpy((char *)*esp,(const char *)&terminator,4);
  585.  
  586. /* Pushing parameters' addresses to the stack. */
  587. i = cnt;
  588. while(i >= 0){
  589. *esp = (void *)((int)*esp - 4);
  590. int address = (int)addr[i];
  591. memcpy((char *)*esp,(const char *)&address,4);
  592. i--;
  593. }
  594.  
  595.  
  596. /* Pushing initial address of argv and value of argc. */
  597. *esp = (void *)((int)*esp - 4);
  598. int tmp_esp = (int)*esp+4;
  599. memcpy((char *)*esp,(const char *)&tmp_esp,4);
  600.  
  601. *esp = (void *)((int)*esp - 4);
  602. int argc = cnt+1;
  603. memcpy((char *)*esp,(const char *)&argc,4);
  604.  
  605. /* Pushing fake return address */
  606. int fake_address = 0;
  607. *esp = (void *)((int)*esp - 4);
  608. memcpy((char *)*esp,(const char *)&fake_address,4);
  609.  
  610. return;
  611.  
  612. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement