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