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( LPCSTR cmdtail, int length );
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, LPCSTR cmdtail, int length )
133 WARN( "Command tail truncated! (length %d)\n", length );
137 psp->cmdLine[0] = length;
140 * Length of exactly 127 bytes means that full command line is
141 * stored in environment variable CMDLINE and PSP contains
142 * command tail truncated to 126 bytes.
148 memmove(psp->cmdLine+1, cmdtail, length);
150 psp->cmdLine[length+1] = '\r';
152 /* FIXME: more PSP stuff */
155 /* default INT 08 handler: increases timer tick counter but not much more */
156 static char int08[]={
157 0xCD,0x1C, /* int $0x1c */
158 0x50, /* pushw %ax */
159 0x1E, /* pushw %ds */
160 0xB8,0x40,0x00, /* movw $0x40,%ax */
161 0x8E,0xD8, /* movw %ax,%ds */
163 0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
164 0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
166 0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
168 0xB0,0x20, /* movb $0x20,%al */
169 0xE6,0x20, /* outb %al,$0x20 */
175 static void MZ_InitHandlers(void)
178 LPBYTE start = DOSVM_AllocCodeUMB( sizeof(int08), &seg, 0 );
179 memcpy(start,int08,sizeof(int08));
180 /* INT 08: point it at our tick-incrementing handler */
181 ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
182 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
183 ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
186 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
193 /* get size of environment block */
194 while (env[sz++]) sz+=strlen(env+sz)+1;
197 envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
200 memcpy(envblk,env,sz);
202 /* DOS 3.x: the block contains 1 additional string */
203 *(WORD*)(envblk+sz)=1;
204 /* being the program name itself */
205 strcpy(envblk+sz+sizeof(WORD),name);
209 static BOOL MZ_InitMemory(void)
211 /* initialize the memory */
212 TRACE("Initializing DOS memory structures\n");
214 DOSDEV_InstallDOSDevices();
220 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
222 IMAGE_DOS_HEADER mz_header;
223 DWORD image_start,image_size,min_size,max_size,avail;
224 BYTE*psp_start,*load_start,*oldenv;
225 int x, old_com=0, alloc;
227 WORD env_seg, load_seg, rel_seg, oldpsp_seg;
231 /* DOS process already running, inherit from it */
232 PDB16* par_psp = (PDB16*)((DWORD)DOSVM_psp << 4);
234 oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
235 oldpsp_seg = DOSVM_psp;
237 /* allocate new DOS process, inheriting from Wine environment */
239 oldenv = GetEnvironmentStringsA();
243 SetFilePointer(hFile,0,NULL,FILE_BEGIN);
244 if ( !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
245 || len != sizeof(mz_header)
246 || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
247 char *p = strrchr( filename, '.' );
248 if (!p || strcasecmp( p, ".com" )) /* check for .COM extension */
250 SetLastError(ERROR_BAD_FORMAT);
253 old_com=1; /* assume .COM file */
255 image_size=GetFileSize(hFile,NULL);
256 min_size=0x10000; max_size=0x100000;
258 mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
259 mz_header.e_cs=0; mz_header.e_ip=0x100;
261 /* calculate load size */
262 image_start=mz_header.e_cparhdr<<4;
263 image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
264 if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
265 image_size-=image_start;
266 min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
267 max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
270 if (alloc) MZ_InitMemory();
273 /* load overlay into preallocated memory */
274 load_seg=oblk->load_seg;
275 rel_seg=oblk->rel_seg;
276 load_start=(LPBYTE)((DWORD)load_seg<<4);
278 /* allocate environment block */
279 env_seg=MZ_InitEnvironment(oldenv, filename);
281 /* allocate memory for the executable */
282 TRACE("Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
283 avail=DOSMEM_Available();
284 if (avail<min_size) {
285 ERR("insufficient DOS memory\n");
286 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
289 if (avail>max_size) avail=max_size;
290 psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
292 ERR("error allocating DOS memory\n");
293 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
296 load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
298 load_start=psp_start+(PSP_SIZE<<4);
299 MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
302 /* load executable image */
303 TRACE("loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
304 SetFilePointer(hFile,image_start,NULL,FILE_BEGIN);
305 if (!ReadFile(hFile,load_start,image_size,&len,NULL) || len != image_size) {
306 SetLastError(ERROR_BAD_FORMAT);
310 if (mz_header.e_crlc) {
311 /* load relocation table */
312 TRACE("loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
313 /* FIXME: is this too slow without read buffering? */
314 SetFilePointer(hFile,mz_header.e_lfarlc,NULL,FILE_BEGIN);
315 for (x=0; x<mz_header.e_crlc; x++) {
316 if (!ReadFile(hFile,&reloc,sizeof(reloc),&len,NULL) || len != sizeof(reloc)) {
317 SetLastError(ERROR_BAD_FORMAT);
320 *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
325 init_cs = load_seg+mz_header.e_cs;
326 init_ip = mz_header.e_ip;
327 init_ss = load_seg+mz_header.e_ss;
328 init_sp = mz_header.e_sp;
330 TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
333 if (alloc && !MZ_InitTask()) {
334 SetLastError(ERROR_GEN_FAILURE);
341 DOSVM_psp = oldpsp_seg;
346 /***********************************************************************
347 * wine_load_dos_exe (WINEDOS.@)
349 * Called from WineVDM when a new real-mode DOS process is started.
350 * Loads DOS program into memory and executes the program.
352 void WINAPI wine_load_dos_exe( LPCSTR filename, LPCSTR cmdline )
354 char dos_cmdtail[126];
357 HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
358 NULL, OPEN_EXISTING, 0, 0 );
359 if (hFile == INVALID_HANDLE_VALUE) return;
360 DOSVM_isdosexe = TRUE;
362 if(cmdline && *cmdline)
364 dos_length = strlen(cmdline);
365 memmove( dos_cmdtail + 1, cmdline,
366 (dos_length < 125) ? dos_length : 125 );
368 /* Non-empty command tail always starts with at least one space. */
369 dos_cmdtail[0] = ' ';
373 * If command tail is longer than 126 characters,
374 * set tail length to 127 and fill CMDLINE environment variable
375 * with full command line (this includes filename).
377 if (dos_length > 126)
379 char *cmd = HeapAlloc( GetProcessHeap(), 0,
380 dos_length + strlen(filename) + 4 );
387 * Append filename. If path includes spaces, quote the path.
389 if (strchr(filename, ' '))
392 strcpy( ptr, filename );
393 ptr += strlen(filename);
398 strcpy( ptr, filename );
399 ptr += strlen(filename);
403 * Append command tail.
405 if (cmdline[0] != ' ')
407 strcpy( ptr, cmdline );
410 * Set environment variable. This will be passed to
413 if (!SetEnvironmentVariableA( "CMDLINE", cmd ))
415 HeapFree(GetProcessHeap(), 0, cmd );
419 HeapFree(GetProcessHeap(), 0, cmd );
424 if (MZ_DoLoadImage( hFile, filename, NULL ))
425 MZ_Launch( dos_cmdtail, dos_length );
428 /***********************************************************************
431 * this may only be called from existing DOS processes
433 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
437 PROCESS_INFORMATION pe;
442 if(!GetBinaryTypeA(filename, &binType)) /* determine what kind of binary this is */
444 return FALSE; /* binary is not an executable */
447 /* handle non-dos executables */
448 if(binType != SCS_DOS_BINARY)
450 if(func == 0) /* load and execute */
454 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
455 PDB16 *psp = (PDB16 *)psp_start;
456 ExecBlock *blk = (ExecBlock *)paramblk;
457 LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
458 LPBYTE envblock = PTR_REAL_TO_LIN(psp->environment, 0);
459 int cmdLength = cmdline[0];
462 * If cmdLength is 127, command tail is truncated and environment
463 * variable CMDLINE should contain full command line
464 * (this includes filename).
466 if (cmdLength == 127)
468 FIXME( "CMDLINE argument passing is unimplemented.\n" );
469 cmdLength = 126; /* FIXME */
472 fullCmdLength = (strlen(filename) + 1) + cmdLength + 1; /* filename + space + cmdline + terminating null character */
474 fullCmdLine = HeapAlloc(GetProcessHeap(), 0, fullCmdLength);
475 if(!fullCmdLine) return FALSE; /* return false on memory alloc failure */
477 /* build the full command line from the executable file and the command line being passed in */
478 snprintf(fullCmdLine, fullCmdLength, "%s ", filename); /* start off with the executable filename and a space */
479 memcpy(fullCmdLine + strlen(fullCmdLine), cmdline + 1, cmdLength); /* append cmdline onto the end */
480 fullCmdLine[fullCmdLength - 1] = 0; /* null terminate string */
482 ZeroMemory (&st, sizeof(STARTUPINFOA));
483 st.cb = sizeof(STARTUPINFOA);
484 ret = CreateProcessA (NULL, fullCmdLine, NULL, NULL, TRUE, 0, envblock, NULL, &st, &pe);
486 /* wait for the app to finish and clean up PROCESS_INFORMATION handles */
489 WaitForSingleObject(pe.hProcess, INFINITE); /* wait here until the child process is complete */
490 CloseHandle(pe.hProcess);
491 CloseHandle(pe.hThread);
494 HeapFree(GetProcessHeap(), 0, fullCmdLine); /* free the memory we allocated */
498 FIXME("EXEC type of %d not implemented for non-dos executables\n", func);
503 } /* if(binType != SCS_DOS_BINARY) */
506 /* handle dos executables */
508 hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
509 NULL, OPEN_EXISTING, 0, 0);
510 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
513 case 0: /* load and execute */
514 case 1: /* load but don't execute */
516 /* save current process's return SS:SP now */
517 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
518 PDB16 *psp = (PDB16 *)psp_start;
519 psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
521 ret = MZ_DoLoadImage( hFile, filename, NULL );
523 /* MZ_LoadImage created a new PSP and loaded new values into it,
524 * let's work on the new values now */
525 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
526 ExecBlock *blk = (ExecBlock *)paramblk;
527 LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
529 /* First character contains the length of the command line. */
530 MZ_FillPSP(psp_start, cmdline + 1, cmdline[0]);
532 /* the lame MS-DOS engineers decided that the return address should be in int22 */
533 DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
535 /* don't execute, just return startup state */
536 blk->init_cs = init_cs;
537 blk->init_ip = init_ip;
538 blk->init_ss = init_ss;
539 blk->init_sp = init_sp;
541 /* execute by making us return to new process */
542 context->SegCs = init_cs;
543 context->Eip = init_ip;
544 context->SegSs = init_ss;
545 context->Esp = init_sp;
546 context->SegDs = DOSVM_psp;
547 context->SegEs = DOSVM_psp;
552 case 3: /* load overlay */
554 OverlayBlock *blk = (OverlayBlock *)paramblk;
555 ret = MZ_DoLoadImage( hFile, filename, blk );
559 FIXME("EXEC load type %d not implemented\n", func);
560 SetLastError(ERROR_INVALID_FUNCTION);
567 /***********************************************************************
570 void WINAPI MZ_AllocDPMITask( void )
576 /***********************************************************************
579 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
587 event = CreateEventA(NULL, TRUE, FALSE, NULL);
588 PostThreadMessageA(loop_tid, WM_USER, (WPARAM)event, (LPARAM)&spc);
589 WaitForSingleObject(event, INFINITE);
595 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
600 dosvm_pid = getpid();
602 memset( &context, 0, sizeof(context) );
603 context.SegCs = init_cs;
604 context.Eip = init_ip;
605 context.SegSs = init_ss;
606 context.Esp = init_sp;
607 context.SegDs = DOSVM_psp;
608 context.SegEs = DOSVM_psp;
609 context.EFlags = 0x00080000; /* virtual interrupt flag */
610 DOSVM_SetTimer(0x10000);
611 ret = DOSVM_Enter( &context );
617 static BOOL MZ_InitTask(void)
619 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
620 GetCurrentProcess(), &loop_thread,
621 0, FALSE, DUPLICATE_SAME_ACCESS))
623 dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
625 CloseHandle(loop_thread);
629 loop_tid = GetCurrentThreadId();
633 static void MZ_Launch( LPCSTR cmdtail, int length )
635 TDB *pTask = GlobalLock16( GetCurrentTask() );
636 BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
640 MZ_FillPSP(psp_start, cmdtail, length);
641 pTask->flags |= TDBF_WINOLDAP;
643 /* DTA is set to PSP:0080h when a program is started. */
644 pTask->dta = MAKESEGPTR( DOSVM_psp, 0x80 );
646 GetpWin16Lock( &lock );
647 _LeaveSysLevel( lock );
649 ResumeThread(dosvm_thread);
650 rv = DOSVM_Loop(dosvm_thread);
652 CloseHandle(dosvm_thread);
653 dosvm_thread = 0; dosvm_tid = 0;
654 CloseHandle(loop_thread);
655 loop_thread = 0; loop_tid = 0;
661 /***********************************************************************
664 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
667 WORD psp_seg = cs_psp ? context->SegCs : DOSVM_psp;
668 LPBYTE psp_start = (LPBYTE)((DWORD)psp_seg << 4);
669 PDB16 *psp = (PDB16 *)psp_start;
670 WORD parpsp = psp->parentPSP; /* check for parent DOS process */
672 /* retrieve parent's return address */
673 FARPROC16 retaddr = DOSVM_GetRMHandler(0x22);
674 /* restore interrupts */
675 DOSVM_SetRMHandler(0x22, psp->savedint22);
676 DOSVM_SetRMHandler(0x23, psp->savedint23);
677 DOSVM_SetRMHandler(0x24, psp->savedint24);
678 /* FIXME: deallocate file handles etc */
679 /* free process's associated memory
680 * FIXME: walk memory and deallocate all blocks owned by process */
681 DOSMEM_FreeBlock( PTR_REAL_TO_LIN(psp->environment,0) );
682 DOSMEM_FreeBlock( PTR_REAL_TO_LIN(DOSVM_psp,0) );
683 /* switch to parent's PSP */
685 psp_start = (LPBYTE)((DWORD)parpsp << 4);
686 psp = (PDB16 *)psp_start;
687 /* now return to parent */
688 DOSVM_retval = retval;
689 context->SegCs = SELECTOROF(retaddr);
690 context->Eip = OFFSETOF(retaddr);
691 context->SegSs = SELECTOROF(psp->saveStack);
692 context->Esp = OFFSETOF(psp->saveStack);
695 TRACE("killing DOS task\n");
697 ExitThread( retval );
701 /***********************************************************************
704 BOOL WINAPI MZ_Current( void )
706 return (dosvm_pid != 0); /* FIXME: do a better check */
709 #else /* !MZ_SUPPORTED */
711 /***********************************************************************
712 * wine_load_dos_exe (WINEDOS.@)
714 void WINAPI wine_load_dos_exe( LPCSTR filename, LPCSTR cmdline )
716 WARN("DOS executables not supported on this platform\n");
717 SetLastError(ERROR_BAD_FORMAT);
720 /***********************************************************************
723 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
726 SetLastError(ERROR_BAD_FORMAT);
730 /***********************************************************************
733 void WINAPI MZ_AllocDPMITask( void )
735 ERR("Actual real-mode calls not supported on this platform!\n");
738 /***********************************************************************
741 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
746 /***********************************************************************
749 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
751 ExitThread( retval );
754 /***********************************************************************
757 BOOL WINAPI MZ_Current( void )
762 #endif /* !MZ_SUPPORTED */