Added a framework for testing CreateProcess and a few tests.
[wine] / dlls / winedos / module.c
1 /*
2  * DOS (MZ) loader
3  *
4  * Copyright 1998 Ove Kåven
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Note: This code hasn't been completely cleaned up yet.
21  */
22
23 #include "config.h"
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <unistd.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include "windef.h"
36 #include "wine/winbase16.h"
37 #include "wingdi.h"
38 #include "winuser.h"
39 #include "winerror.h"
40 #include "module.h"
41 #include "task.h"
42 #include "file.h"
43 #include "miscemu.h"
44 #include "wine/debug.h"
45 #include "dosexe.h"
46 #include "dosvm.h"
47 #include "options.h"
48 #include "vga.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(module);
51
52 #ifdef MZ_SUPPORTED
53
54 #ifdef HAVE_SYS_MMAN_H
55 # include <sys/mman.h>
56 #endif
57
58 /* define this to try mapping through /proc/pid/mem instead of a temp file,
59    but Linus doesn't like mmapping /proc/pid/mem, so it doesn't work for me */
60 #undef MZ_MAPSELF
61
62 #define BIOS_DATA_SEGMENT 0x40
63 #define PSP_SIZE 0x10
64
65 #define SEG16(ptr,seg) ((LPVOID)((BYTE*)ptr+((DWORD)(seg)<<4)))
66 #define SEGPTR16(ptr,segptr) ((LPVOID)((BYTE*)ptr+((DWORD)SELECTOROF(segptr)<<4)+OFFSETOF(segptr)))
67
68 /* structures for EXEC */
69
70 typedef struct {
71   WORD env_seg;
72   DWORD cmdline WINE_PACKED;
73   DWORD fcb1 WINE_PACKED;
74   DWORD fcb2 WINE_PACKED;
75   WORD init_sp;
76   WORD init_ss;
77   WORD init_ip;
78   WORD init_cs;
79 } ExecBlock;
80
81 typedef struct {
82   WORD load_seg;
83   WORD rel_seg;
84 } OverlayBlock;
85
86 /* global variables */
87
88 pid_t dosvm_pid;
89
90 static WORD init_cs,init_ip,init_ss,init_sp;
91 static HANDLE dosvm_thread, loop_thread;
92 static DWORD dosvm_tid, loop_tid;
93
94 static void MZ_Launch(void);
95 static BOOL MZ_InitTask(void);
96 static void MZ_KillTask(void);
97
98 static void MZ_CreatePSP( LPVOID lpPSP, WORD env, WORD par )
99 {
100   PDB16*psp=lpPSP;
101
102   psp->int20=0x20CD; /* int 20 */
103   /* some programs use this to calculate how much memory they need */
104   psp->nextParagraph=0x9FFF; /* FIXME: use a real value */
105   /* FIXME: dispatcher */
106   psp->savedint22 = DOSVM_GetRMHandler(0x22);
107   psp->savedint23 = DOSVM_GetRMHandler(0x23);
108   psp->savedint24 = DOSVM_GetRMHandler(0x24);
109   psp->parentPSP=par;
110   psp->environment=env;
111   /* FIXME: more PSP stuff */
112 }
113
114 static void MZ_FillPSP( LPVOID lpPSP, LPCSTR cmdline )
115 {
116  PDB16*psp=lpPSP;
117  const char*cmd=cmdline?strchr(cmdline,' '):NULL;
118
119  /* copy parameters */
120  if (cmd) {
121 #if 0
122   /* command.com doesn't do this */
123   while (*cmd == ' ') cmd++;
124 #endif
125   psp->cmdLine[0]=strlen(cmd);
126   strcpy(psp->cmdLine+1,cmd);
127   psp->cmdLine[psp->cmdLine[0]+1]='\r';
128  } else psp->cmdLine[1]='\r';
129  /* FIXME: more PSP stuff */
130 }
131
132 /* default INT 08 handler: increases timer tick counter but not much more */
133 static char int08[]={
134  0xCD,0x1C,           /* int $0x1c */
135  0x50,                /* pushw %ax */
136  0x1E,                /* pushw %ds */
137  0xB8,0x40,0x00,      /* movw $0x40,%ax */
138  0x8E,0xD8,           /* movw %ax,%ds */
139 #if 0
140  0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
141  0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
142 #else
143  0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
144 #endif
145  0xB0,0x20,           /* movb $0x20,%al */
146  0xE6,0x20,           /* outb %al,$0x20 */
147  0x1F,                /* popw %ax */
148  0x58,                /* popw %ax */
149  0xCF                 /* iret */
150 };
151
152 static void MZ_InitHandlers(void)
153 {
154  WORD seg;
155  LPBYTE start=DOSMEM_GetBlock(sizeof(int08),&seg);
156  memcpy(start,int08,sizeof(int08));
157 /* INT 08: point it at our tick-incrementing handler */
158  ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
159 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
160  ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
161 }
162
163 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
164 {
165  unsigned sz=0;
166  WORD seg;
167  LPSTR envblk;
168
169  if (env) {
170   /* get size of environment block */
171   while (env[sz++]) sz+=strlen(env+sz)+1;
172  } else sz++;
173  /* allocate it */
174  envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
175  /* fill it */
176  if (env) {
177   memcpy(envblk,env,sz);
178  } else envblk[0]=0;
179  /* DOS 3.x: the block contains 1 additional string */
180  *(WORD*)(envblk+sz)=1;
181  /* being the program name itself */
182  strcpy(envblk+sz+sizeof(WORD),name);
183  return seg;
184 }
185
186 static BOOL MZ_InitMemory(void)
187 {
188     /* initialize the memory */
189     TRACE("Initializing DOS memory structures\n");
190     DOSMEM_Init(TRUE);
191
192     MZ_InitHandlers();
193     return TRUE;
194 }
195
196 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
197 {
198   IMAGE_DOS_HEADER mz_header;
199   DWORD image_start,image_size,min_size,max_size,avail;
200   BYTE*psp_start,*load_start,*oldenv;
201   int x, old_com=0, alloc;
202   SEGPTR reloc;
203   WORD env_seg, load_seg, rel_seg, oldpsp_seg;
204   DWORD len;
205
206   if (DOSVM_psp) {
207     /* DOS process already running, inherit from it */
208     PDB16* par_psp = (PDB16*)((DWORD)DOSVM_psp << 4);
209     alloc=0;
210     oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
211     oldpsp_seg = DOSVM_psp;
212   } else {
213     /* allocate new DOS process, inheriting from Wine environment */
214     alloc=1;
215     oldenv = GetEnvironmentStringsA();
216     oldpsp_seg = 0;
217   }
218
219  SetFilePointer(hFile,0,NULL,FILE_BEGIN);
220  if (   !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
221      || len != sizeof(mz_header) 
222      || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
223   char *p = strrchr( filename, '.' );
224   if (!p || strcasecmp( p, ".com" ))  /* check for .COM extension */
225   {
226       SetLastError(ERROR_BAD_FORMAT);
227       goto load_error;
228   }
229   old_com=1; /* assume .COM file */
230   image_start=0;
231   image_size=GetFileSize(hFile,NULL);
232   min_size=0x10000; max_size=0x100000;
233   mz_header.e_crlc=0;
234   mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
235   mz_header.e_cs=0; mz_header.e_ip=0x100;
236  } else {
237   /* calculate load size */
238   image_start=mz_header.e_cparhdr<<4;
239   image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
240   if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
241   image_size-=image_start;
242   min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
243   max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
244  }
245
246   if (alloc) MZ_InitMemory();
247
248   if (oblk) {
249     /* load overlay into preallocated memory */
250     load_seg=oblk->load_seg;
251     rel_seg=oblk->rel_seg;
252     load_start=(LPBYTE)((DWORD)load_seg<<4);
253   } else {
254     /* allocate environment block */
255     env_seg=MZ_InitEnvironment(oldenv, filename);
256
257     /* allocate memory for the executable */
258     TRACE("Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
259     avail=DOSMEM_Available();
260     if (avail<min_size) {
261       ERR("insufficient DOS memory\n");
262       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
263       goto load_error;
264     }
265     if (avail>max_size) avail=max_size;
266     psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
267     if (!psp_start) {
268       ERR("error allocating DOS memory\n");
269       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
270       goto load_error;
271     }
272     load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
273     rel_seg=load_seg;
274     load_start=psp_start+(PSP_SIZE<<4);
275     MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
276   }
277
278  /* load executable image */
279  TRACE("loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
280  SetFilePointer(hFile,image_start,NULL,FILE_BEGIN);
281  if (!ReadFile(hFile,load_start,image_size,&len,NULL) || len != image_size) {
282   SetLastError(ERROR_BAD_FORMAT);
283   goto load_error;
284  }
285
286  if (mz_header.e_crlc) {
287   /* load relocation table */
288   TRACE("loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
289   /* FIXME: is this too slow without read buffering? */
290   SetFilePointer(hFile,mz_header.e_lfarlc,NULL,FILE_BEGIN);
291   for (x=0; x<mz_header.e_crlc; x++) {
292    if (!ReadFile(hFile,&reloc,sizeof(reloc),&len,NULL) || len != sizeof(reloc)) {
293     SetLastError(ERROR_BAD_FORMAT);
294     goto load_error;
295    }
296    *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
297   }
298  }
299
300   if (!oblk) {
301     init_cs = load_seg+mz_header.e_cs;
302     init_ip = mz_header.e_ip;
303     init_ss = load_seg+mz_header.e_ss;
304     init_sp = mz_header.e_sp;
305
306     TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
307   }
308
309   if (alloc && !MZ_InitTask()) {
310     SetLastError(ERROR_GEN_FAILURE);
311     return FALSE;
312   }
313
314   return TRUE;
315
316 load_error:
317   DOSVM_psp = oldpsp_seg;
318
319   return FALSE;
320 }
321
322 /***********************************************************************
323  *              LoadDosExe (WINEDOS.@)
324  */
325 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
326 {
327   if (MZ_DoLoadImage( hFile, filename, NULL )) MZ_Launch();
328 }
329
330 /***********************************************************************
331  *              MZ_Exec
332  */
333 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
334 {
335   /* this may only be called from existing DOS processes
336    * (i.e. one DOS app spawning another) */
337   /* FIXME: do we want to check binary type first, to check
338    * whether it's a NE/PE executable? */
339   HFILE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
340                              NULL, OPEN_EXISTING, 0, 0);
341   BOOL ret = FALSE;
342   if (hFile == INVALID_HANDLE_VALUE) return FALSE;
343   switch (func) {
344   case 0: /* load and execute */
345   case 1: /* load but don't execute */
346     {
347       /* save current process's return SS:SP now */
348       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
349       PDB16 *psp = (PDB16 *)psp_start;
350       psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
351     }
352     ret = MZ_DoLoadImage( hFile, filename, NULL );
353     if (ret) {
354       /* MZ_LoadImage created a new PSP and loaded new values into it,
355        * let's work on the new values now */
356       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
357       ExecBlock *blk = (ExecBlock *)paramblk;
358       MZ_FillPSP(psp_start, DOSMEM_MapRealToLinear(blk->cmdline));
359       /* the lame MS-DOS engineers decided that the return address should be in int22 */
360       DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
361       if (func) {
362         /* don't execute, just return startup state */
363         blk->init_cs = init_cs;
364         blk->init_ip = init_ip;
365         blk->init_ss = init_ss;
366         blk->init_sp = init_sp;
367       } else {
368         /* execute by making us return to new process */
369         context->SegCs = init_cs;
370         context->Eip   = init_ip;
371         context->SegSs = init_ss;
372         context->Esp   = init_sp;
373         context->SegDs = DOSVM_psp;
374         context->SegEs = DOSVM_psp;
375         context->Eax   = 0;
376       }
377     }
378     break;
379   case 3: /* load overlay */
380     {
381       OverlayBlock *blk = (OverlayBlock *)paramblk;
382       ret = MZ_DoLoadImage( hFile, filename, blk );
383     }
384     break;
385   default:
386     FIXME("EXEC load type %d not implemented\n", func);
387     SetLastError(ERROR_INVALID_FUNCTION);
388     break;
389   }
390   CloseHandle(hFile);
391   return ret;
392 }
393
394 /***********************************************************************
395  *              MZ_AllocDPMITask
396  */
397 void WINAPI MZ_AllocDPMITask( void )
398 {
399   MZ_InitMemory();
400   MZ_InitTask();
401 }
402
403 /***********************************************************************
404  *              MZ_RunInThread
405  */
406 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
407 {
408   if (loop_thread) {
409     DOS_SPC spc;
410     HANDLE event;
411
412     spc.proc = proc;
413     spc.arg = arg;
414     event = CreateEventA(NULL, TRUE, FALSE, NULL);
415     PostThreadMessageA(loop_tid, WM_USER, event, (LPARAM)&spc);
416     WaitForSingleObject(event, INFINITE);
417     CloseHandle(event);
418   } else
419     proc(arg);
420 }
421
422 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
423 {
424   CONTEXT context;
425   DWORD ret;
426
427   dosvm_pid = getpid();
428
429   memset( &context, 0, sizeof(context) );
430   context.SegCs  = init_cs;
431   context.Eip    = init_ip;
432   context.SegSs  = init_ss;
433   context.Esp    = init_sp;
434   context.SegDs  = DOSVM_psp;
435   context.SegEs  = DOSVM_psp;
436   context.EFlags = 0x00080000;  /* virtual interrupt flag */
437   DOSVM_SetTimer(0x10000);
438   ret = DOSVM_Enter( &context );
439
440   dosvm_pid = 0;
441   return ret;
442 }
443
444 static BOOL MZ_InitTask(void)
445 {
446   if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
447                        GetCurrentProcess(), &loop_thread,
448                        0, FALSE, DUPLICATE_SAME_ACCESS))
449     return FALSE;
450   dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
451   if (!dosvm_thread) {
452     CloseHandle(loop_thread);
453     loop_thread = 0;
454     return FALSE;
455   }
456   loop_tid = GetCurrentThreadId();
457   return TRUE;
458 }
459
460 static void MZ_Launch(void)
461 {
462   TDB *pTask = TASK_GetCurrent();
463   BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
464
465   MZ_FillPSP(psp_start, GetCommandLineA());
466   pTask->flags |= TDBF_WINOLDAP;
467
468   _LeaveWin16Lock();
469   
470   ResumeThread(dosvm_thread);
471   DOSVM_Loop(NULL);
472   ExitThread(0);
473 }
474
475 static void MZ_KillTask(void)
476 {
477   TRACE("killing DOS task\n");
478   VGA_Clean();
479   PostThreadMessageA(loop_tid, WM_QUIT, 0, 0);
480   WaitForSingleObject(loop_thread, INFINITE); /* ? */
481   CloseHandle(dosvm_thread);
482   dosvm_thread = 0; dosvm_tid = 0;
483   CloseHandle(loop_thread);
484   loop_thread = 0; loop_tid = 0;
485 }
486
487 /***********************************************************************
488  *              MZ_Exit
489  */
490 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
491 {
492   if (DOSVM_psp) {
493     WORD psp_seg = cs_psp ? context->SegCs : DOSVM_psp;
494     LPBYTE psp_start = (LPBYTE)((DWORD)psp_seg << 4);
495     PDB16 *psp = (PDB16 *)psp_start;
496     WORD parpsp = psp->parentPSP; /* check for parent DOS process */
497     if (parpsp) {
498       /* retrieve parent's return address */
499       FARPROC16 retaddr = DOSVM_GetRMHandler(0x22);
500       /* restore interrupts */
501       DOSVM_SetRMHandler(0x22, psp->savedint22);
502       DOSVM_SetRMHandler(0x23, psp->savedint23);
503       DOSVM_SetRMHandler(0x24, psp->savedint24);
504       /* FIXME: deallocate file handles etc */
505       /* free process's associated memory
506        * FIXME: walk memory and deallocate all blocks owned by process */
507       DOSMEM_FreeBlock(DOSMEM_MapRealToLinear(MAKELONG(0,psp->environment)));
508       DOSMEM_FreeBlock(DOSMEM_MapRealToLinear(MAKELONG(0,DOSVM_psp)));
509       /* switch to parent's PSP */
510       DOSVM_psp = parpsp;
511       psp_start = (LPBYTE)((DWORD)parpsp << 4);
512       psp = (PDB16 *)psp_start;
513       /* now return to parent */
514       DOSVM_retval = retval;
515       context->SegCs = SELECTOROF(retaddr);
516       context->Eip   = OFFSETOF(retaddr);
517       context->SegSs = SELECTOROF(psp->saveStack);
518       context->Esp   = OFFSETOF(psp->saveStack);
519       return;
520     } else
521       MZ_KillTask();
522   }
523   ExitThread( retval );
524 }
525
526
527 /***********************************************************************
528  *              MZ_Current
529  */
530 BOOL WINAPI MZ_Current( void )
531 {
532   return (dosvm_pid != 0); /* FIXME: do a better check */
533 }
534
535 #else /* !MZ_SUPPORTED */
536
537 /***********************************************************************
538  *              LoadDosExe (WINEDOS.@)
539  */
540 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
541 {
542   WARN("DOS executables not supported on this platform\n");
543   SetLastError(ERROR_BAD_FORMAT);
544 }
545
546 /***********************************************************************
547  *              MZ_Exec
548  */
549 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
550 {
551   /* can't happen */
552   SetLastError(ERROR_BAD_FORMAT);
553   return FALSE;
554 }
555
556 /***********************************************************************
557  *              MZ_AllocDPMITask
558  */
559 void WINAPI MZ_AllocDPMITask( void )
560 {
561     ERR("Actual real-mode calls not supported on this platform!\n");
562 }
563
564 /***********************************************************************
565  *              MZ_Exit
566  */
567 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
568 {
569   ExitThread( retval );
570 }
571
572 /***********************************************************************
573  *              MZ_Current
574  */
575 BOOL WINAPI MZ_Current( void )
576 {
577     return FALSE;
578 }
579
580 #endif /* !MZ_SUPPORTED */