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