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