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