Advertisement
Guest User

process

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