Provide stub for SetupDiGetClassDevsW.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.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 #include <sys/stat.h>
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
39 #endif
40 #include "windef.h"
41 #include "wine/winbase16.h"
42 #include "wingdi.h"
43 #include "winuser.h"
44 #include "winerror.h"
45 #include "module.h"
46 #include "task.h"
47 #include "file.h"
48 #include "miscemu.h"
49 #include "wine/debug.h"
50 #include "dosexe.h"
51 #include "dosvm.h"
52 #include "vga.h"
53
54 WINE_DEFAULT_DEBUG_CHANNEL(module);
55
56 #ifdef MZ_SUPPORTED
57
58 #ifdef HAVE_SYS_MMAN_H
59 # include <sys/mman.h>
60 #endif
61
62 /* define this to try mapping through /proc/pid/mem instead of a temp file,
63    but Linus doesn't like mmapping /proc/pid/mem, so it doesn't work for me */
64 #undef MZ_MAPSELF
65
66 #define BIOS_DATA_SEGMENT 0x40
67 #define PSP_SIZE 0x10
68
69 #define SEG16(ptr,seg) ((LPVOID)((BYTE*)ptr+((DWORD)(seg)<<4)))
70 #define SEGPTR16(ptr,segptr) ((LPVOID)((BYTE*)ptr+((DWORD)SELECTOROF(segptr)<<4)+OFFSETOF(segptr)))
71
72 /* structures for EXEC */
73
74 typedef struct {
75   WORD env_seg;
76   DWORD cmdline WINE_PACKED;
77   DWORD fcb1 WINE_PACKED;
78   DWORD fcb2 WINE_PACKED;
79   WORD init_sp;
80   WORD init_ss;
81   WORD init_ip;
82   WORD init_cs;
83 } ExecBlock;
84
85 typedef struct {
86   WORD load_seg;
87   WORD rel_seg;
88 } OverlayBlock;
89
90 /* global variables */
91
92 pid_t dosvm_pid;
93
94 static WORD init_cs,init_ip,init_ss,init_sp;
95 static HANDLE dosvm_thread, loop_thread;
96 static DWORD dosvm_tid, loop_tid;
97
98 static void MZ_Launch(void);
99 static BOOL MZ_InitTask(void);
100
101 static void MZ_CreatePSP( LPVOID lpPSP, WORD env, WORD par )
102 {
103   PDB16*psp=lpPSP;
104
105   psp->int20=0x20CD; /* int 20 */
106   /* some programs use this to calculate how much memory they need */
107   psp->nextParagraph=0x9FFF; /* FIXME: use a real value */
108   /* FIXME: dispatcher */
109   psp->savedint22 = DOSVM_GetRMHandler(0x22);
110   psp->savedint23 = DOSVM_GetRMHandler(0x23);
111   psp->savedint24 = DOSVM_GetRMHandler(0x24);
112   psp->parentPSP=par;
113   psp->environment=env;
114   /* FIXME: more PSP stuff */
115 }
116
117 static void MZ_FillPSP( LPVOID lpPSP, LPBYTE cmdline, int length )
118 {
119   PDB16      *psp = lpPSP;
120
121   while(length > 0 && *cmdline != ' ') {
122     length--;
123     cmdline++;
124   }
125
126   /* command.com does not skip over multiple spaces */
127
128   if(length > 126) {
129     ERR("Command line truncated! (length %d > maximum length 126)\n",
130        length);
131     length = 126;
132   }
133
134   psp->cmdLine[0] = length;
135   if(length > 0)
136     memmove(psp->cmdLine+1, cmdline, length);
137   psp->cmdLine[length+1] = '\r';
138
139   /* FIXME: more PSP stuff */
140 }
141
142 /* default INT 08 handler: increases timer tick counter but not much more */
143 static char int08[]={
144  0xCD,0x1C,           /* int $0x1c */
145  0x50,                /* pushw %ax */
146  0x1E,                /* pushw %ds */
147  0xB8,0x40,0x00,      /* movw $0x40,%ax */
148  0x8E,0xD8,           /* movw %ax,%ds */
149 #if 0
150  0x83,0x06,0x6C,0x00,0x01, /* addw $1,(0x6c) */
151  0x83,0x16,0x6E,0x00,0x00, /* adcw $0,(0x6e) */
152 #else
153  0x66,0xFF,0x06,0x6C,0x00, /* incl (0x6c) */
154 #endif
155  0xB0,0x20,           /* movb $0x20,%al */
156  0xE6,0x20,           /* outb %al,$0x20 */
157  0x1F,                /* popw %ax */
158  0x58,                /* popw %ax */
159  0xCF                 /* iret */
160 };
161
162 static void MZ_InitHandlers(void)
163 {
164  WORD seg;
165  LPBYTE start=DOSMEM_GetBlock(sizeof(int08),&seg);
166  memcpy(start,int08,sizeof(int08));
167 /* INT 08: point it at our tick-incrementing handler */
168  ((SEGPTR*)0)[0x08]=MAKESEGPTR(seg,0);
169 /* INT 1C: just point it to IRET, we don't want to handle it ourselves */
170  ((SEGPTR*)0)[0x1C]=MAKESEGPTR(seg,sizeof(int08)-1);
171 }
172
173 static WORD MZ_InitEnvironment( LPCSTR env, LPCSTR name )
174 {
175  unsigned sz=0;
176  WORD seg;
177  LPSTR envblk;
178
179  if (env) {
180   /* get size of environment block */
181   while (env[sz++]) sz+=strlen(env+sz)+1;
182  } else sz++;
183  /* allocate it */
184  envblk=DOSMEM_GetBlock(sz+sizeof(WORD)+strlen(name)+1,&seg);
185  /* fill it */
186  if (env) {
187   memcpy(envblk,env,sz);
188  } else envblk[0]=0;
189  /* DOS 3.x: the block contains 1 additional string */
190  *(WORD*)(envblk+sz)=1;
191  /* being the program name itself */
192  strcpy(envblk+sz+sizeof(WORD),name);
193  return seg;
194 }
195
196 static BOOL MZ_InitMemory(void)
197 {
198     /* initialize the memory */
199     TRACE("Initializing DOS memory structures\n");
200     DOSMEM_Init(TRUE);
201
202     MZ_InitHandlers();
203     return TRUE;
204 }
205
206 static BOOL MZ_DoLoadImage( HANDLE hFile, LPCSTR filename, OverlayBlock *oblk )
207 {
208   IMAGE_DOS_HEADER mz_header;
209   DWORD image_start,image_size,min_size,max_size,avail;
210   BYTE*psp_start,*load_start,*oldenv;
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 = (PDB16*)((DWORD)DOSVM_psp << 4);
219     alloc=0;
220     oldenv = (LPBYTE)((DWORD)par_psp->environment << 4);
221     oldpsp_seg = DOSVM_psp;
222   } else {
223     /* allocate new DOS process, inheriting from Wine environment */
224     alloc=1;
225     oldenv = GetEnvironmentStringsA();
226     oldpsp_seg = 0;
227   }
228
229  SetFilePointer(hFile,0,NULL,FILE_BEGIN);
230  if (   !ReadFile(hFile,&mz_header,sizeof(mz_header),&len,NULL)
231      || len != sizeof(mz_header)
232      || mz_header.e_magic != IMAGE_DOS_SIGNATURE) {
233   char *p = strrchr( filename, '.' );
234   if (!p || strcasecmp( p, ".com" ))  /* check for .COM extension */
235   {
236       SetLastError(ERROR_BAD_FORMAT);
237       goto load_error;
238   }
239   old_com=1; /* assume .COM file */
240   image_start=0;
241   image_size=GetFileSize(hFile,NULL);
242   min_size=0x10000; max_size=0x100000;
243   mz_header.e_crlc=0;
244   mz_header.e_ss=0; mz_header.e_sp=0xFFFE;
245   mz_header.e_cs=0; mz_header.e_ip=0x100;
246  } else {
247   /* calculate load size */
248   image_start=mz_header.e_cparhdr<<4;
249   image_size=mz_header.e_cp<<9; /* pages are 512 bytes */
250   if ((mz_header.e_cblp!=0)&&(mz_header.e_cblp!=4)) image_size-=512-mz_header.e_cblp;
251   image_size-=image_start;
252   min_size=image_size+((DWORD)mz_header.e_minalloc<<4)+(PSP_SIZE<<4);
253   max_size=image_size+((DWORD)mz_header.e_maxalloc<<4)+(PSP_SIZE<<4);
254  }
255
256   if (alloc) MZ_InitMemory();
257
258   if (oblk) {
259     /* load overlay into preallocated memory */
260     load_seg=oblk->load_seg;
261     rel_seg=oblk->rel_seg;
262     load_start=(LPBYTE)((DWORD)load_seg<<4);
263   } else {
264     /* allocate environment block */
265     env_seg=MZ_InitEnvironment(oldenv, filename);
266
267     /* allocate memory for the executable */
268     TRACE("Allocating DOS memory (min=%ld, max=%ld)\n",min_size,max_size);
269     avail=DOSMEM_Available();
270     if (avail<min_size) {
271       ERR("insufficient DOS memory\n");
272       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
273       goto load_error;
274     }
275     if (avail>max_size) avail=max_size;
276     psp_start=DOSMEM_GetBlock(avail,&DOSVM_psp);
277     if (!psp_start) {
278       ERR("error allocating DOS memory\n");
279       SetLastError(ERROR_NOT_ENOUGH_MEMORY);
280       goto load_error;
281     }
282     load_seg=DOSVM_psp+(old_com?0:PSP_SIZE);
283     rel_seg=load_seg;
284     load_start=psp_start+(PSP_SIZE<<4);
285     MZ_CreatePSP(psp_start, env_seg, oldpsp_seg);
286   }
287
288  /* load executable image */
289  TRACE("loading DOS %s image, %08lx bytes\n",old_com?"COM":"EXE",image_size);
290  SetFilePointer(hFile,image_start,NULL,FILE_BEGIN);
291  if (!ReadFile(hFile,load_start,image_size,&len,NULL) || len != image_size) {
292   SetLastError(ERROR_BAD_FORMAT);
293   goto load_error;
294  }
295
296  if (mz_header.e_crlc) {
297   /* load relocation table */
298   TRACE("loading DOS EXE relocation table, %d entries\n",mz_header.e_crlc);
299   /* FIXME: is this too slow without read buffering? */
300   SetFilePointer(hFile,mz_header.e_lfarlc,NULL,FILE_BEGIN);
301   for (x=0; x<mz_header.e_crlc; x++) {
302    if (!ReadFile(hFile,&reloc,sizeof(reloc),&len,NULL) || len != sizeof(reloc)) {
303     SetLastError(ERROR_BAD_FORMAT);
304     goto load_error;
305    }
306    *(WORD*)SEGPTR16(load_start,reloc)+=rel_seg;
307   }
308  }
309
310   if (!oblk) {
311     init_cs = load_seg+mz_header.e_cs;
312     init_ip = mz_header.e_ip;
313     init_ss = load_seg+mz_header.e_ss;
314     init_sp = mz_header.e_sp;
315
316     TRACE("entry point: %04x:%04x\n",init_cs,init_ip);
317   }
318
319   if (alloc && !MZ_InitTask()) {
320     SetLastError(ERROR_GEN_FAILURE);
321     return FALSE;
322   }
323
324   return TRUE;
325
326 load_error:
327   DOSVM_psp = oldpsp_seg;
328
329   return FALSE;
330 }
331
332 /***********************************************************************
333  *              LoadDosExe (WINEDOS.@)
334  */
335 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
336 {
337   if (MZ_DoLoadImage( hFile, filename, NULL )) MZ_Launch();
338 }
339
340 /***********************************************************************
341  *              MZ_Exec
342  */
343 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
344 {
345   /* this may only be called from existing DOS processes
346    * (i.e. one DOS app spawning another) */
347   /* FIXME: do we want to check binary type first, to check
348    * whether it's a NE/PE executable? */
349   HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
350                              NULL, OPEN_EXISTING, 0, 0);
351   BOOL ret = FALSE;
352   if (hFile == INVALID_HANDLE_VALUE) return FALSE;
353   switch (func) {
354   case 0: /* load and execute */
355   case 1: /* load but don't execute */
356     {
357       /* save current process's return SS:SP now */
358       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
359       PDB16 *psp = (PDB16 *)psp_start;
360       psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
361     }
362     ret = MZ_DoLoadImage( hFile, filename, NULL );
363     if (ret) {
364       /* MZ_LoadImage created a new PSP and loaded new values into it,
365        * let's work on the new values now */
366       LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
367       ExecBlock *blk = (ExecBlock *)paramblk;
368       LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
369
370       /* First character contains the length of the command line. */
371       MZ_FillPSP(psp_start, cmdline + 1, cmdline[0]);
372
373       /* the lame MS-DOS engineers decided that the return address should be in int22 */
374       DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
375       if (func) {
376         /* don't execute, just return startup state */
377         blk->init_cs = init_cs;
378         blk->init_ip = init_ip;
379         blk->init_ss = init_ss;
380         blk->init_sp = init_sp;
381       } else {
382         /* execute by making us return to new process */
383         context->SegCs = init_cs;
384         context->Eip   = init_ip;
385         context->SegSs = init_ss;
386         context->Esp   = init_sp;
387         context->SegDs = DOSVM_psp;
388         context->SegEs = DOSVM_psp;
389         context->Eax   = 0;
390       }
391     }
392     break;
393   case 3: /* load overlay */
394     {
395       OverlayBlock *blk = (OverlayBlock *)paramblk;
396       ret = MZ_DoLoadImage( hFile, filename, blk );
397     }
398     break;
399   default:
400     FIXME("EXEC load type %d not implemented\n", func);
401     SetLastError(ERROR_INVALID_FUNCTION);
402     break;
403   }
404   CloseHandle(hFile);
405   return ret;
406 }
407
408 /***********************************************************************
409  *              MZ_AllocDPMITask
410  */
411 void WINAPI MZ_AllocDPMITask( void )
412 {
413   MZ_InitMemory();
414   MZ_InitTask();
415 }
416
417 /***********************************************************************
418  *              MZ_RunInThread
419  */
420 void WINAPI MZ_RunInThread( PAPCFUNC proc, ULONG_PTR arg )
421 {
422   if (loop_thread) {
423     DOS_SPC spc;
424     HANDLE event;
425
426     spc.proc = proc;
427     spc.arg = arg;
428     event = CreateEventA(NULL, TRUE, FALSE, NULL);
429     PostThreadMessageA(loop_tid, WM_USER, event, (LPARAM)&spc);
430     WaitForSingleObject(event, INFINITE);
431     CloseHandle(event);
432   } else
433     proc(arg);
434 }
435
436 static DWORD WINAPI MZ_DOSVM( LPVOID lpExtra )
437 {
438   CONTEXT context;
439   DWORD ret;
440
441   dosvm_pid = getpid();
442
443   memset( &context, 0, sizeof(context) );
444   context.SegCs  = init_cs;
445   context.Eip    = init_ip;
446   context.SegSs  = init_ss;
447   context.Esp    = init_sp;
448   context.SegDs  = DOSVM_psp;
449   context.SegEs  = DOSVM_psp;
450   context.EFlags = 0x00080000;  /* virtual interrupt flag */
451   DOSVM_SetTimer(0x10000);
452   ret = DOSVM_Enter( &context );
453
454   dosvm_pid = 0;
455   return ret;
456 }
457
458 static BOOL MZ_InitTask(void)
459 {
460   if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
461                        GetCurrentProcess(), &loop_thread,
462                        0, FALSE, DUPLICATE_SAME_ACCESS))
463     return FALSE;
464   dosvm_thread = CreateThread(NULL, 0, MZ_DOSVM, NULL, CREATE_SUSPENDED, &dosvm_tid);
465   if (!dosvm_thread) {
466     CloseHandle(loop_thread);
467     loop_thread = 0;
468     return FALSE;
469   }
470   loop_tid = GetCurrentThreadId();
471   return TRUE;
472 }
473
474 static void MZ_Launch(void)
475 {
476   TDB *pTask = TASK_GetPtr( GetCurrentTask() );
477   BYTE *psp_start = PTR_REAL_TO_LIN( DOSVM_psp, 0 );
478   LPSTR cmdline = GetCommandLineA();
479   DWORD rv;
480   SYSLEVEL *lock;
481
482   MZ_FillPSP(psp_start, cmdline, cmdline ? strlen(cmdline) : 0);
483   pTask->flags |= TDBF_WINOLDAP;
484
485   GetpWin16Lock( &lock );
486   _LeaveSysLevel( lock );
487
488   ResumeThread(dosvm_thread);
489   rv = DOSVM_Loop(dosvm_thread);
490
491   CloseHandle(dosvm_thread);
492   dosvm_thread = 0; dosvm_tid = 0;
493   CloseHandle(loop_thread);
494   loop_thread = 0; loop_tid = 0;
495
496   VGA_Clean();
497   ExitThread(rv);
498 }
499
500 /***********************************************************************
501  *              MZ_Exit
502  */
503 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
504 {
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( PTR_REAL_TO_LIN(psp->environment,0) );
521       DOSMEM_FreeBlock( PTR_REAL_TO_LIN(DOSVM_psp,0) );
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       TRACE("killing DOS task\n");
535   }
536   ExitThread( retval );
537 }
538
539
540 /***********************************************************************
541  *              MZ_Current
542  */
543 BOOL WINAPI MZ_Current( void )
544 {
545   return (dosvm_pid != 0); /* FIXME: do a better check */
546 }
547
548 #else /* !MZ_SUPPORTED */
549
550 /***********************************************************************
551  *              LoadDosExe (WINEDOS.@)
552  */
553 void WINAPI MZ_LoadImage( LPCSTR filename, HANDLE hFile )
554 {
555   WARN("DOS executables not supported on this platform\n");
556   SetLastError(ERROR_BAD_FORMAT);
557 }
558
559 /***********************************************************************
560  *              MZ_Exec
561  */
562 BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
563 {
564   /* can't happen */
565   SetLastError(ERROR_BAD_FORMAT);
566   return FALSE;
567 }
568
569 /***********************************************************************
570  *              MZ_AllocDPMITask
571  */
572 void WINAPI MZ_AllocDPMITask( void )
573 {
574     ERR("Actual real-mode calls not supported on this platform!\n");
575 }
576
577 /***********************************************************************
578  *              MZ_Exit
579  */
580 void WINAPI MZ_Exit( CONTEXT86 *context, BOOL cs_psp, WORD retval )
581 {
582   ExitThread( retval );
583 }
584
585 /***********************************************************************
586  *              MZ_Current
587  */
588 BOOL WINAPI MZ_Current( void )
589 {
590     return FALSE;
591 }
592
593 #endif /* !MZ_SUPPORTED */