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