4 * Copyright 1998 Ove Kåven
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.
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.
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
20 * Note: This code hasn't been completely cleaned up yet.
24 #include "wine/port.h"
34 #include <sys/types.h>
36 #ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
40 #include "wine/winbase16.h"
47 #include "wine/debug.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(module);
54 static BOOL DOSVM_isdosexe;
56 /**********************************************************************
59 * Return TRUE if we are in Windows process.
61 BOOL DOSVM_IsWin16(void)
63 return DOSVM_isdosexe ? FALSE : TRUE;
68 #ifdef HAVE_SYS_MMAN_H
69 # include <sys/mman.h>
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 */
76 #define BIOS_DATA_SEGMENT 0x40
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)))
82 /* structures for EXEC */
86 DWORD cmdline WINE_PACKED;
87 DWORD fcb1 WINE_PACKED;
88 DWORD fcb2 WINE_PACKED;
100 /* global variables */
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;
108 static void MZ_Launch(void);
109 static BOOL MZ_InitTask(void);
111 static void MZ_CreatePSP( LPVOID lpPSP, WORD env, WORD par )
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);
123 psp->environment=env;
124 /* FIXME: more PSP stuff */
127 static void MZ_FillPSP( LPVOID lpPSP, LPBYTE cmdline, int length )
131 while(length > 0 && *cmdline != ' ') {
136 /* command.com does not skip over multiple spaces */
140 * FIXME: If length > 126 we should put truncated command line to
141 * PSP and store the entire command line in the environment
144 FIXME("Command line truncated! (length %d > maximum length 126)\n",
149 psp->cmdLine[0] = length;
151 memmove(psp->cmdLine+1, cmdline, length);
152 psp->cmdLine[length+1] = '\r';
154 /* FIXME: more PSP stuff */
157 /* default INT 08 handler: increases timer tick counter but not much more */
158 static char int08[]={
159 0xCD,0x1C, /* int $0x1c */
160 0x50, /* pushw %ax */
161 0x1E, /* pushw %ds */
162 0xB8,0x40,0x00, /* movw $0x40,%ax */
163 0x8E,0xD8, /* movw %ax,%ds */
165 0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
166 0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
168 0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
170 0xB0,0x20, /* movb $0x20,%al */
171 0xE6,0x20, /* outb %al,$0x20 */
177 static void MZ_InitHandlers(void)
180 LPBYTE start = DOSVM_AllocCodeUMB( sizeof(int08), &seg, 0 );
181 memcpy(start,int08,sizeof(int08));
182 /* INT 08: point it at our tick-incrementing handler */
183 ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
184 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
185 ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
188 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
195 /* get size of environment block */
196 while (env[sz++]) sz+=strlen(env+sz)+1;
199 envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
202 memcpy(envblk,env,sz);
204 /* DOS 3.x: the block contains 1 additional string */
205 *(WORD*)(envblk+sz)=1;
206 /* being the program name itself */
207 strcpy(envblk+sz+sizeof(WORD),name);
211 static BOOL MZ_InitMemory(void)
213 /* initialize the memory */
214 TRACE("Initializing DOS memory structures\n");
216 DOSDEV_InstallDOSDevices();
222 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
224 IMAGE_DOS_HEADER mz_header;
225 DWORD image_start,image_size,min_size,max_size,avail;
226 BYTE*psp_start,*load_start,*oldenv;
227 int x, old_com=0, alloc;
229 WORD env_seg, load_seg, rel_seg, oldpsp_seg;
233 /* DOS process already running, inherit from it */
234 PDB16* par_psp = (PDB16*)((DWORD)DOSVM_psp << 4);
236 oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
237 oldpsp_seg = DOSVM_psp;
239 /* allocate new DOS process, inheriting from Wine environment */
241 oldenv = GetEnvironmentStringsA();
245 SetFilePointer(hFile,0,NULL,FILE_BEGIN);
246 if ( !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
247 || len != sizeof(mz_header)
248 || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
249 char *p = strrchr( filename, '.' );
250 if (!p || strcasecmp( p, ".com" )) /* check for .COM extension */
252 SetLastError(ERROR_BAD_FORMAT);
255 old_com=1; /* assume .COM file */
257 image_size=GetFileSize(hFile,NULL);
258 min_size=0x10000; max_size=0x100000;
260 mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
261 mz_header.e_cs=0; mz_header.e_ip=0x100;
263 /* calculate load size */
264 image_start=mz_header.e_cparhdr<<4;
265 image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
266 if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
267 image_size-=image_start;
268 min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
269 max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
272 if (alloc) MZ_InitMemory();
275 /* load overlay into preallocated memory */
276 load_seg=oblk->load_seg;
277 rel_seg=oblk->rel_seg;
278 load_start=(LPBYTE)((DWORD)load_seg<<4);
280 /* allocate environment block */
281 env_seg=MZ_InitEnvironment(oldenv, filename);
283 /* allocate memory for the executable */
284 TRACE("Allocating DOS memory (min=%ld, max=%ld)\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);
291 if (avail>max_size) avail=max_size;
292 psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
294 ERR("error allocating DOS memory\n");
295 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
298 load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
300 load_start=psp_start+(PSP_SIZE<<4);
301 MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
304 /* load executable image */
305 TRACE("loading DOS %s image, %08lx 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 SetLastError(ERROR_BAD_FORMAT);
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);
322 *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
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;
332 TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
335 if (alloc && !MZ_InitTask()) {
336 SetLastError(ERROR_GEN_FAILURE);
343 DOSVM_psp = oldpsp_seg;
348 /***********************************************************************
349 * LoadDosExe (WINEDOS.@)
351 * Called from Wine loader when a new real-mode DOS process is started.
352 * Loads DOS program into memory and executes the program.
354 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
356 DOSVM_isdosexe = TRUE;
357 if (MZ_DoLoadImage( hFile, filename, NULL )) MZ_Launch();
360 /***********************************************************************
363 * this may only be called from existing DOS processes
365 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
369 PROCESS_INFORMATION pe;
374 if(!GetBinaryTypeA(filename, &binType)) /* determine what kind of binary this is */
376 return FALSE; /* binary is not an executable */
379 /* handle non-dos executables */
380 if(binType != SCS_DOS_BINARY)
382 if(func == 0) /* load and execute */
386 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
387 PDB16 *psp = (PDB16 *)psp_start;
388 ExecBlock *blk = (ExecBlock *)paramblk;
389 LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
390 LPBYTE envblock = PTR_REAL_TO_LIN(psp->environment, 0);
391 BYTE cmdLength = cmdline[0];
394 * FIXME: If cmdLength == 126, PSP may contain truncated version
395 * of the full command line. In this case environment
396 * variable CMDLINE contains the entire command line.
399 fullCmdLength = (strlen(filename) + 1) + cmdLength + 1; /* filename + space + cmdline + terminating null character */
401 fullCmdLine = HeapAlloc(GetProcessHeap(), 0, fullCmdLength);
402 if(!fullCmdLine) return FALSE; /* return false on memory alloc failure */
404 /* build the full command line from the executable file and the command line being passed in */
405 snprintf(fullCmdLine, fullCmdLength, "%s ", filename); /* start off with the executable filename and a space */
406 memcpy(fullCmdLine + strlen(fullCmdLine), cmdline + 1, cmdLength); /* append cmdline onto the end */
407 fullCmdLine[fullCmdLength - 1] = 0; /* null terminate string */
409 ZeroMemory (&st, sizeof(STARTUPINFOA));
410 st.cb = sizeof(STARTUPINFOA);
411 ret = CreateProcessA (NULL, fullCmdLine, NULL, NULL, TRUE, 0, envblock, NULL, &st, &pe);
413 /* wait for the app to finish and clean up PROCESS_INFORMATION handles */
416 WaitForSingleObject(pe.hProcess, INFINITE); /* wait here until the child process is complete */
417 CloseHandle(pe.hProcess);
418 CloseHandle(pe.hThread);
421 HeapFree(GetProcessHeap(), 0, fullCmdLine); /* free the memory we allocated */
425 FIXME("EXEC type of %d not implemented for non-dos executables\n", func);
430 } /* if(binType != SCS_DOS_BINARY) */
433 /* handle dos executables */
435 hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
436 NULL, OPEN_EXISTING, 0, 0);
437 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
440 case 0: /* load and execute */
441 case 1: /* load but don't execute */
443 /* save current process's return SS:SP now */
444 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
445 PDB16 *psp = (PDB16 *)psp_start;
446 psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
448 ret = MZ_DoLoadImage( hFile, filename, NULL );
450 /* MZ_LoadImage created a new PSP and loaded new values into it,
451 * let's work on the new values now */
452 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
453 ExecBlock *blk = (ExecBlock *)paramblk;
454 LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
456 /* First character contains the length of the command line. */
457 MZ_FillPSP(psp_start, cmdline + 1, cmdline[0]);
459 /* the lame MS-DOS engineers decided that the return address should be in int22 */
460 DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
462 /* don't execute, just return startup state */
463 blk->init_cs = init_cs;
464 blk->init_ip = init_ip;
465 blk->init_ss = init_ss;
466 blk->init_sp = init_sp;
468 /* execute by making us return to new process */
469 context->SegCs = init_cs;
470 context->Eip = init_ip;
471 context->SegSs = init_ss;
472 context->Esp = init_sp;
473 context->SegDs = DOSVM_psp;
474 context->SegEs = DOSVM_psp;
479 case 3: /* load overlay */
481 OverlayBlock *blk = (OverlayBlock *)paramblk;
482 ret = MZ_DoLoadImage( hFile, filename, blk );
486 FIXME("EXEC load type %d not implemented\n", func);
487 SetLastError(ERROR_INVALID_FUNCTION);
494 /***********************************************************************
497 void WINAPI MZ_AllocDPMITask( void )
503 /***********************************************************************
506 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
514 event = CreateEventA(NULL, TRUE, FALSE, NULL);
515 PostThreadMessageA(loop_tid, WM_USER, (WPARAM)event, (LPARAM)&spc);
516 WaitForSingleObject(event, INFINITE);
522 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
527 dosvm_pid = getpid();
529 memset( &context, 0, sizeof(context) );
530 context.SegCs = init_cs;
531 context.Eip = init_ip;
532 context.SegSs = init_ss;
533 context.Esp = init_sp;
534 context.SegDs = DOSVM_psp;
535 context.SegEs = DOSVM_psp;
536 context.EFlags = 0x00080000; /* virtual interrupt flag */
537 DOSVM_SetTimer(0x10000);
538 ret = DOSVM_Enter( &context );
544 static BOOL MZ_InitTask(void)
546 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
547 GetCurrentProcess(), &loop_thread,
548 0, FALSE, DUPLICATE_SAME_ACCESS))
550 dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
552 CloseHandle(loop_thread);
556 loop_tid = GetCurrentThreadId();
560 static void MZ_Launch(void)
562 TDB *pTask = GlobalLock16( GetCurrentTask() );
563 BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
564 LPSTR cmdline = GetCommandLineA();
568 MZ_FillPSP(psp_start, cmdline, cmdline ? strlen(cmdline) : 0);
569 pTask->flags |= TDBF_WINOLDAP;
571 /* DTA is set to PSP:0080h when a program is started. */
572 pTask->dta = MAKESEGPTR( DOSVM_psp, 0x80 );
574 GetpWin16Lock( &lock );
575 _LeaveSysLevel( lock );
577 ResumeThread(dosvm_thread);
578 rv = DOSVM_Loop(dosvm_thread);
580 CloseHandle(dosvm_thread);
581 dosvm_thread = 0; dosvm_tid = 0;
582 CloseHandle(loop_thread);
583 loop_thread = 0; loop_tid = 0;
589 /***********************************************************************
592 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
595 WORD psp_seg = cs_psp ? context->SegCs : DOSVM_psp;
596 LPBYTE psp_start = (LPBYTE)((DWORD)psp_seg << 4);
597 PDB16 *psp = (PDB16 *)psp_start;
598 WORD parpsp = psp->parentPSP; /* check for parent DOS process */
600 /* retrieve parent's return address */
601 FARPROC16 retaddr = DOSVM_GetRMHandler(0x22);
602 /* restore interrupts */
603 DOSVM_SetRMHandler(0x22, psp->savedint22);
604 DOSVM_SetRMHandler(0x23, psp->savedint23);
605 DOSVM_SetRMHandler(0x24, psp->savedint24);
606 /* FIXME: deallocate file handles etc */
607 /* free process's associated memory
608 * FIXME: walk memory and deallocate all blocks owned by process */
609 DOSMEM_FreeBlock( PTR_REAL_TO_LIN(psp->environment,0) );
610 DOSMEM_FreeBlock( PTR_REAL_TO_LIN(DOSVM_psp,0) );
611 /* switch to parent's PSP */
613 psp_start = (LPBYTE)((DWORD)parpsp << 4);
614 psp = (PDB16 *)psp_start;
615 /* now return to parent */
616 DOSVM_retval = retval;
617 context->SegCs = SELECTOROF(retaddr);
618 context->Eip = OFFSETOF(retaddr);
619 context->SegSs = SELECTOROF(psp->saveStack);
620 context->Esp = OFFSETOF(psp->saveStack);
623 TRACE("killing DOS task\n");
625 ExitThread( retval );
629 /***********************************************************************
632 BOOL WINAPI MZ_Current( void )
634 return (dosvm_pid != 0); /* FIXME: do a better check */
637 #else /* !MZ_SUPPORTED */
639 /***********************************************************************
640 * LoadDosExe (WINEDOS.@)
642 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
644 WARN("DOS executables not supported on this platform\n");
645 SetLastError(ERROR_BAD_FORMAT);
648 /***********************************************************************
651 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
654 SetLastError(ERROR_BAD_FORMAT);
658 /***********************************************************************
661 void WINAPI MZ_AllocDPMITask( void )
663 ERR("Actual real-mode calls not supported on this platform!\n");
666 /***********************************************************************
669 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
674 /***********************************************************************
677 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
679 ExitThread( retval );
682 /***********************************************************************
685 BOOL WINAPI MZ_Current( void )
690 #endif /* !MZ_SUPPORTED */