When DOS program executes another DOS program, command line is now
[wine/multimedia.git] / dlls / winedos / module.c
blob1a87fae852f3e5d70a99857a0551948c909e075f
1 /*
2 * DOS (MZ) loader
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.
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <unistd.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include "windef.h"
37 #include "wine/winbase16.h"
38 #include "wingdi.h"
39 #include "winuser.h"
40 #include "winerror.h"
41 #include "module.h"
42 #include "task.h"
43 #include "file.h"
44 #include "miscemu.h"
45 #include "wine/debug.h"
46 #include "dosexe.h"
47 #include "dosvm.h"
48 #include "options.h"
49 #include "vga.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(module);
53 #ifdef MZ_SUPPORTED
55 #ifdef HAVE_SYS_MMAN_H
56 # include <sys/mman.h>
57 #endif
59 /* define this to try mapping through /proc/pid/mem instead of a temp file,
60 but Linus doesn't like mmapping /proc/pid/mem, so it doesn't work for me */
61 #undef MZ_MAPSELF
63 #define BIOS_DATA_SEGMENT 0x40
64 #define PSP_SIZE 0x10
66 #define SEG16(ptr,seg) ((LPVOID)((BYTE*)ptr+((DWORD)(seg)<<4)))
67 #define SEGPTR16(ptr,segptr) ((LPVOID)((BYTE*)ptr+((DWORD)SELECTOROF(segptr)<<4)+OFFSETOF(segptr)))
69 /* structures for EXEC */
71 typedef struct {
72 WORD env_seg;
73 DWORD cmdline WINE_PACKED;
74 DWORD fcb1 WINE_PACKED;
75 DWORD fcb2 WINE_PACKED;
76 WORD init_sp;
77 WORD init_ss;
78 WORD init_ip;
79 WORD init_cs;
80 } ExecBlock;
82 typedef struct {
83 WORD load_seg;
84 WORD rel_seg;
85 } OverlayBlock;
87 /* global variables */
89 pid_t dosvm_pid;
91 static WORD init_cs,init_ip,init_ss,init_sp;
92 static HANDLE dosvm_thread, loop_thread;
93 static DWORD dosvm_tid, loop_tid;
95 static void MZ_Launch(void);
96 static BOOL MZ_InitTask(void);
97 static void MZ_KillTask(void);
99 static void MZ_CreatePSP( LPVOID lpPSP, WORD env, WORD par )
101 PDB16*psp=lpPSP;
103 psp->int20=0x20CD; /* int 20 */
104 /* some programs use this to calculate how much memory they need */
105 psp->nextParagraph=0x9FFF; /* FIXME: use a real value */
106 /* FIXME: dispatcher */
107 psp->savedint22 = DOSVM_GetRMHandler(0x22);
108 psp->savedint23 = DOSVM_GetRMHandler(0x23);
109 psp->savedint24 = DOSVM_GetRMHandler(0x24);
110 psp->parentPSP=par;
111 psp->environment=env;
112 /* FIXME: more PSP stuff */
115 static void MZ_FillPSP( LPVOID lpPSP, LPBYTE cmdline, int length )
117 PDB16 *psp = lpPSP;
119 while(length > 0 && *cmdline != ' ') {
120 length--;
121 cmdline++;
124 /* command.com does not skip over multiple spaces */
126 if(length > 126) {
127 ERR("Command line truncated! (length %d > maximum length 126)\n",
128 length);
129 length = 126;
132 psp->cmdLine[0] = length;
133 if(length > 0)
134 memmove(psp->cmdLine+1, cmdline, length);
135 psp->cmdLine[length+1] = '\r';
137 /* FIXME: more PSP stuff */
140 /* default INT 08 handler: increases timer tick counter but not much more */
141 static char int08[]={
142 0xCD,0x1C, /* int $0x1c */
143 0x50, /* pushw %ax */
144 0x1E, /* pushw %ds */
145 0xB8,0x40,0x00, /* movw $0x40,%ax */
146 0x8E,0xD8, /* movw %ax,%ds */
147 #if 0
148 0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
149 0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
150 #else
151 0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
152 #endif
153 0xB0,0x20, /* movb $0x20,%al */
154 0xE6,0x20, /* outb %al,$0x20 */
155 0x1F, /* popw %ax */
156 0x58, /* popw %ax */
157 0xCF /* iret */
160 static void MZ_InitHandlers(void)
162 WORD seg;
163 LPBYTE start=DOSMEM_GetBlock(sizeof(int08),&seg);
164 memcpy(start,int08,sizeof(int08));
165 /* INT 08: point it at our tick-incrementing handler */
166 ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
167 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
168 ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
171 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
173 unsigned sz=0;
174 WORD seg;
175 LPSTR envblk;
177 if (env) {
178 /* get size of environment block */
179 while (env[sz++]) sz+=strlen(env+sz)+1;
180 } else sz++;
181 /* allocate it */
182 envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
183 /* fill it */
184 if (env) {
185 memcpy(envblk,env,sz);
186 } else envblk[0]=0;
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;
194 static BOOL MZ_InitMemory(void)
196 /* initialize the memory */
197 TRACE("Initializing DOS memory structures\n");
198 DOSMEM_Init(TRUE);
200 MZ_InitHandlers();
201 return TRUE;
204 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
206 IMAGE_DOS_HEADER mz_header;
207 DWORD image_start,image_size,min_size,max_size,avail;
208 BYTE*psp_start,*load_start,*oldenv;
209 int x, old_com=0, alloc;
210 SEGPTR reloc;
211 WORD env_seg, load_seg, rel_seg, oldpsp_seg;
212 DWORD len;
214 if (DOSVM_psp) {
215 /* DOS process already running, inherit from it */
216 PDB16* par_psp = (PDB16*)((DWORD)DOSVM_psp << 4);
217 alloc=0;
218 oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
219 oldpsp_seg = DOSVM_psp;
220 } else {
221 /* allocate new DOS process, inheriting from Wine environment */
222 alloc=1;
223 oldenv = GetEnvironmentStringsA();
224 oldpsp_seg = 0;
227 SetFilePointer(hFile,0,NULL,FILE_BEGIN);
228 if ( !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
229 || len != sizeof(mz_header)
230 || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
231 char *p = strrchr( filename, '.' );
232 if (!p || strcasecmp( p, ".com" )) /* check for .COM extension */
234 SetLastError(ERROR_BAD_FORMAT);
235 goto load_error;
237 old_com=1; /* assume .COM file */
238 image_start=0;
239 image_size=GetFileSize(hFile,NULL);
240 min_size=0x10000; max_size=0x100000;
241 mz_header.e_crlc=0;
242 mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
243 mz_header.e_cs=0; mz_header.e_ip=0x100;
244 } else {
245 /* calculate load size */
246 image_start=mz_header.e_cparhdr<<4;
247 image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
248 if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
249 image_size-=image_start;
250 min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
251 max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
254 if (alloc) MZ_InitMemory();
256 if (oblk) {
257 /* load overlay into preallocated memory */
258 load_seg=oblk->load_seg;
259 rel_seg=oblk->rel_seg;
260 load_start=(LPBYTE)((DWORD)load_seg<<4);
261 } else {
262 /* allocate environment block */
263 env_seg=MZ_InitEnvironment(oldenv, filename);
265 /* allocate memory for the executable */
266 TRACE("Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
267 avail=DOSMEM_Available();
268 if (avail<min_size) {
269 ERR("insufficient DOS memory\n");
270 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
271 goto load_error;
273 if (avail>max_size) avail=max_size;
274 psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
275 if (!psp_start) {
276 ERR("error allocating DOS memory\n");
277 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
278 goto load_error;
280 load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
281 rel_seg=load_seg;
282 load_start=psp_start+(PSP_SIZE<<4);
283 MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
286 /* load executable image */
287 TRACE("loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
288 SetFilePointer(hFile,image_start,NULL,FILE_BEGIN);
289 if (!ReadFile(hFile,load_start,image_size,&len,NULL) || len != image_size) {
290 SetLastError(ERROR_BAD_FORMAT);
291 goto load_error;
294 if (mz_header.e_crlc) {
295 /* load relocation table */
296 TRACE("loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
297 /* FIXME: is this too slow without read buffering? */
298 SetFilePointer(hFile,mz_header.e_lfarlc,NULL,FILE_BEGIN);
299 for (x=0; x<mz_header.e_crlc; x++) {
300 if (!ReadFile(hFile,&reloc,sizeof(reloc),&len,NULL) || len != sizeof(reloc)) {
301 SetLastError(ERROR_BAD_FORMAT);
302 goto load_error;
304 *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
308 if (!oblk) {
309 init_cs = load_seg+mz_header.e_cs;
310 init_ip = mz_header.e_ip;
311 init_ss = load_seg+mz_header.e_ss;
312 init_sp = mz_header.e_sp;
314 TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
317 if (alloc && !MZ_InitTask()) {
318 SetLastError(ERROR_GEN_FAILURE);
319 return FALSE;
322 return TRUE;
324 load_error:
325 DOSVM_psp = oldpsp_seg;
327 return FALSE;
330 /***********************************************************************
331 * LoadDosExe (WINEDOS.@)
333 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
335 if (MZ_DoLoadImage( hFile, filename, NULL )) MZ_Launch();
338 /***********************************************************************
339 * MZ_Exec
341 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
343 /* this may only be called from existing DOS processes
344 * (i.e. one DOS app spawning another) */
345 /* FIXME: do we want to check binary type first, to check
346 * whether it's a NE/PE executable? */
347 HFILE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
348 NULL, OPEN_EXISTING, 0, 0);
349 BOOL ret = FALSE;
350 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
351 switch (func) {
352 case 0: /* load and execute */
353 case 1: /* load but don't execute */
355 /* save current process's return SS:SP now */
356 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
357 PDB16 *psp = (PDB16 *)psp_start;
358 psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
360 ret = MZ_DoLoadImage( hFile, filename, NULL );
361 if (ret) {
362 /* MZ_LoadImage created a new PSP and loaded new values into it,
363 * let's work on the new values now */
364 LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
365 ExecBlock *blk = (ExecBlock *)paramblk;
366 LPBYTE cmdline = DOSMEM_MapRealToLinear(blk->cmdline);
368 /* First character contains the length of the command line. */
369 MZ_FillPSP(psp_start, cmdline + 1, cmdline[0]);
371 /* the lame MS-DOS engineers decided that the return address should be in int22 */
372 DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
373 if (func) {
374 /* don't execute, just return startup state */
375 blk->init_cs = init_cs;
376 blk->init_ip = init_ip;
377 blk->init_ss = init_ss;
378 blk->init_sp = init_sp;
379 } else {
380 /* execute by making us return to new process */
381 context->SegCs = init_cs;
382 context->Eip = init_ip;
383 context->SegSs = init_ss;
384 context->Esp = init_sp;
385 context->SegDs = DOSVM_psp;
386 context->SegEs = DOSVM_psp;
387 context->Eax = 0;
390 break;
391 case 3: /* load overlay */
393 OverlayBlock *blk = (OverlayBlock *)paramblk;
394 ret = MZ_DoLoadImage( hFile, filename, blk );
396 break;
397 default:
398 FIXME("EXEC load type %d not implemented\n", func);
399 SetLastError(ERROR_INVALID_FUNCTION);
400 break;
402 CloseHandle(hFile);
403 return ret;
406 /***********************************************************************
407 * MZ_AllocDPMITask
409 void WINAPI MZ_AllocDPMITask( void )
411 MZ_InitMemory();
412 MZ_InitTask();
415 /***********************************************************************
416 * MZ_RunInThread
418 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
420 if (loop_thread) {
421 DOS_SPC spc;
422 HANDLE event;
424 spc.proc = proc;
425 spc.arg = arg;
426 event = CreateEventA(NULL, TRUE, FALSE, NULL);
427 PostThreadMessageA(loop_tid, WM_USER, event, (LPARAM)&spc);
428 WaitForSingleObject(event, INFINITE);
429 CloseHandle(event);
430 } else
431 proc(arg);
434 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
436 CONTEXT context;
437 DWORD ret;
439 dosvm_pid = getpid();
441 memset( &context, 0, sizeof(context) );
442 context.SegCs = init_cs;
443 context.Eip = init_ip;
444 context.SegSs = init_ss;
445 context.Esp = init_sp;
446 context.SegDs = DOSVM_psp;
447 context.SegEs = DOSVM_psp;
448 context.EFlags = 0x00080000; /* virtual interrupt flag */
449 DOSVM_SetTimer(0x10000);
450 ret = DOSVM_Enter( &context );
452 dosvm_pid = 0;
453 return ret;
456 static BOOL MZ_InitTask(void)
458 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
459 GetCurrentProcess(), &loop_thread,
460 0, FALSE, DUPLICATE_SAME_ACCESS))
461 return FALSE;
462 dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
463 if (!dosvm_thread) {
464 CloseHandle(loop_thread);
465 loop_thread = 0;
466 return FALSE;
468 loop_tid = GetCurrentThreadId();
469 return TRUE;
472 static void MZ_Launch(void)
474 TDB *pTask = TASK_GetCurrent();
475 BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
476 LPSTR cmdline = GetCommandLineA();
478 MZ_FillPSP(psp_start, cmdline, cmdline ? strlen(cmdline) : 0);
479 pTask->flags |= TDBF_WINOLDAP;
481 _LeaveWin16Lock();
483 ResumeThread(dosvm_thread);
484 DOSVM_Loop(NULL);
485 ExitThread(0);
488 static void MZ_KillTask(void)
490 TRACE("killing DOS task\n");
491 VGA_Clean();
492 PostThreadMessageA(loop_tid, WM_QUIT, 0, 0);
493 WaitForSingleObject(loop_thread, INFINITE); /* ? */
494 CloseHandle(dosvm_thread);
495 dosvm_thread = 0; dosvm_tid = 0;
496 CloseHandle(loop_thread);
497 loop_thread = 0; loop_tid = 0;
500 /***********************************************************************
501 * MZ_Exit
503 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
505 if (DOSVM_psp) {
506 WORD psp_seg = cs_psp ? context->SegCs : DOSVM_psp;
507 LPBYTE psp_start = (LPBYTE)((DWORD)psp_seg << 4);
508 PDB16 *psp = (PDB16 *)psp_start;
509 WORD parpsp = psp->parentPSP; /* check for parent DOS process */
510 if (parpsp) {
511 /* retrieve parent's return address */
512 FARPROC16 retaddr = DOSVM_GetRMHandler(0x22);
513 /* restore interrupts */
514 DOSVM_SetRMHandler(0x22, psp->savedint22);
515 DOSVM_SetRMHandler(0x23, psp->savedint23);
516 DOSVM_SetRMHandler(0x24, psp->savedint24);
517 /* FIXME: deallocate file handles etc */
518 /* free process's associated memory
519 * FIXME: walk memory and deallocate all blocks owned by process */
520 DOSMEM_FreeBlock(DOSMEM_MapRealToLinear(MAKELONG(0,psp->environment)));
521 DOSMEM_FreeBlock(DOSMEM_MapRealToLinear(MAKELONG(0,DOSVM_psp)));
522 /* switch to parent's PSP */
523 DOSVM_psp = parpsp;
524 psp_start = (LPBYTE)((DWORD)parpsp << 4);
525 psp = (PDB16 *)psp_start;
526 /* now return to parent */
527 DOSVM_retval = retval;
528 context->SegCs = SELECTOROF(retaddr);
529 context->Eip = OFFSETOF(retaddr);
530 context->SegSs = SELECTOROF(psp->saveStack);
531 context->Esp = OFFSETOF(psp->saveStack);
532 return;
533 } else
534 MZ_KillTask();
536 ExitThread( retval );
540 /***********************************************************************
541 * MZ_Current
543 BOOL WINAPI MZ_Current( void )
545 return (dosvm_pid != 0); /* FIXME: do a better check */
548 #else /* !MZ_SUPPORTED */
550 /***********************************************************************
551 * LoadDosExe (WINEDOS.@)
553 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
555 WARN("DOS executables not supported on this platform\n");
556 SetLastError(ERROR_BAD_FORMAT);
559 /***********************************************************************
560 * MZ_Exec
562 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
564 /* can't happen */
565 SetLastError(ERROR_BAD_FORMAT);
566 return FALSE;
569 /***********************************************************************
570 * MZ_AllocDPMITask
572 void WINAPI MZ_AllocDPMITask( void )
574 ERR("Actual real-mode calls not supported on this platform!\n");
577 /***********************************************************************
578 * MZ_Exit
580 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
582 ExitThread( retval );
585 /***********************************************************************
586 * MZ_Current
588 BOOL WINAPI MZ_Current( void )
590 return FALSE;
593 #endif /* !MZ_SUPPORTED */