Fixed typo.
[wine] / loader / dos / module.c
1 /*
2  * DOS (MZ) loader
3  *
4  * Copyright 1998 Ove Kåven
5  *
6  * This code hasn't been completely cleaned up yet.
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <signal.h>
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/time.h>
19 #include "windef.h"
20 #include "wine/winbase16.h"
21 #include "winerror.h"
22 #include "module.h"
23 #include "peexe.h"
24 #include "neexe.h"
25 #include "task.h"
26 #include "selectors.h"
27 #include "file.h"
28 #include "ldt.h"
29 #include "process.h"
30 #include "miscemu.h"
31 #include "debug.h"
32 #include "dosexe.h"
33 #include "dosmod.h"
34 #include "options.h"
35
36 #ifdef MZ_SUPPORTED
37
38 #include <sys/mman.h>
39
40 /* define this to try mapping through /proc/pid/mem instead of a temp file,
41    but Linus doesn't like mmapping /proc/pid/mem, so it doesn't work for me */
42 #undef MZ_MAPSELF
43
44 #define BIOS_DATA_SEGMENT 0x40
45 #define START_OFFSET 0
46 #define PSP_SIZE 0x10
47
48 #define SEG16(ptr,seg) ((LPVOID)((BYTE*)ptr+((DWORD)(seg)<<4)))
49 #define SEGPTR16(ptr,segptr) ((LPVOID)((BYTE*)ptr+((DWORD)SELECTOROF(segptr)<<4)+OFFSETOF(segptr)))
50
51 static void MZ_InitPSP( LPVOID lpPSP, LPCSTR cmdline, WORD env )
52 {
53  PDB16*psp=lpPSP;
54  const char*cmd=cmdline?strchr(cmdline,' '):NULL;
55
56  psp->int20=0x20CD; /* int 20 */
57  /* some programs use this to calculate how much memory they need */
58  psp->nextParagraph=0x9FFF;
59  psp->environment=env;
60  /* copy parameters */
61  if (cmd) {
62 #if 0
63   /* command.com doesn't do this */
64   while (*cmd == ' ') cmd++;
65 #endif
66   psp->cmdLine[0]=strlen(cmd);
67   strcpy(psp->cmdLine+1,cmd);
68   psp->cmdLine[psp->cmdLine[0]+1]='\r';
69  } else psp->cmdLine[1]='\r';
70  /* FIXME: integrate the memory stuff from Wine (msdos/dosmem.c) */
71  /* FIXME: integrate the PDB stuff from Wine (loader/task.c) */
72 }
73
74 /* default INT 08 handler: increases timer tick counter but not much more */
75 static char int08[]={
76  0xCD,0x1C,           /* int $0x1c */
77  0x50,                /* pushw %ax */
78  0x1E,                /* pushw %ds */
79  0xB8,0x40,0x00,      /* movw $0x40,%ax */
80  0x8E,0xD8,           /* movw %ax,%ds */
81 #if 0
82  0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
83  0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
84 #else
85  0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
86 #endif
87  0xB0,0x20,           /* movb $0x20,%al */
88  0xE6,0x20,           /* outb %al,$0x20 */
89  0x1F,                /* popw %ax */
90  0x58,                /* popw %ax */
91  0xCF                 /* iret */
92 };
93
94 static void MZ_InitHandlers( LPDOSTASK lpDosTask )
95 {
96  WORD seg;
97  LPBYTE start=DOSMEM_GetBlock(lpDosTask->hModule,sizeof(int08),&seg);
98  memcpy(start,int08,sizeof(int08));
99 /* INT 08: point it at our tick-incrementing handler */
100  ((SEGPTR*)(lpDosTask->img))[0x08]=PTR_SEG_OFF_TO_SEGPTR(seg,0);
101 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
102  ((SEGPTR*)(lpDosTask->img))[0x1C]=PTR_SEG_OFF_TO_SEGPTR(seg,sizeof(int08)-1);
103 }
104
105 static char enter_xms[]={
106 /* XMS hookable entry point */
107  0xEB,0x03,           /* jmp entry */
108  0x90,0x90,0x90,      /* nop;nop;nop */
109                       /* entry: */
110 /* real entry point */
111 /* for simplicity, we'll just use the same hook as DPMI below */
112  0xCD,0x31,           /* int $0x31 */
113  0xCB                 /* lret */
114 };
115
116 static void MZ_InitXMS( LPDOSTASK lpDosTask )
117 {
118  LPBYTE start=DOSMEM_GetBlock(lpDosTask->hModule,sizeof(enter_xms),&(lpDosTask->xms_seg));
119  memcpy(start,enter_xms,sizeof(enter_xms));
120 }
121
122 static char enter_pm[]={
123  0x50,                /* pushw %ax */
124  0x52,                /* pushw %dx */
125  0x55,                /* pushw %bp */
126  0x89,0xE5,           /* movw %sp,%bp */
127 /* get return CS */
128  0x8B,0x56,0x08,      /* movw 8(%bp),%dx */
129 /* just call int 31 here to get into protected mode... */
130 /* it'll check whether it was called from dpmi_seg... */
131  0xCD,0x31,           /* int $0x31 */
132 /* we are now in the context of a 16-bit relay call */
133 /* need to fixup our stack;
134  * 16-bit relay return address will be lost, but we won't worry quite yet */
135  0x8E,0xD0,           /* movw %ax,%ss */
136  0x66,0x0F,0xB7,0xE5, /* movzwl %bp,%esp */
137 /* set return CS */
138  0x89,0x56,0x08,      /* movw %dx,8(%bp) */
139  0x5D,                /* popw %bp */
140  0x5A,                /* popw %dx */
141  0x58,                /* popw %ax */
142  0xCB                 /* lret */
143 };
144
145 static void MZ_InitDPMI( LPDOSTASK lpDosTask )
146 {
147  unsigned size=sizeof(enter_pm);
148  LPBYTE start=DOSMEM_GetBlock(lpDosTask->hModule,size,&(lpDosTask->dpmi_seg));
149  
150  lpDosTask->dpmi_sel = SELECTOR_AllocBlock( start, size, SEGMENT_CODE, FALSE, FALSE );
151
152  memcpy(start,enter_pm,sizeof(enter_pm));
153 }
154
155 static WORD MZ_InitEnvironment( LPDOSTASK lpDosTask, LPCSTR env, LPCSTR name )
156 {
157  unsigned sz=0;
158  WORD seg;
159  LPSTR envblk;
160
161  if (env) {
162   /* get size of environment block */
163   while (env[sz++]) sz+=strlen(env+sz)+1;
164  } else sz++;
165  /* allocate it */
166  envblk=DOSMEM_GetBlock(lpDosTask->hModule,sz+sizeof(WORD)+strlen(name)+1,&seg);
167  /* fill it */
168  if (env) {
169   memcpy(envblk,env,sz);
170  } else envblk[0]=0;
171  /* DOS 3.x: the block contains 1 additional string */
172  *(WORD*)(envblk+sz)=1;
173  /* being the program name itself */
174  strcpy(envblk+sz+sizeof(WORD),name);
175  return seg;
176 }
177
178 static BOOL MZ_InitMemory( LPDOSTASK lpDosTask, NE_MODULE *pModule )
179 {
180  int x;
181
182  if (lpDosTask->img_ofs) return TRUE; /* already allocated */
183
184  /* allocate 1MB+64K shared memory */
185  lpDosTask->img_ofs=START_OFFSET;
186 #ifdef MZ_MAPSELF
187  lpDosTask->img=VirtualAlloc(NULL,0x110000,MEM_COMMIT,PAGE_READWRITE);
188  /* make sure mmap accepts it */
189  ((char*)lpDosTask->img)[0x10FFFF]=0;
190 #else
191  tmpnam(lpDosTask->mm_name);
192 /* strcpy(lpDosTask->mm_name,"/tmp/mydosimage"); */
193  lpDosTask->mm_fd=open(lpDosTask->mm_name,O_RDWR|O_CREAT /* |O_TRUNC */,S_IRUSR|S_IWUSR);
194  if (lpDosTask->mm_fd<0) ERR(module,"file %s could not be opened\n",lpDosTask->mm_name);
195  /* expand file to 1MB+64K */
196  lseek(lpDosTask->mm_fd,0x110000-1,SEEK_SET);
197  x=0; write(lpDosTask->mm_fd,&x,1);
198  /* map it in */
199  lpDosTask->img=mmap(NULL,0x110000-START_OFFSET,PROT_READ|PROT_WRITE,MAP_SHARED,lpDosTask->mm_fd,0);
200 #endif
201  if (lpDosTask->img==(LPVOID)-1) {
202   ERR(module,"could not map shared memory, error=%s\n",strerror(errno));
203   return FALSE;
204  }
205  TRACE(module,"DOS VM86 image mapped at %08lx\n",(DWORD)lpDosTask->img);
206  pModule->dos_image=lpDosTask->img;
207
208  /* initialize the memory */
209  TRACE(module,"Initializing DOS memory structures\n");
210  DOSMEM_Init(lpDosTask->hModule);
211  MZ_InitHandlers(lpDosTask);
212  MZ_InitXMS(lpDosTask);
213  MZ_InitDPMI(lpDosTask);
214  return TRUE;
215 }
216
217 static BOOL MZ_LoadImage( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmdline,
218                           LPCSTR env, LPDOSTASK lpDosTask, NE_MODULE *pModule )
219 {
220  IMAGE_DOS_HEADER mz_header;
221  DWORD image_start,image_size,min_size,max_size,avail;
222  BYTE*psp_start,*load_start;
223  int x,old_com=0;
224  SEGPTR reloc;
225  WORD env_seg;
226
227  _llseek(hFile,0,FILE_BEGIN);
228  if ((_lread(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
229      (mz_header.e_magic != IMAGE_DOS_SIGNATURE)) {
230   old_com=1; /* assume .COM file */
231   image_start=0;
232   image_size=GetFileSize(hFile,NULL);
233   min_size=0x10000; max_size=0x100000;
234   mz_header.e_crlc=0;
235   mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
236   mz_header.e_cs=0; mz_header.e_ip=0x100;
237  } else {
238   /* calculate load size */
239   image_start=mz_header.e_cparhdr<<4;
240   image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
241   if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
242   image_size-=image_start;
243   min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
244   max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
245  }
246
247  MZ_InitMemory(lpDosTask,pModule);
248
249  /* allocate environment block */
250  env_seg=MZ_InitEnvironment(lpDosTask,env,ofs->szPathName);
251
252  /* allocate memory for the executable */
253  TRACE(module,"Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
254  avail=DOSMEM_Available(lpDosTask->hModule);
255  if (avail<min_size) {
256   ERR(module, "insufficient DOS memory\n");
257   SetLastError(ERROR_NOT_ENOUGH_MEMORY);
258   return FALSE;
259  }
260  if (avail>max_size) avail=max_size;
261  psp_start=DOSMEM_GetBlock(lpDosTask->hModule,avail,&lpDosTask->psp_seg);
262  if (!psp_start) {
263   ERR(module, "error allocating DOS memory\n");
264   SetLastError(ERROR_NOT_ENOUGH_MEMORY);
265   return FALSE;
266  }
267  lpDosTask->load_seg=lpDosTask->psp_seg+(old_com?0:PSP_SIZE);
268  load_start=psp_start+(PSP_SIZE<<4);
269  MZ_InitPSP(psp_start, cmdline, env_seg);
270
271  /* load executable image */
272  TRACE(module,"loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
273  _llseek(hFile,image_start,FILE_BEGIN);
274  if ((_lread(hFile,load_start,image_size)) != image_size) {
275   SetLastError(ERROR_BAD_FORMAT);
276   return FALSE;
277  }
278
279  if (mz_header.e_crlc) {
280   /* load relocation table */
281   TRACE(module,"loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
282   /* FIXME: is this too slow without read buffering? */
283   _llseek(hFile,mz_header.e_lfarlc,FILE_BEGIN);
284   for (x=0; x<mz_header.e_crlc; x++) {
285    if (_lread(hFile,&reloc,sizeof(reloc)) != sizeof(reloc)) {
286     SetLastError(ERROR_BAD_FORMAT);
287     return FALSE;
288    }
289    *(WORD*)SEGPTR16(load_start,reloc)+=lpDosTask->load_seg;
290   }
291  }
292
293  lpDosTask->init_cs=lpDosTask->load_seg+mz_header.e_cs;
294  lpDosTask->init_ip=mz_header.e_ip;
295  lpDosTask->init_ss=lpDosTask->load_seg+mz_header.e_ss;
296  lpDosTask->init_sp=mz_header.e_sp;
297
298  TRACE(module,"entry point: %04x:%04x\n",lpDosTask->init_cs,lpDosTask->init_ip);
299  return TRUE;
300 }
301
302 LPDOSTASK MZ_AllocDPMITask( HMODULE16 hModule )
303 {
304  LPDOSTASK lpDosTask = calloc(1, sizeof(DOSTASK));
305  NE_MODULE *pModule;
306
307  if (lpDosTask) {
308   lpDosTask->hModule = hModule;
309
310   pModule = (NE_MODULE *)GlobalLock16(hModule);
311   pModule->lpDosTask = lpDosTask;
312  
313   lpDosTask->img=NULL; lpDosTask->mm_name[0]=0; lpDosTask->mm_fd=-1;
314
315   MZ_InitMemory(lpDosTask, pModule);
316
317   GlobalUnlock16(hModule);
318  }
319  return lpDosTask;
320 }
321
322 static void MZ_InitTimer( LPDOSTASK lpDosTask, int ver )
323 {
324  if (ver<1) {
325 #if 0
326   /* start simulated system 55Hz timer */
327   lpDosTask->system_timer = CreateSystemTimer( 55, MZ_Tick );
328   TRACE(module,"created 55Hz timer tick, handle=%d\n",lpDosTask->system_timer);
329 #endif
330  } else {
331   int func;
332   struct timeval tim;
333
334   /* start dosmod timer at 55Hz */
335   func=DOSMOD_SET_TIMER;
336   tim.tv_sec=0; tim.tv_usec=54925;
337   write(lpDosTask->write_pipe,&func,sizeof(func));
338   write(lpDosTask->write_pipe,&tim,sizeof(tim));
339  }
340 }
341
342 BOOL MZ_InitTask( LPDOSTASK lpDosTask )
343 {
344  int read_fd[2],write_fd[2];
345  pid_t child;
346  char *fname,*farg,arg[16],fproc[64],path[256],*fpath;
347
348  if (!lpDosTask) return FALSE;
349  /* create read pipe */
350  if (pipe(read_fd)<0) return FALSE;
351  if (pipe(write_fd)<0) {
352   close(read_fd[0]); close(read_fd[1]); return FALSE;
353  }
354  lpDosTask->read_pipe=read_fd[0];
355  lpDosTask->write_pipe=write_fd[1];
356  /* if we have a mapping file, use it */
357  fname=lpDosTask->mm_name; farg=NULL;
358  if (!fname[0]) {
359   /* otherwise, map our own memory image */
360   sprintf(fproc,"/proc/%d/mem",getpid());
361   sprintf(arg,"%ld",(unsigned long)lpDosTask->img);
362   fname=fproc; farg=arg;
363  }
364
365  TRACE(module,"Loading DOS VM support module (hmodule=%04x)\n",lpDosTask->hModule);
366  if ((child=fork())<0) {
367   close(write_fd[0]); close(write_fd[1]);
368   close(read_fd[0]); close(read_fd[1]); return FALSE;
369  }
370  if (child!=0) {
371   /* parent process */
372   int ret;
373
374   close(read_fd[1]); close(write_fd[0]);
375   lpDosTask->task=child;
376   /* wait for child process to signal readiness */
377   do {
378    if (read(lpDosTask->read_pipe,&ret,sizeof(ret))!=sizeof(ret)) {
379     if ((errno==EINTR)||(errno==EAGAIN)) continue;
380     /* failure */
381     ERR(module,"dosmod has failed to initialize\n");
382     if (lpDosTask->mm_name[0]!=0) unlink(lpDosTask->mm_name);
383     return FALSE;
384    }
385   } while (0);
386   /* the child has now mmaped the temp file, it's now safe to unlink.
387    * do it here to avoid leaving a mess in /tmp if/when Wine crashes... */
388   if (lpDosTask->mm_name[0]!=0) unlink(lpDosTask->mm_name);
389   /* start simulated system timer */
390   MZ_InitTimer(lpDosTask,ret);
391   /* all systems are now go */
392  } else {
393   /* child process */
394   close(read_fd[0]); close(write_fd[1]);
395   /* put our pipes somewhere dosmod can find them */
396   dup2(write_fd[0],0);      /* stdin */
397   dup2(read_fd[1],1);       /* stdout */
398   /* enable signals */
399   SIGNAL_MaskAsyncEvents(FALSE);
400   /* now load dosmod */
401   execlp("dosmod",fname,farg,NULL);
402   execl("dosmod",fname,farg,NULL);
403   /* hmm, they didn't install properly */
404   execl("loader/dos/dosmod",fname,farg,NULL);
405   /* last resort, try to find it through argv[0] */
406   fpath=strrchr(strcpy(path,Options.argv0),'/');
407   if (fpath) {
408    strcpy(fpath,"/loader/dos/dosmod");
409    execl(path,fname,farg,NULL);
410   }
411   /* if failure, exit */
412   ERR(module,"Failed to spawn dosmod, error=%s\n",strerror(errno));
413   exit(1);
414  }
415  return TRUE;
416 }
417
418 BOOL MZ_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmdline, LPCSTR env, 
419                        LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
420                        BOOL inherit, LPSTARTUPINFOA startup, 
421                        LPPROCESS_INFORMATION info )
422 {
423  LPDOSTASK lpDosTask = NULL; /* keep gcc from complaining */
424  HMODULE16 hModule;
425  PDB *pdb = PROCESS_Current();
426  TDB *pTask = (TDB*)GlobalLock16( GetCurrentTask() );
427  NE_MODULE *pModule = pTask ? NE_GetPtr( pTask->hModule ) : NULL;
428  int alloc = !(pModule && pModule->dos_image);
429
430  if (alloc && (lpDosTask = calloc(1, sizeof(DOSTASK))) == NULL) {
431   SetLastError(ERROR_NOT_ENOUGH_MEMORY);
432   return FALSE;
433  }
434
435  if ((!env)&&pdb) env = pdb->env_db->environ;
436  if (alloc) {
437   if ((hModule = MODULE_CreateDummyModule(ofs, NULL)) < 32) {
438    SetLastError(hModule);
439    return FALSE;
440   }
441   lpDosTask->hModule = hModule;
442
443   pModule = (NE_MODULE *)GlobalLock16(hModule);
444   pModule->lpDosTask = lpDosTask;
445  
446   lpDosTask->img=NULL; lpDosTask->mm_name[0]=0; lpDosTask->mm_fd=-1;
447  } else lpDosTask=pModule->lpDosTask;
448  if (!MZ_LoadImage( hFile, ofs, cmdline, env, lpDosTask, pModule )) {
449   if (alloc) {
450    if (lpDosTask->mm_name[0]!=0) {
451     if (lpDosTask->img!=NULL) munmap(lpDosTask->img,0x110000-START_OFFSET);
452     if (lpDosTask->mm_fd>=0) close(lpDosTask->mm_fd);
453     unlink(lpDosTask->mm_name);
454    } else
455     if (lpDosTask->img!=NULL) VirtualFree(lpDosTask->img,0x110000,MEM_RELEASE);
456   }
457   return FALSE;
458  }
459  if (alloc) {
460   pModule->dos_image = lpDosTask->img;
461   if (!MZ_InitTask( lpDosTask )) {
462    MZ_KillModule( lpDosTask );
463    /* FIXME: cleanup hModule */
464    SetLastError(ERROR_GEN_FAILURE);
465    return FALSE;
466   }
467   if (!PROCESS_Create( pModule, cmdline, env, 0, 0, 
468                        psa, tsa, inherit, startup, info ))
469    return FALSE;
470  }
471  return TRUE;
472 }
473
474 void MZ_KillModule( LPDOSTASK lpDosTask )
475 {
476  TRACE(module,"killing DOS task\n");
477 #if 0
478  SYSTEM_KillSystemTimer(lpDosTask->system_timer);
479 #endif
480  if (lpDosTask->mm_name[0]!=0) {
481   munmap(lpDosTask->img,0x110000-START_OFFSET);
482   close(lpDosTask->mm_fd);
483  } else VirtualFree(lpDosTask->img,0x110000,MEM_RELEASE);
484  close(lpDosTask->read_pipe);
485  close(lpDosTask->write_pipe);
486  kill(lpDosTask->task,SIGTERM);
487 #if 0
488  /* FIXME: this seems to crash */
489  if (lpDosTask->dpmi_sel)
490   UnMapLS(PTR_SEG_OFF_TO_SEGPTR(lpDosTask->dpmi_sel,0));
491 #endif
492 }
493
494 #else /* !MZ_SUPPORTED */
495
496 BOOL MZ_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmdline, LPCSTR env, 
497                        LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
498                        BOOL inherit, LPSTARTUPINFOA startup, 
499                        LPPROCESS_INFORMATION info )
500 {
501  WARN(module,"DOS executables not supported on this architecture\n");
502  SetLastError(ERROR_BAD_FORMAT);
503  return FALSE;
504 }
505
506 #endif