Forked from BOURBAKI04 / YuanShen OS
Source project has a limited visibility.
exec.c 6.28 KiB
#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "riscv.h"
#include "include/spinlock.h"
#include "proc.h"
#include "defs.h"
#include "file.h"
#include "fcntl.h"
#include "elf.h"
#include "vma.h"
// static int loadseg(pde_t *, uint64, struct inode *, uint, uint);
int flags2perm(int flags)
    int perm = 0;
    if(flags & 0x1)
      perm = PTE_X;
    if(flags & 0x2)
      perm |= PTE_W;
    return perm;
int
exec(char *path, char **argv)
  char *s, *last;
  int i, off;
  uint64 argc, sz = 0, sp, ustack[MAXARG], stackbase;
  struct elfhdr elf;
  struct inode *ip;
  struct proghdr ph;
  pagetable_t pagetable = 0, oldpagetable;
  struct proc *p = myproc();
  // printf("hey");
  unmap_all_vma(&p->mm);// unmap all vmas
  begin_op();
  if((ip = namei(path)) == 0){
    end_op();
    return -1;
  ilock(ip);
  // Check ELF header
  if(readi(ip, 0, (uint64)&elf, 0, sizeof(elf)) != sizeof(elf))
    goto bad;
  if(elf.magic != ELF_MAGIC)
    goto bad;
  if((pagetable = proc_pagetable(p)) == 0)
    goto bad;
  // printf("exec: elf.phnum: %d\n", elf.phnum);
  // Load program into memory.
  struct file *f = filealloc();
  f->ip = idup(ip);
  if(f == 0)
    panic("exec: no file");
  for(i=0, off=elf.phoff; i<elf.phnum; i++, off+=sizeof(ph)){
    if(readi(ip, 0, (uint64)&ph, off, sizeof(ph)) != sizeof(ph))
      goto bad;
    if(ph.type != ELF_PROG_LOAD)
      continue;