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