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"
35 #include <sys/types.h>
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
41 #include "wine/winbase16.h"
49 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(module);
56 static BOOL DOSVM_isdosexe;
58 /**********************************************************************
61 * Return TRUE if we are in Windows process.
63 BOOL DOSVM_IsWin16(void)
65 return DOSVM_isdosexe ? FALSE : TRUE;
70 #ifdef HAVE_SYS_MMAN_H
71 # include <sys/mman.h>
74 /* define this to try mapping through /proc/pid/mem instead of a temp file,
75 but Linus doesn't like mmapping /proc/pid/mem, so it doesn't work for me */
78 #define BIOS_DATA_SEGMENT 0x40
81 #define SEG16(ptr,seg) ((LPVOID)((BYTE*)ptr+((DWORD)(seg)<<4)))
82 #define SEGPTR16(ptr,segptr) ((LPVOID)((BYTE*)ptr+((DWORD)SELECTOROF(segptr)<<4)+OFFSETOF(segptr)))
84 /* structures for EXEC */
88 DWORD cmdline WINE_PACKED;
89 DWORD fcb1 WINE_PACKED;
90 DWORD fcb2 WINE_PACKED;
102 /* global variables */
106 static WORD init_cs,init_ip,init_ss,init_sp;
107 static HANDLE dosvm_thread, loop_thread;
108 static DWORD dosvm_tid, loop_tid;
110 static void MZ_Launch(void);
111 static BOOL MZ_InitTask(void);
113 static void MZ_CreatePSP( LPVOID lpPSP, WORD env, WORD par )
117 psp->int20=0x20CD; /* int 20 */
118 /* some programs use this to calculate how much memory they need */
119 psp->nextParagraph=0x9FFF; /* FIXME: use a real value */
120 /* FIXME: dispatcher */
121 psp->savedint22 = DOSVM_GetRMHandler(0x22);
122 psp->savedint23 = DOSVM_GetRMHandler(0x23);
123 psp->savedint24 = DOSVM_GetRMHandler(0x24);
125 psp->environment=env;
126 /* FIXME: more PSP stuff */
129 static void MZ_FillPSP( LPVOID lpPSP, LPBYTE cmdline, int length )
133 while(length > 0 && *cmdline != ' ') {
138 /* command.com does not skip over multiple spaces */
141 ERR("Command line truncated! (length %d > maximum length 126)\n",
146 psp->cmdLine[0] = length;
148 memmove(psp->cmdLine+1, cmdline, length);
149 psp->cmdLine[length+1] = '\r';
151 /* FIXME: more PSP stuff */
154 /* default INT 08 handler: increases timer tick counter but not much more */
155 static char int08[]={
156 0xCD,0x1C, /* int $0x1c */
157 0x50, /* pushw %ax */
158 0x1E, /* pushw %ds */
159 0xB8,0x40,0x00, /* movw $0x40,%ax */
160 0x8E,0xD8, /* movw %ax,%ds */
162 0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
163 0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
165 0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
167 0xB0,0x20, /* movb $0x20,%al */
168 0xE6,0x20, /* outb %al,$0x20 */
174 static void MZ_InitHandlers(void)
177 LPBYTE start=DOSMEM_GetBlock(sizeof(int08),&seg);
178 memcpy(start,int08,sizeof(int08));
179 /* INT 08: point it at our tick-incrementing handler */
180 ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
181 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
182 ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
185 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
192 /* get size of environment block */
193 while (env[sz++]) sz+=strlen(env+sz)+1;
196 envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
199 memcpy(envblk,env,sz);
201 /* DOS 3.x: the block contains 1 additional string */
202 *(WORD*)(envblk+sz)=1;
203 /* being the program name itself */
204 strcpy(envblk+sz+sizeof(WORD),name);
208 static BOOL MZ_InitMemory(void)
210 /* initialize the memory */
211 TRACE("Initializing DOS memory structures\n");
213 DOSDEV_InstallDOSDevices();
219 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
221 IMAGE_DOS_HEADER mz_header;
222 DWORD image_start,image_size,min_size,max_size,avail;
223 BYTE*psp_start,*load_start,*oldenv;
224 int x, old_com=0, alloc;
226 WORD env_seg, load_seg, rel_seg, oldpsp_seg;
230 /* DOS process already running, inherit from it */
231 PDB16* par_psp = (PDB16*)((DWORD)DOSVM_psp << 4);
233 oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
234 oldpsp_seg = DOSVM_psp;
236 /* allocate new DOS process, inheriting from Wine environment */
238 oldenv = GetEnvironmentStringsA();
242 SetFilePointer(hFile,0,NULL,FILE_BEGIN);
243 if ( !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
244 || len != sizeof(mz_header)
245 || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
246 char *p = strrchr( filename, '.' );
247 if (!p || strcasecmp( p, ".com" )) /* check for .COM extension */
249 SetLastError(ERROR_BAD_FORMAT);
252 old_com=1; /* assume .COM file */
254 image_size=GetFileSize(hFile,NULL);
255 min_size=0x10000; max_size=0x100000;
257 mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
258 mz_header.e_cs=0; mz_header.e_ip=0x100;
260 /* calculate load size */
261 image_start=mz_header.e_cparhdr<<4;
262 image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
263 if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
264 image_size-=image_start;
265 min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
266 max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
269 if (alloc) MZ_InitMemory();
272 /* load overlay into preallocated memory */
273 load_seg=oblk->load_seg;
274 rel_seg=oblk->rel_seg;
275 load_start=(LPBYTE)((DWORD)load_seg<<4);
277 /* allocate environment block */
278 env_seg=MZ_InitEnvironment(oldenv, filename);
280 /* allocate memory for the executable */
281 TRACE("Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
282 avail=DOSMEM_Available();
283 if (avail<min_size) {
284 ERR("insufficient DOS memory\n");
285 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
288 if (avail>max_size) avail=max_size;
289 psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
291 ERR("error allocating DOS memory\n");
292 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
295 load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
297 load_start=psp_start+(PSP_SIZE<<4);
298 MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
301 /* load executable image */
302 TRACE("loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
303 SetFilePointer(hFile,image_start,NULL,FILE_BEGIN);
304 if (!ReadFile(hFile,load_start,image_size,&len,NULL) || len != image_size) {
305 SetLastError(ERROR_BAD_FORMAT);
309 if (mz_header.e_crlc) {
310 /* load relocation table */
311 TRACE("loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
312 /* FIXME: is this too slow without read buffering? */
313 SetFilePointer(hFile,mz_header.e_lfarlc,NULL,FILE_BEGIN);
314 for (x=0; x<mz_header.e_crlc; x++) {
315 if (!ReadFile(hFile,&reloc,sizeof(reloc),&len,NULL) || len != sizeof(reloc)) {
316 SetLastError(ERROR_BAD_FORMAT);
319 *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
324 init_cs = load_seg+mz_header.e_cs;
325 init_ip = mz_header.e_ip;
326 init_ss = load_seg+mz_header.e_ss;
327 init_sp = mz_header.e_sp;
329 TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
332 if (alloc && !MZ_InitTask()) {
333 SetLastError(ERROR_GEN_FAILURE);
340 DOSVM_psp = oldpsp_seg;
345 /***********************************************************************
346 * LoadDosExe (WINEDOS.@)
348 * Called from Wine loader when a new real-mode DOS process is started.
349 * Loads DOS program into memory and executes the program.
351 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
353 DOSVM_isdosexe = TRUE;
354 if (MZ_DoLoadImage( hFile, filename, NULL )) MZ_Launch();
357 /***********************************************************************
360 * this may only be called from existing DOS processes
362 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
366 PROCESS_INFORMATION pe;
371 if(!GetBinaryTypeA(filename, &binType)) /* determine what kind of binary this is */
373 return FALSE; /* binary is not an executable */
376 /* handle non-dos executables */
377 if(binType != SCS_DOS_BINARY)
379 if(func == 0) /* load and execute */
383 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
384 PDB16 *psp = (PDB16 *)psp_start;
385 ExecBlock *blk = (ExecBlock *)paramblk;
386 LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
387 LPBYTE envblock = PTR_REAL_TO_LIN(psp->environment, 0);
388 BYTE cmdLength = cmdline[0];
390 fullCmdLength = (strlen(filename) + 1) + cmdLength + 1; /* filename + space + cmdline + terminating null character */
392 fullCmdLine = HeapAlloc(GetProcessHeap(), 0, fullCmdLength);
393 if(!fullCmdLine) return FALSE; /* return false on memory alloc failure */
395 /* build the full command line from the executable file and the command line being passed in */
396 snprintf(fullCmdLine, fullCmdLength, "%s ", filename); /* start off with the executable filename and a space */
397 memcpy(fullCmdLine + strlen(fullCmdLine), cmdline + 1, cmdLength); /* append cmdline onto the end */
398 fullCmdLine[fullCmdLength - 1] = 0; /* null terminate string */
400 ZeroMemory (&st, sizeof(STARTUPINFOA));
401 st.cb = sizeof(STARTUPINFOA);
402 ret = CreateProcessA (NULL, fullCmdLine, NULL, NULL, TRUE, 0, envblock, NULL, &st, &pe);
404 /* wait for the app to finish and clean up PROCESS_INFORMATION handles */
407 WaitForSingleObject(pe.hProcess, INFINITE); /* wait here until the child process is complete */
408 CloseHandle(pe.hProcess);
409 CloseHandle(pe.hThread);
412 HeapFree(GetProcessHeap(), 0, fullCmdLine); /* free the memory we allocated */
416 FIXME("EXEC type of %d not implemented for non-dos executables\n", func);
421 } /* if(binType != SCS_DOS_BINARY) */
424 /* handle dos executables */
426 hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
427 NULL, OPEN_EXISTING, 0, 0);
428 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
431 case 0: /* load and execute */
432 case 1: /* load but don't execute */
434 /* save current process's return SS:SP now */
435 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
436 PDB16 *psp = (PDB16 *)psp_start;
437 psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
439 ret = MZ_DoLoadImage( hFile, filename, NULL );
441 /* MZ_LoadImage created a new PSP and loaded new values into it,
442 * let's work on the new values now */
443 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
444 ExecBlock *blk = (ExecBlock *)paramblk;
445 LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
447 /* First character contains the length of the command line. */
448 MZ_FillPSP(psp_start, cmdline + 1, cmdline[0]);
450 /* the lame MS-DOS engineers decided that the return address should be in int22 */
451 DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
453 /* don't execute, just return startup state */
454 blk->init_cs = init_cs;
455 blk->init_ip = init_ip;
456 blk->init_ss = init_ss;
457 blk->init_sp = init_sp;
459 /* execute by making us return to new process */
460 context->SegCs = init_cs;
461 context->Eip = init_ip;
462 context->SegSs = init_ss;
463 context->Esp = init_sp;
464 context->SegDs = DOSVM_psp;
465 context->SegEs = DOSVM_psp;
470 case 3: /* load overlay */
472 OverlayBlock *blk = (OverlayBlock *)paramblk;
473 ret = MZ_DoLoadImage( hFile, filename, blk );
477 FIXME("EXEC load type %d not implemented\n", func);
478 SetLastError(ERROR_INVALID_FUNCTION);
485 /***********************************************************************
488 void WINAPI MZ_AllocDPMITask( void )
494 /***********************************************************************
497 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
505 event = CreateEventA(NULL, TRUE, FALSE, NULL);
506 PostThreadMessageA(loop_tid, WM_USER, (WPARAM)event, (LPARAM)&spc);
507 WaitForSingleObject(event, INFINITE);
513 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
518 dosvm_pid = getpid();
520 memset( &context, 0, sizeof(context) );
521 context.SegCs = init_cs;
522 context.Eip = init_ip;
523 context.SegSs = init_ss;
524 context.Esp = init_sp;
525 context.SegDs = DOSVM_psp;
526 context.SegEs = DOSVM_psp;
527 context.EFlags = 0x00080000; /* virtual interrupt flag */
528 DOSVM_SetTimer(0x10000);
529 ret = DOSVM_Enter( &context );
535 static BOOL MZ_InitTask(void)
537 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
538 GetCurrentProcess(), &loop_thread,
539 0, FALSE, DUPLICATE_SAME_ACCESS))
541 dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
543 CloseHandle(loop_thread);
547 loop_tid = GetCurrentThreadId();
551 static void MZ_Launch(void)
553 TDB *pTask = GlobalLock16( GetCurrentTask() );
554 BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
555 LPSTR cmdline = GetCommandLineA();
559 MZ_FillPSP(psp_start, cmdline, cmdline ? strlen(cmdline) : 0);
560 pTask->flags |= TDBF_WINOLDAP;
562 GetpWin16Lock( &lock );
563 _LeaveSysLevel( lock );
565 ResumeThread(dosvm_thread);
566 rv = DOSVM_Loop(dosvm_thread);
568 CloseHandle(dosvm_thread);
569 dosvm_thread = 0; dosvm_tid = 0;
570 CloseHandle(loop_thread);
571 loop_thread = 0; loop_tid = 0;
577 /***********************************************************************
580 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
583 WORD psp_seg = cs_psp ? context->SegCs : DOSVM_psp;
584 LPBYTE psp_start = (LPBYTE)((DWORD)psp_seg << 4);
585 PDB16 *psp = (PDB16 *)psp_start;
586 WORD parpsp = psp->parentPSP; /* check for parent DOS process */
588 /* retrieve parent's return address */
589 FARPROC16 retaddr = DOSVM_GetRMHandler(0x22);
590 /* restore interrupts */
591 DOSVM_SetRMHandler(0x22, psp->savedint22);
592 DOSVM_SetRMHandler(0x23, psp->savedint23);
593 DOSVM_SetRMHandler(0x24, psp->savedint24);
594 /* FIXME: deallocate file handles etc */
595 /* free process's associated memory
596 * FIXME: walk memory and deallocate all blocks owned by process */
597 DOSMEM_FreeBlock( PTR_REAL_TO_LIN(psp->environment,0) );
598 DOSMEM_FreeBlock( PTR_REAL_TO_LIN(DOSVM_psp,0) );
599 /* switch to parent's PSP */
601 psp_start = (LPBYTE)((DWORD)parpsp << 4);
602 psp = (PDB16 *)psp_start;
603 /* now return to parent */
604 DOSVM_retval = retval;
605 context->SegCs = SELECTOROF(retaddr);
606 context->Eip = OFFSETOF(retaddr);
607 context->SegSs = SELECTOROF(psp->saveStack);
608 context->Esp = OFFSETOF(psp->saveStack);
611 TRACE("killing DOS task\n");
613 ExitThread( retval );
617 /***********************************************************************
620 BOOL WINAPI MZ_Current( void )
622 return (dosvm_pid != 0); /* FIXME: do a better check */
625 #else /* !MZ_SUPPORTED */
627 /***********************************************************************
628 * LoadDosExe (WINEDOS.@)
630 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
632 WARN("DOS executables not supported on this platform\n");
633 SetLastError(ERROR_BAD_FORMAT);
636 /***********************************************************************
639 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
642 SetLastError(ERROR_BAD_FORMAT);
646 /***********************************************************************
649 void WINAPI MZ_AllocDPMITask( void )
651 ERR("Actual real-mode calls not supported on this platform!\n");
654 /***********************************************************************
657 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
662 /***********************************************************************
665 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
667 ExitThread( retval );
670 /***********************************************************************
673 BOOL WINAPI MZ_Current( void )
678 #endif /* !MZ_SUPPORTED */