/**************************************************************************************
 Copyright (c) 2002 The UbixOS Project
 All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors
in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project nor the names of its
contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 $Id: exec.c,v 1.29 2003/05/11 23:37:07 reddawg Exp $

**************************************************************************************/

#include <ubixos/exec.h>
#include <ubixos/schedule.h>
#include <ubixos/elf.h>
#include <ubixos/file.h>
#include <lib/kmalloc.h>
#include <vmm/paging.h>
#include <vmm/memory.h>
#include <sys/video.h>
#include <ld/ld.h>

/************************************************************************

Function: void execFile(char *file);
Description: This Function Executes A Kile Into A New VM Space With Out
             Having To Fork
Notes:

07/30/02 - I Have Made Some Heavy Changes To This As Well As Fixed A Few
           Memory Leaks The Memory Allocated To Load The Binary Into Is
           Now Unmapped So It Can Be Used Again And Not Held Onto Until
           The Program Exits

07/30/02 - Now I Have To Make A Better Memory Allocator So We Can Set Up
           The Freshly Allocated Pages With The Correct Permissions

************************************************************************/
void execFile(char *file) {
  int i=0,x=0,eStart=0;
  char *binarySpace = (char *)0x7C0000;
  char *newLoc;
  fileDescriptor *tmpFd = 0x0;
  elfHeader *binaryHeader = (elfHeader *)0x7C0000;
  elfProgramheader *programHeader;
  //Get A New Task For This Proccess
  _current = findTask();
  _current->gid = 0;
  _current->uid = 0;
  //Now We Must Create A Virtual Space For This Proccess To Run In
  _current->tss.cr3 = (uLong)createVirtualSpace(_current->id);
  //To Better Load This Application We Will Switch Over To Its VM Space
  asm(
    "movl %0,%%eax          \n"
    "movl %%eax,%%cr3       \n"
    : : "d" ((uLong *)(_current->tss.cr3))
    );
  //Lets Find The File
  tmpFd = fopen(file,"r");
  //If We Dont Find the File Return
  if (!tmpFd) {
    return;
    }
  //Now We Must Allocate Memory To Load The Binary Into
  for (i=0;i<((tmpFd->size+4095)/4096);i++) {
    remapPage(findFreePage(_current->id),(0x7C0000 + (0x1000 * i)));
    }
  //Load The Binary Into Memory Byte For Byte I Should Find A Faster Way
  fread(binarySpace,tmpFd->size,1,tmpFd);
  /*
  for (i=0;feof(tmpFd) == 0;i++) {
    binarySpace[i] = fgetc(tmpFd);
    }
    */
  //Close The File
  fclose(tmpFd);
  //Set programHeader To Point To Loaded Binary So We Can Gather Info
  programHeader = (elfProgramheader *)(0x7C0000 + binaryHeader->ePhoff);
  //Loop Through The Header And Load Sections Which Need To Be Loaded
  for (i=0;i<binaryHeader->ePhnum;i++) {
    newLoc = (char *)programHeader[i].phVaddr;
    /*
    Allocate Memory Im Going To Have To Make This Load Memory With Corrent
    Settings so it helps us in the future
    */
    for (x=0;x<=((programHeader[i].phMemsz & 0xFFFFF000)+0x1000);x+=0x1000) {
      remapPage(findFreePage(_current->id),((programHeader[i].phVaddr & 0xFFFFF000) + x));
      }
    //Now Copy The Binary To Its Correct Location
    for (x=0;x<programHeader[i].phFilesz;x++) {
      newLoc[x] = binarySpace[(programHeader[i].phOffset+x)];
      }
    }
  //Set Virtual Memory Start
  _current->oInfo.vmStart = ((programHeader[i].phVaddr & 0xFFFFF000) + 0x1900000);
  //Get The Starting Point
  eStart = binaryHeader->eEntry;
  //Now That We Relocated The Binary We Can Unmap And Free Old Pages
  for (i=0;i<((tmpFd->size+4095)/4096);i++) {
    unmapPage((0x7C0000 + (0x1000 * i)),0);
    }
  //Now Lets Make A Clean Stack
  newLoc = (char *)0x5DB000;
  remapPage(findFreePage(_current->id),0x5DC000);
  setPageAttribute(0x5DC000,(pageDefault | pageStack));
  remapPage(findFreePage(_current->id),0x5DB000);
  setPageAttribute(0x5DB000,(pageDefault | pageStack));
  remapPage(findFreePage(_current->id),0x5DA000);
  setPageAttribute(0x5DA000,(pageDefault | pageStack));
  remapPage(findFreePage(_current->id),0x5D9000);
  setPageAttribute(0x5D9000,(pageDefault | pageStack));

  i = 0x5DD000;

  remapPage(findFreePage(_current->id),0x5D3000);
  setPageAttribute(0x5D3000,(pageDefault | pageStack));
  remapPage(findFreePage(_current->id),0x5D2000);
  setPageAttribute(0x5D2000,(pageDefault | pageStack));
  remapPage(findFreePage(_current->id),0x5D1000);
  setPageAttribute(0x5D1000,(pageDefault | pageStack));
  remapPage(findFreePage(_current->id),0x5D0000);
  setPageAttribute(0x5D0000,(pageDefault | pageStack));
  
  //Set All The Proper Information For The Task
  _current->tss.back_link    = 0x0;
  _current->tss.esp0         = 0x5D4000;
  _current->tss.ss0          = 0x10;
  _current->tss.esp1         = 0x0;
  _current->tss.ss1          = 0x0;
  _current->tss.esp2         = 0x0;
  _current->tss.ss2          = 0x0;
  _current->tss.eip          = (long)eStart;
  _current->tss.eflags       = 0x206;
  _current->tss.esp          = i-16;
  _current->tss.ebp          = i;
  _current->tss.esi          = 0x0;
  _current->tss.edi          = 0x0;
  _current->tss.es           = 0x38+3;
  _current->tss.cs           = 0x30+3;
  _current->tss.ss           = 0x38+3;
  _current->tss.ds           = 0x38+3;
  _current->tss.fs           = 0x38+3;
  _current->tss.gs           = 0x38+3;
  _current->tss.ldt          = 0x18;
  _current->tss.trace_bitmap = 0x0000;
  _current->tss.io_map       = 0x8000;
  setTaskStatus(_current->id, READY);
  
  //_current->status = READY;
  //Switch Back To The Kernels VM Space
  asm(
    "movl %0,%%eax          \n"
    "movl %%eax,%%cr3       \n"
    : : "d" ((uLong *)(kernelPageDirectory))
    );
  //kprintf("Temp: [%i](%i)\n",getTask(0),getTask(0)->status);
  //while(1);
  //Finally Return
  return;
  }

/************************************************************************

Function: void execThread(void (* tproc)(void),int stack,char *descr);
Description: This Function Executes A New Thread For Kernel And Does
             Not Create Its Own VM Space
Notes:

************************************************************************/  
void execThread(void (* tproc)(void),int stack,char *descr) {
  kTask_t * newProcess;
  //Find A New Thread
  newProcess = findTask();
  //kprintf("newProcess: [%i](%i)\n",newProcess,newProcess->status);
  //Set All The Correct Thread Attributes
  newProcess->tss.back_link    = 0x0;
  newProcess->tss.esp0         = (uInt32)kmalloc(4096,newProcess->id)+4095;//0x5000;
  newProcess->tss.ss0          = 0x10;
  newProcess->tss.esp1         = 0x0;
  newProcess->tss.ss1          = 0x0;
  newProcess->tss.esp2         = 0x0;
  newProcess->tss.ss2          = 0x0;
  newProcess->tss.cr3          = (unsigned int)kernelPageDirectory;
  newProcess->tss.eip          = (unsigned int)tproc;
  newProcess->tss.eflags       = 0x206;
  newProcess->tss.esp          = stack;
  newProcess->tss.ebp          = stack;
  newProcess->tss.esi          = 0x0;
  newProcess->tss.edi          = 0x0;
  
  /*  
  newProcess->tss.es           = 0x38+3;//0x10;
  newProcess->tss.cs           = 0x30+3;//0x08;
  newProcess->tss.ss           = 0x38+3;//0x10;
  newProcess->tss.ds           = 0x38+3;//0x10;
  newProcess->tss.fs           = 0x38+3;//0x10;
  newProcess->tss.gs           = 0x38+3;//0x10;
  */
  
  newProcess->tss.es           = 0x10;
  newProcess->tss.cs           = 0x08;
  newProcess->tss.ss           = 0x10;
  newProcess->tss.ds           = 0x10;
  newProcess->tss.fs           = 0x10;
  newProcess->tss.gs           = 0x10;
  newProcess->tss.ldt          = 0x18;

  newProcess->tss.trace_bitmap = 0x0000;
  newProcess->tss.io_map       = 0x8000;
  //newProcess->status = READY;
  newProcess->oInfo.vmStart = 0x6400000;
  setTaskStatus(newProcess->id, READY);
  //Return
  return;
  }

/************************************************************************

Function: void sysExec();
Description: This Is The System Call To Execute A New Task

Notes:
  04-22-03 - It Now Loads Sections Not The Full File
  
************************************************************************/  
void sysExec(int argc,char **argv,char *file,int *status) {
  int    i            = 0x0;
  int    x            = 0x0;
  uInt32 eStart       = 0x0;
  uInt32 *tmp         = 0x0;
  char   *newLoc      = 0x0;

  fileDescriptor   *tmpFd         = 0x0;
  elfHeader        *binaryHeader  = 0x0;
  elfProgramheader *programHeader = 0x0;
  elfDynamic       *elfDynamicS   = 0x0;
  elfSectionheader *sectionHeader = 0x0;
  elfDynsym        *elfDynsymS    = 0x0;
  elfPltInfo       *elfPltInfoS   = 0x0;
  
  asm("sti");

  //kprintf("Status: [0x%X]\n",*status);
  
  tmpFd = fopen(file,"r");
  //If We Dont Find the File Return
  if (tmpFd == 0x0) {
    *status = 0;
    return;
    }
  if (tmpFd->perms == 0) {
    *status = -2;
    kprintf("Exec Format Error: Binary File Not Executable.\n");
    fclose(tmpFd);
    return;
    }

  //Load ELF Header
  binaryHeader = (elfHeader *)kmalloc(sizeof(elfHeader),_current->id);
  fread(binaryHeader,sizeof(elfHeader),1,tmpFd);

  //Set sectionHeader To Point To Loaded Binary To We Can Gather Info
  //sectionHeader = (elfSectionheader *)(0x7C0000 + binaryHeader->eShoff);

  //Check If App Is A Real Application
  if ((binaryHeader->eIdent[1] != 'E') && (binaryHeader->eIdent[2] != 'L') && (binaryHeader->eIdent[3] != 'F')) {
    *status = -1;
    kprintf("Exec Format Error: Binary File Not Executable.\n");
    kfree(binaryHeader);
    fclose(tmpFd);
    return;
    }
  else if (binaryHeader->eType != 2) {
    *status = -2;
    kprintf("Exec Format Error: Binary File Not Executable.\n");
    kfree(binaryHeader);
    fclose(tmpFd);
    return;
    }
  else if (binaryHeader->eEntry == 0x300000) {
    *status = -2;
    kprintf("Exec Format Error: Binary File Not Executable.\n");
    kfree(binaryHeader);
    fclose(tmpFd);
    return;
    }

  //Load The Program Header(s)
  programHeader = (elfProgramheader *)kmalloc(sizeof(elfProgramheader)*binaryHeader->ePhnum,_current->id);
  fseek(tmpFd,binaryHeader->ePhoff,0);
  fread(programHeader,sizeof(elfProgramheader)*binaryHeader->ePhnum,1,tmpFd);

  sectionHeader = (elfSectionheader *)kmalloc(sizeof(elfSectionheader)*binaryHeader->eShnum,_current->id);
  fseek(tmpFd,binaryHeader->eShoff,0);
  fread(sectionHeader,sizeof(elfSectionheader)*binaryHeader->eShnum,1,tmpFd);
  
  //Loop Through The Header And Load Sections Which Need To Be Loaded
  for (i=0;i<binaryHeader->ePhnum;i++) {
    if (programHeader[i].phType == 1) {
      newLoc = (char *)programHeader[i].phVaddr;
      /*
      Allocate Memory Im Going To Have To Make This Load Memory With Corrent
      Settings so it helps us in the future
      */
      for (x=0;x<=((programHeader[i].phMemsz & 0xFFFFF000)+4095);x+=4096) {
        remapPage(findFreePage(_current->id),((programHeader[i].phVaddr & 0xFFFFF000) + x));
        }
      _current->oInfo.vmStart = ((programHeader[i].phVaddr & 0xFFFFF000) + 0x1900000);        
      //Now Load Section To Memory
      fseek(tmpFd,programHeader[i].phOffset,0);
      fread(newLoc,programHeader[i].phFilesz,1,tmpFd);
      }
    else if (programHeader[i].phType == 2) {
      newLoc = (char *)programHeader[i].phVaddr;
      fseek(tmpFd,programHeader[i].phOffset,0);
      fread(newLoc,programHeader[i].phFilesz,1,tmpFd);
      }  
    }

  _current->oInfo.shstrtab = (char *)kmalloc(sectionHeader[binaryHeader->eShstrndx].shSize,_current->id);
  fseek(tmpFd,sectionHeader[binaryHeader->eShstrndx].shOffset,0);
  fread(_current->oInfo.shstrtab,sectionHeader[binaryHeader->eShstrndx].shSize,0,tmpFd);

  

  kprintf("[%s]\n",_current->oInfo.shstrtab+1);
  
  for (i=0;i<binaryHeader->eShnum;i++) {
    switch (sectionHeader[i].shType) {
      case 0:
        break;
      case 9:
        elfPltInfoS = (elfPltInfo *)sectionHeader[i].shAddr;
        for (x=0x0;x<sectionHeader[i].shSize/sizeof(elfDynamic);x++) {
          tmp = elfPltInfoS[x].pltOffset;
          kprintf("[0x%X][0x%X]\n",tmp,*tmp);
          *tmp = &ld;
          }
        break;
      default:
        //kprintf("[0x%X][%s]\n",sectionHeader[i].shType,elfGetShType(sectionHeader[i].shType));
        break;
      }
    }

  _current->oInfo.sectionHeader = sectionHeader;
  _current->oInfo.sectionCount  = binaryHeader->eShnum;
  _current->oInfo.stringSection = binaryHeader->eShstrndx;
  
  //Get The Starting Point
  eStart = binaryHeader->eEntry;
  
  //Now That We Relocated The Binary We Can Unmap And Free Header Info
  kfree(binaryHeader);
  kfree(programHeader);
  fclose(tmpFd);
  
  //Jump To Start Of New Binary  
  asm(
  
    "pushl %1\n"
    "pushl %1\n"
    "pushl %0\n"
    "jmp  *%2\n"
    :
    : "g" (argc),"g" (argv),"g" (eStart)
    );
  }
