Split timer code into separate source file.
[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 <fcntl.h>
30 #include <signal.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
38 #endif
39 #include "windef.h"
40 #include "wine/winbase16.h"
41 #include "wingdi.h"
42 #include "winuser.h"
43 #include "winerror.h"
44 #include "task.h"
45 #include "file.h"
46 #include "miscemu.h"
47 #include "wine/debug.h"
48 #include "dosexe.h"
49 #include "dosvm.h"
50 #include "vga.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(module);
53
54 static BOOL DOSVM_isdosexe;
55
56 /**********************************************************************
57  *          DOSVM_IsWin16
58  * 
59  * Return TRUE if we are in Windows process.
60  */
61 BOOL DOSVM_IsWin16(void)
62 {
63   return DOSVM_isdosexe ? FALSE : TRUE;
64 }
65
66 #ifdef MZ_SUPPORTED
67
68 #ifdef HAVE_SYS_MMAN_H
69 # include <sys/mman.h>
70 #endif
71
72 /* define this to try mapping through /proc/pid/mem instead of a temp file,
73    but Linus doesn't like mmapping /proc/pid/mem, so it doesn't work for me */
74 #undef MZ_MAPSELF
75
76 #define BIOS_DATA_SEGMENT 0x40
77 #define PSP_SIZE 0x10
78
79 #define SEG16(ptr,seg) ((LPVOID)((BYTE*)ptr+((DWORD)(seg)<<4)))
80 #define SEGPTR16(ptr,segptr) ((LPVOID)((BYTE*)ptr+((DWORD)SELECTOROF(segptr)<<4)+OFFSETOF(segptr)))
81
82 /* structures for EXEC */
83
84 typedef struct {
85   WORD env_seg;
86   DWORD cmdline WINE_PACKED;
87   DWORD fcb1 WINE_PACKED;
88   DWORD fcb2 WINE_PACKED;
89   WORD init_sp;
90   WORD init_ss;
91   WORD init_ip;
92   WORD init_cs;
93 } ExecBlock;
94
95 typedef struct {
96   WORD load_seg;
97   WORD rel_seg;
98 } OverlayBlock;
99
100 /* global variables */
101
102 pid_t dosvm_pid;
103
104 static WORD init_cs,init_ip,init_ss,init_sp;
105 static HANDLE dosvm_thread, loop_thread;
106 static DWORD dosvm_tid, loop_tid;
107
108 static void MZ_Launch( LPCSTR cmdtail, int length );
109 static BOOL MZ_InitTask(void);
110
111 static void MZ_CreatePSP( LPVOID lpPSP, WORD env, WORD par )
112 {
113   PDB16*psp=lpPSP;
114
115   psp->int20=0x20CD; /* int 20 */
116   /* some programs use this to calculate how much memory they need */
117   psp->nextParagraph=0x9FFF; /* FIXME: use a real value */
118   /* FIXME: dispatcher */
119   psp->savedint22 = DOSVM_GetRMHandler(0x22);
120   psp->savedint23 = DOSVM_GetRMHandler(0x23);
121   psp->savedint24 = DOSVM_GetRMHandler(0x24);
122   psp->parentPSP=par;
123   psp->environment=env;
124   /* FIXME: more PSP stuff */
125 }
126
127 static void MZ_FillPSP( LPVOID lpPSP, LPCSTR cmdtail, int length )
128 {
129     PDB16 *psp = lpPSP;
130
131     if(length > 127) 
132     {
133         WARN( "Command tail truncated! (length %d)\n", length );
134         length = 126;
135     }
136
137     psp->cmdLine[0] = length;
138
139     /*
140      * Length of exactly 127 bytes means that full command line is 
141      * stored in environment variable CMDLINE and PSP contains 
142      * command tail truncated to 126 bytes.
143      */
144     if(length == 127)
145         length = 126;
146
147     if(length > 0)
148         memmove(psp->cmdLine+1, cmdtail, length);
149
150     psp->cmdLine[length+1] = '\r';
151
152     /* FIXME: more PSP stuff */
153 }
154
155 /* default INT 08 handler: increases timer tick counter but not much more */
156 static char int08[]={
157  0xCD,0x1C,           /* int $0x1c */
158  0x50,                /* pushw %ax */
159  0x1E,                /* pushw %ds */
160  0xB8,0x40,0x00,      /* movw $0x40,%ax */
161  0x8E,0xD8,           /* movw %ax,%ds */
162 #if 0
163  0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
164  0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
165 #else
166  0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
167 #endif
168  0xB0,0x20,           /* movb $0x20,%al */
169  0xE6,0x20,           /* outb %al,$0x20 */
170  0x1F,                /* popw %ax */
171  0x58,                /* popw %ax */
172  0xCF                 /* iret */
173 };
174
175 static void MZ_InitHandlers(void)
176 {
177  WORD seg;
178  LPBYTE start = DOSVM_AllocCodeUMB( sizeof(int08), &seg, 0 );
179  memcpy(start,int08,sizeof(int08));
180 /* INT 08: point it at our tick-incrementing handler */
181  ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
182 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
183  ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
184 }
185
186 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
187 {
188  unsigned sz=0;
189  WORD seg;
190  LPSTR envblk;
191
192  if (env) {
193   /* get size of environment block */
194   while (env[sz++]) sz+=strlen(env+sz)+1;
195  } else sz++;
196  /* allocate it */
197  envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
198  /* fill it */
199  if (env) {
200   memcpy(envblk,env,sz);
201  } else envblk[0]=0;
202  /* DOS 3.x: the block contains 1 additional string */
203  *(WORD*)(envblk+sz)=1;
204  /* being the program name itself */
205  strcpy(envblk+sz+sizeof(WORD),name);
206  return seg;
207 }
208
209 static BOOL MZ_InitMemory(void)
210 {
211     /* initialize the memory */
212     TRACE("Initializing DOS memory structures\n");
213     DOSMEM_Init(TRUE);
214     DOSDEV_InstallDOSDevices();
215
216     MZ_InitHandlers();
217     return TRUE;
218 }
219
220 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
221 {
222   IMAGE_DOS_HEADER mz_header;
223   DWORD image_start,image_size,min_size,max_size,avail;
224   BYTE*psp_start,*load_start,*oldenv;
225   int x, old_com=0, alloc;
226   SEGPTR reloc;
227   WORD env_seg, load_seg, rel_seg, oldpsp_seg;
228   DWORD len;
229
230   if (DOSVM_psp) {
231     /* DOS process already running, inherit from it */
232     PDB16* par_psp = (PDB16*)((DWORD)DOSVM_psp << 4);
233     alloc=0;
234     oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
235     oldpsp_seg = DOSVM_psp;
236   } else {
237     /* allocate new DOS process, inheriting from Wine environment */
238     alloc=1;
239     oldenv = GetEnvironmentStringsA();
240     oldpsp_seg = 0;
241   }
242
243  SetFilePointer(hFile,0,NULL,FILE_BEGIN);
244  if (   !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
245      || len != sizeof(mz_header)
246      || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
247   char *p = strrchr( filename, '.' );
248   if (!p || strcasecmp( p, ".com" ))  /* check for .COM extension */
249   {
250       SetLastError(ERROR_BAD_FORMAT);
251       goto load_error;
252   }
253   old_com=1; /* assume .COM file */
254   image_start=0;
255   image_size=GetFileSize(hFile,NULL);
256   min_size=0x10000; max_size=0x100000;
257   mz_header.e_crlc=0;
258   mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
259   mz_header.e_cs=0; mz_header.e_ip=0x100;
260  } else {
261   /* calculate load size */
262   image_start=mz_header.e_cparhdr<<4;
263   image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
264   if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
265   image_size-=image_start;
266   min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
267   max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
268  }
269
270   if (alloc) MZ_InitMemory();
271
272   if (oblk) {
273     /* load overlay into preallocated memory */
274     load_seg=oblk->load_seg;
275     rel_seg=oblk->rel_seg;
276     load_start=(LPBYTE)((DWORD)load_seg<<4);
277   } else {
278     /* allocate environment block */
279     env_seg=MZ_InitEnvironment(oldenv, filename);
280
281     /* allocate memory for the executable */
282     TRACE("Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
283     avail=DOSMEM_Available();
284     if (avail<min_size) {
285       ERR("insufficient DOS memory\n");
286       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
287       goto load_error;
288     }
289     if (avail>max_size) avail=max_size;
290     psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
291     if (!psp_start) {
292       ERR("error allocating DOS memory\n");
293       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
294       goto load_error;
295     }
296     load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
297     rel_seg=load_seg;
298     load_start=psp_start+(PSP_SIZE<<4);
299     MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
300   }
301
302  /* load executable image */
303  TRACE("loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
304  SetFilePointer(hFile,image_start,NULL,FILE_BEGIN);
305  if (!ReadFile(hFile,load_start,image_size,&len,NULL) || len != image_size) {
306   SetLastError(ERROR_BAD_FORMAT);
307   goto load_error;
308  }
309
310  if (mz_header.e_crlc) {
311   /* load relocation table */
312   TRACE("loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
313   /* FIXME: is this too slow without read buffering? */
314   SetFilePointer(hFile,mz_header.e_lfarlc,NULL,FILE_BEGIN);
315   for (x=0; x<mz_header.e_crlc; x++) {
316    if (!ReadFile(hFile,&reloc,sizeof(reloc),&len,NULL) || len != sizeof(reloc)) {
317     SetLastError(ERROR_BAD_FORMAT);
318     goto load_error;
319    }
320    *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
321   }
322  }
323
324   if (!oblk) {
325     init_cs = load_seg+mz_header.e_cs;
326     init_ip = mz_header.e_ip;
327     init_ss = load_seg+mz_header.e_ss;
328     init_sp = mz_header.e_sp;
329
330     TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
331   }
332
333   if (alloc && !MZ_InitTask()) {
334     SetLastError(ERROR_GEN_FAILURE);
335     return FALSE;
336   }
337
338   return TRUE;
339
340 load_error:
341   DOSVM_psp = oldpsp_seg;
342
343   return FALSE;
344 }
345
346 /***********************************************************************
347  *              wine_load_dos_exe (WINEDOS.@)
348  *
349  * Called from WineVDM when a new real-mode DOS process is started.
350  * Loads DOS program into memory and executes the program.
351  */
352 void WINAPI wine_load_dos_exe( LPCSTR filename, LPCSTR cmdline )
353 {
354     char dos_cmdtail[126];
355     int  dos_length = 0;
356
357     HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ, 
358                                 NULL, OPEN_EXISTING, 0, 0 );
359     if (hFile == INVALID_HANDLE_VALUE) return;
360     DOSVM_isdosexe = TRUE;
361
362     if(cmdline && *cmdline)
363     {
364         dos_length = strlen(cmdline);
365         memmove( dos_cmdtail + 1, cmdline, 
366                  (dos_length < 125) ? dos_length : 125 );
367
368         /* Non-empty command tail always starts with at least one space. */
369         dos_cmdtail[0] = ' ';
370         dos_length++;
371
372         /*
373          * If command tail is longer than 126 characters,
374          * set tail length to 127 and fill CMDLINE environment variable 
375          * with full command line (this includes filename).
376          */
377         if (dos_length > 126)
378         {
379             char *cmd = HeapAlloc( GetProcessHeap(), 0, 
380                                    dos_length + strlen(filename) + 4 );
381             char *ptr = cmd;
382
383             if (!cmd)
384                 return;
385
386             /*
387              * Append filename. If path includes spaces, quote the path.
388              */
389             if (strchr(filename, ' '))
390             {
391                 *ptr++ = '\"';
392                 strcpy( ptr, filename );
393                 ptr += strlen(filename);                   
394                 *ptr++ = '\"';
395             }
396             else
397             {
398                 strcpy( ptr, filename );
399                 ptr += strlen(filename);  
400             }
401
402             /*
403              * Append command tail.
404              */
405             if (cmdline[0] != ' ')
406                 *ptr++ = ' ';
407             strcpy( ptr, cmdline );
408
409             /*
410              * Set environment variable. This will be passed to
411              * new DOS process.
412              */
413             if (!SetEnvironmentVariableA( "CMDLINE", cmd ))
414             {
415                 HeapFree(GetProcessHeap(), 0, cmd );
416                 return;
417             }
418
419             HeapFree(GetProcessHeap(), 0, cmd );
420             dos_length = 127;
421         }
422     }
423
424     if (MZ_DoLoadImage( hFile, filename, NULL )) 
425         MZ_Launch( dos_cmdtail, dos_length );
426 }
427
428 /***********************************************************************
429  *              MZ_Exec
430  *
431  * this may only be called from existing DOS processes
432  */
433 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
434 {
435   DWORD binType;
436   STARTUPINFOA st;
437   PROCESS_INFORMATION pe;
438   HANDLE hFile;
439
440   BOOL ret = FALSE;
441
442   if(!GetBinaryTypeA(filename, &binType))   /* determine what kind of binary this is */
443   {
444     return FALSE; /* binary is not an executable */
445   }
446
447   /* handle non-dos executables */
448   if(binType != SCS_DOS_BINARY)
449   {
450     if(func == 0) /* load and execute */
451     {
452       LPBYTE fullCmdLine;
453       WORD fullCmdLength;
454       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
455       PDB16 *psp = (PDB16 *)psp_start;
456       ExecBlock *blk = (ExecBlock *)paramblk;
457       LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
458       LPBYTE envblock = PTR_REAL_TO_LIN(psp->environment, 0);
459       int    cmdLength = cmdline[0];
460
461       /*
462        * If cmdLength is 127, command tail is truncated and environment 
463        * variable CMDLINE should contain full command line 
464        * (this includes filename).
465        */
466       if (cmdLength == 127)
467       {
468           FIXME( "CMDLINE argument passing is unimplemented.\n" );
469           cmdLength = 126; /* FIXME */
470       }
471
472       fullCmdLength = (strlen(filename) + 1) + cmdLength + 1; /* filename + space + cmdline + terminating null character */
473
474       fullCmdLine = HeapAlloc(GetProcessHeap(), 0, fullCmdLength);
475       if(!fullCmdLine) return FALSE; /* return false on memory alloc failure */
476
477       /* build the full command line from the executable file and the command line being passed in */
478       snprintf(fullCmdLine, fullCmdLength, "%s ", filename); /* start off with the executable filename and a space */
479       memcpy(fullCmdLine + strlen(fullCmdLine), cmdline + 1, cmdLength); /* append cmdline onto the end */
480       fullCmdLine[fullCmdLength - 1] = 0; /* null terminate string */
481
482       ZeroMemory (&st, sizeof(STARTUPINFOA));
483       st.cb = sizeof(STARTUPINFOA);
484       ret = CreateProcessA (NULL, fullCmdLine, NULL, NULL, TRUE, 0, envblock, NULL, &st, &pe);
485
486       /* wait for the app to finish and clean up PROCESS_INFORMATION handles */
487       if(ret)
488       {
489         WaitForSingleObject(pe.hProcess, INFINITE);  /* wait here until the child process is complete */
490         CloseHandle(pe.hProcess);
491         CloseHandle(pe.hThread);
492       }
493
494       HeapFree(GetProcessHeap(), 0, fullCmdLine);  /* free the memory we allocated */
495     }
496     else
497     {
498       FIXME("EXEC type of %d not implemented for non-dos executables\n", func);
499       ret = FALSE;
500     }
501
502     return ret;
503   } /* if(binType != SCS_DOS_BINARY) */
504
505
506   /* handle dos executables */
507
508   hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
509                              NULL, OPEN_EXISTING, 0, 0);
510   if (hFile == INVALID_HANDLE_VALUE) return FALSE;
511
512   switch (func) {
513   case 0: /* load and execute */
514   case 1: /* load but don't execute */
515     {
516       /* save current process's return SS:SP now */
517       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
518       PDB16 *psp = (PDB16 *)psp_start;
519       psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
520     }
521     ret = MZ_DoLoadImage( hFile, filename, NULL );
522     if (ret) {
523       /* MZ_LoadImage created a new PSP and loaded new values into it,
524        * let's work on the new values now */
525       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
526       ExecBlock *blk = (ExecBlock *)paramblk;
527       LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
528
529       /* First character contains the length of the command line. */
530       MZ_FillPSP(psp_start, cmdline + 1, cmdline[0]);
531
532       /* the lame MS-DOS engineers decided that the return address should be in int22 */
533       DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
534       if (func) {
535         /* don't execute, just return startup state */
536         blk->init_cs = init_cs;
537         blk->init_ip = init_ip;
538         blk->init_ss = init_ss;
539         blk->init_sp = init_sp;
540       } else {
541         /* execute by making us return to new process */
542         context->SegCs = init_cs;
543         context->Eip   = init_ip;
544         context->SegSs = init_ss;
545         context->Esp   = init_sp;
546         context->SegDs = DOSVM_psp;
547         context->SegEs = DOSVM_psp;
548         context->Eax   = 0;
549       }
550     }
551     break;
552   case 3: /* load overlay */
553     {
554       OverlayBlock *blk = (OverlayBlock *)paramblk;
555       ret = MZ_DoLoadImage( hFile, filename, blk );
556     }
557     break;
558   default:
559     FIXME("EXEC load type %d not implemented\n", func);
560     SetLastError(ERROR_INVALID_FUNCTION);
561     break;
562   }
563   CloseHandle(hFile);
564   return ret;
565 }
566
567 /***********************************************************************
568  *              MZ_AllocDPMITask
569  */
570 void WINAPI MZ_AllocDPMITask( void )
571 {
572   MZ_InitMemory();
573   MZ_InitTask();
574 }
575
576 /***********************************************************************
577  *              MZ_RunInThread
578  */
579 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
580 {
581   if (loop_thread) {
582     DOS_SPC spc;
583     HANDLE event;
584
585     spc.proc = proc;
586     spc.arg = arg;
587     event = CreateEventA(NULL, TRUE, FALSE, NULL);
588     PostThreadMessageA(loop_tid, WM_USER, (WPARAM)event, (LPARAM)&spc);
589     WaitForSingleObject(event, INFINITE);
590     CloseHandle(event);
591   } else
592     proc(arg);
593 }
594
595 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
596 {
597   CONTEXT context;
598   DWORD ret;
599
600   dosvm_pid = getpid();
601
602   memset( &context, 0, sizeof(context) );
603   context.SegCs  = init_cs;
604   context.Eip    = init_ip;
605   context.SegSs  = init_ss;
606   context.Esp    = init_sp;
607   context.SegDs  = DOSVM_psp;
608   context.SegEs  = DOSVM_psp;
609   context.EFlags = 0x00080000;  /* virtual interrupt flag */
610   DOSVM_SetTimer(0x10000);
611   ret = DOSVM_Enter( &context );
612
613   dosvm_pid = 0;
614   return ret;
615 }
616
617 static BOOL MZ_InitTask(void)
618 {
619   if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
620                        GetCurrentProcess(), &loop_thread,
621                        0, FALSE, DUPLICATE_SAME_ACCESS))
622     return FALSE;
623   dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
624   if (!dosvm_thread) {
625     CloseHandle(loop_thread);
626     loop_thread = 0;
627     return FALSE;
628   }
629   loop_tid = GetCurrentThreadId();
630   return TRUE;
631 }
632
633 static void MZ_Launch( LPCSTR cmdtail, int length )
634 {
635   TDB *pTask = GlobalLock16( GetCurrentTask() );
636   BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
637   DWORD rv;
638   SYSLEVEL *lock;
639
640   MZ_FillPSP(psp_start, cmdtail, length);
641   pTask->flags |= TDBF_WINOLDAP;
642
643   /* DTA is set to PSP:0080h when a program is started. */
644   pTask->dta = MAKESEGPTR( DOSVM_psp, 0x80 );
645
646   GetpWin16Lock( &lock );
647   _LeaveSysLevel( lock );
648
649   ResumeThread(dosvm_thread);
650   rv = DOSVM_Loop(dosvm_thread);
651
652   CloseHandle(dosvm_thread);
653   dosvm_thread = 0; dosvm_tid = 0;
654   CloseHandle(loop_thread);
655   loop_thread = 0; loop_tid = 0;
656
657   VGA_Clean();
658   ExitThread(rv);
659 }
660
661 /***********************************************************************
662  *              MZ_Exit
663  */
664 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
665 {
666   if (DOSVM_psp) {
667     WORD psp_seg = cs_psp ? context->SegCs : DOSVM_psp;
668     LPBYTE psp_start = (LPBYTE)((DWORD)psp_seg << 4);
669     PDB16 *psp = (PDB16 *)psp_start;
670     WORD parpsp = psp->parentPSP; /* check for parent DOS process */
671     if (parpsp) {
672       /* retrieve parent's return address */
673       FARPROC16 retaddr = DOSVM_GetRMHandler(0x22);
674       /* restore interrupts */
675       DOSVM_SetRMHandler(0x22, psp->savedint22);
676       DOSVM_SetRMHandler(0x23, psp->savedint23);
677       DOSVM_SetRMHandler(0x24, psp->savedint24);
678       /* FIXME: deallocate file handles etc */
679       /* free process's associated memory
680        * FIXME: walk memory and deallocate all blocks owned by process */
681       DOSMEM_FreeBlock( PTR_REAL_TO_LIN(psp->environment,0) );
682       DOSMEM_FreeBlock( PTR_REAL_TO_LIN(DOSVM_psp,0) );
683       /* switch to parent's PSP */
684       DOSVM_psp = parpsp;
685       psp_start = (LPBYTE)((DWORD)parpsp << 4);
686       psp = (PDB16 *)psp_start;
687       /* now return to parent */
688       DOSVM_retval = retval;
689       context->SegCs = SELECTOROF(retaddr);
690       context->Eip   = OFFSETOF(retaddr);
691       context->SegSs = SELECTOROF(psp->saveStack);
692       context->Esp   = OFFSETOF(psp->saveStack);
693       return;
694     } else
695       TRACE("killing DOS task\n");
696   }
697   ExitThread( retval );
698 }
699
700
701 /***********************************************************************
702  *              MZ_Current
703  */
704 BOOL WINAPI MZ_Current( void )
705 {
706   return (dosvm_pid != 0); /* FIXME: do a better check */
707 }
708
709 #else /* !MZ_SUPPORTED */
710
711 /***********************************************************************
712  *              wine_load_dos_exe (WINEDOS.@)
713  */
714 void WINAPI wine_load_dos_exe( LPCSTR filename, LPCSTR cmdline )
715 {
716   WARN("DOS executables not supported on this platform\n");
717   SetLastError(ERROR_BAD_FORMAT);
718 }
719
720 /***********************************************************************
721  *              MZ_Exec
722  */
723 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
724 {
725   /* can't happen */
726   SetLastError(ERROR_BAD_FORMAT);
727   return FALSE;
728 }
729
730 /***********************************************************************
731  *              MZ_AllocDPMITask
732  */
733 void WINAPI MZ_AllocDPMITask( void )
734 {
735     ERR("Actual real-mode calls not supported on this platform!\n");
736 }
737
738 /***********************************************************************
739  *              MZ_RunInThread
740  */
741 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
742 {
743     proc(arg);
744 }
745
746 /***********************************************************************
747  *              MZ_Exit
748  */
749 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
750 {
751   ExitThread( retval );
752 }
753
754 /***********************************************************************
755  *              MZ_Current
756  */
757 BOOL WINAPI MZ_Current( void )
758 {
759     return FALSE;
760 }
761
762 #endif /* !MZ_SUPPORTED */