winedos: Clear TF bit before passing control to a VM86 interrupt handler.
[wine] / dlls / winedos / dosmem.c
1 /*
2  * DOS memory emulation
3  *
4  * Copyright 1995 Alexandre Julliard
5  * Copyright 1996 Marcus Meissner
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #ifdef HAVE_SYS_MMAN_H
31 # include <sys/mman.h>
32 #endif
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winreg.h"
37 #include "excpt.h"
38 #include "winternl.h"
39 #include "wine/winbase16.h"
40
41 #include "dosexe.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(dosmem);
45
46 /* DOS memory highest address (including HMA) */
47 #define DOSMEM_SIZE             0x110000
48 #define DOSMEM_64KB             0x10000
49
50 /* see dlls/kernel/dosmem.c for the details */
51 static char *DOSMEM_dosmem;
52 static char *DOSMEM_sysmem;
53
54 /*
55  * Memory Control Block (MCB) definition
56  * FIXME: implement Allocation Strategy
57  */
58
59 #define MCB_DUMP(mc) \
60     TRACE ("MCB_DUMP base=%p type=%02xh psp=%04xh size=%04xh\n", mc, mc->type, mc->psp , mc->size )
61  
62 #define MCB_NEXT(mc) \
63     (MCB*) ((mc->type==MCB_TYPE_LAST) ? NULL : (char*)(mc) + ((mc->size + 1) << 4) )
64
65 /* FIXME: should we check more? */
66 #define MCB_VALID(mc) \
67     ((mc->type==MCB_TYPE_NORMAL) || (mc->type==MCB_TYPE_LAST))
68
69
70 #define MCB_TYPE_NORMAL    0x4d
71 #define MCB_TYPE_LAST      0x5a
72
73 #define MCB_PSP_DOS        0x0060  
74 #define MCB_PSP_FREE       0
75
76 #include "pshpack1.h"
77 typedef struct {
78     BYTE type;
79     WORD psp;     /* segment of owner psp */
80     WORD size;    /* in paragraphs */
81     BYTE pad[3];
82     BYTE name[8];
83 } MCB;
84 #include "poppack.h"
85
86 /*
87 #define __DOSMEM_DEBUG__
88  */
89
90 #define VM_STUB(x) (0x90CF00CD|(x<<8)) /* INT x; IRET; NOP */
91 #define VM_STUB_SEGMENT 0xf000         /* BIOS segment */
92
93 /* FIXME: this should be moved to the LOL */
94 static MCB* DOSMEM_root_block;
95
96 /***********************************************************************
97  *           DOSMEM_MemoryTop
98  *
99  * Gets the DOS memory top.
100  */
101 static char *DOSMEM_MemoryTop(void)
102 {
103     return DOSMEM_dosmem+0x9FFFC; /* 640K */
104 }
105
106 /***********************************************************************
107  *           DOSMEM_FillIsrTable
108  *
109  * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
110  *
111  * NOTES:
112  * Linux normally only traps INTs performed from or destined to BIOSSEG
113  * for us to handle, if the int_revectored table is empty. Filling the
114  * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
115  * to hook interrupts, as well as use their familiar retf tricks to call
116  * them, AND let Wine handle any unhooked interrupts transparently.
117  */
118 static void DOSMEM_FillIsrTable(void)
119 {
120     SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
121     int x;
122
123     for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
124 }
125
126 static void DOSMEM_MakeIsrStubs(void)
127 {
128     DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
129     int x;
130
131     for (x=0; x<256; x++) stub[x]=VM_STUB(x);
132 }
133
134 BIOSDATA* DOSVM_BiosData(void)
135 {
136     return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
137 }
138
139 /**********************************************************************
140  *          DOSMEM_GetTicksSinceMidnight
141  *
142  * Return number of clock ticks since midnight.
143  */
144 static DWORD DOSMEM_GetTicksSinceMidnight(void)
145 {
146     SYSTEMTIME time;
147
148     /* This should give us the (approximately) correct
149      * 18.206 clock ticks per second since midnight.
150      */
151
152     GetLocalTime( &time );
153
154     return (((time.wHour * 3600 + time.wMinute * 60 +
155               time.wSecond) * 18206) / 1000) +
156              (time.wMilliseconds * 1000 / 54927);
157 }
158
159 /***********************************************************************
160  *           DOSMEM_FillBiosSegments
161  *
162  * Fill the BIOS data segment with dummy values.
163  */
164 static void DOSMEM_FillBiosSegments(void)
165 {
166     BYTE *pBiosSys = (BYTE*)DOSMEM_dosmem + 0xf0000;
167     BYTE *pBiosROMTable = pBiosSys+0xe6f5;
168     BIOSDATA *pBiosData = DOSVM_BiosData();
169     static const char bios_date[] = "13/01/99";
170
171       /* Clear all unused values */
172     memset( pBiosData, 0, sizeof(*pBiosData) );
173
174     /* FIXME: should check the number of configured drives and ports */
175     pBiosData->Com1Addr             = 0x3f8;
176     pBiosData->Com2Addr             = 0x2f8;
177     pBiosData->Lpt1Addr             = 0x378;
178     pBiosData->Lpt2Addr             = 0x278;
179     pBiosData->InstalledHardware    = 0x5463;
180     pBiosData->MemSize              = 640;
181     pBiosData->NextKbdCharPtr       = 0x1e;
182     pBiosData->FirstKbdCharPtr      = 0x1e;
183     pBiosData->VideoMode            = 3;
184     pBiosData->VideoColumns         = 80;
185     pBiosData->VideoPageSize        = 80 * 25 * 2;
186     pBiosData->VideoPageStartAddr   = 0xb800;
187     pBiosData->VideoCtrlAddr        = 0x3d4;
188     pBiosData->Ticks                = DOSMEM_GetTicksSinceMidnight();
189     pBiosData->NbHardDisks          = 2;
190     pBiosData->KbdBufferStart       = 0x1e;
191     pBiosData->KbdBufferEnd         = 0x3e;
192     pBiosData->RowsOnScreenMinus1   = 24;
193     pBiosData->BytesPerChar         = 0x10;
194     pBiosData->ModeOptions          = 0x64;
195     pBiosData->FeatureBitsSwitches  = 0xf9;
196     pBiosData->VGASettings          = 0x51;
197     pBiosData->DisplayCombination   = 0x08;
198     pBiosData->DiskDataRate         = 0;
199
200     /* fill ROM configuration table (values from Award) */
201     *(pBiosROMTable+0x0)        = 0x08; /* number of bytes following LO */
202     *(pBiosROMTable+0x1)        = 0x00; /* number of bytes following HI */
203     *(pBiosROMTable+0x2)        = 0xfc; /* model */
204     *(pBiosROMTable+0x3)        = 0x01; /* submodel */
205     *(pBiosROMTable+0x4)        = 0x00; /* BIOS revision */
206     *(pBiosROMTable+0x5)        = 0x74; /* feature byte 1 */
207     *(pBiosROMTable+0x6)        = 0x00; /* feature byte 2 */
208     *(pBiosROMTable+0x7)        = 0x00; /* feature byte 3 */
209     *(pBiosROMTable+0x8)        = 0x00; /* feature byte 4 */
210     *(pBiosROMTable+0x9)        = 0x00; /* feature byte 5 */
211
212     /* BIOS date string */
213     memcpy(pBiosSys+0xfff5, bios_date, sizeof bios_date);
214
215     /* BIOS ID */
216     *(pBiosSys+0xfffe) = 0xfc;
217
218     /* Reboot vector (f000:fff0 or ffff:0000) */
219     *(DWORD*)(pBiosSys + 0xfff0) = VM_STUB(0x19);
220 }
221
222 /***********************************************************************
223  *           BiosTick
224  *
225  * Increment the BIOS tick counter. Called by timer signal handler.
226  */
227 void BiosTick( WORD timer )
228 {
229     BIOSDATA *pBiosData = DOSVM_BiosData();
230     if (pBiosData) pBiosData->Ticks++;
231 }
232
233 /***********************************************************************
234  *           DOSMEM_Collapse
235  *
236  * Helper function for internal use only.
237  * Atach all following free blocks to this one, even if this one is not free.
238  */
239 void DOSMEM_Collapse( MCB* mcb )
240 {
241     MCB* next = MCB_NEXT( mcb );
242
243     while (next && next->psp == MCB_PSP_FREE)
244     {
245         mcb->size = mcb->size + next->size + 1;
246         mcb->type = next->type;    /* make sure keeping MCB_TYPE_LAST */
247         next = MCB_NEXT( next );
248     }
249 }
250
251 /***********************************************************************
252  *           DOSMEM_AllocBlock
253  *
254  * Carve a chunk of the DOS memory block (without selector).
255  */
256 LPVOID DOSMEM_AllocBlock(UINT size, UINT16* pseg)
257 {
258     MCB *curr = DOSMEM_root_block;
259     MCB *next = NULL;
260     WORD psp = DOSVM_psp;
261     
262     if (!psp)
263         psp = MCB_PSP_DOS;
264     
265     *pseg = 0;
266     
267     TRACE( "(%04xh)\n", size );
268     
269     /* round up to paragraph */
270     size = (size + 15) >> 4;
271
272 #ifdef __DOSMEM_DEBUG__
273     DOSMEM_Available();     /* checks the whole MCB list */
274 #endif
275     
276     /* loop over all MCB and search the next large enough MCB */
277     while (curr)
278     {
279         if (!MCB_VALID (curr))
280         {
281             ERR( "MCB List Corrupt\n" );
282             MCB_DUMP( curr );
283             return NULL;
284         }
285         if (curr->psp == MCB_PSP_FREE)
286         {
287             DOSMEM_Collapse( curr );            
288             /* is it large enough (one paragaph for the MCB)? */
289             if (curr->size >= size)
290             {
291                 if (curr->size > size)
292                 {
293                     /* split curr */
294                     next = (MCB *) ((char*) curr + ((size+1) << 4));
295                     next->psp = MCB_PSP_FREE;
296                     next->size = curr->size - (size+1);
297                     next->type = curr->type;
298                     curr->type = MCB_TYPE_NORMAL;
299                     curr->size = size;
300                 }
301                 /* curr is the found block */
302                 curr->psp = psp;
303                 if( pseg ) *pseg = (((char*)curr) + 16 - (char*)DOSMEM_dosmem) >> 4;
304                 return (LPVOID) ((char*)curr + 16);
305             }
306         }
307         curr = MCB_NEXT(curr);
308     }
309     return NULL;
310 }
311
312 /***********************************************************************
313  *           DOSMEM_FreeBlock
314  */
315 BOOL DOSMEM_FreeBlock(void* ptr)
316 {
317     MCB* mcb = (MCB*) ((char*)ptr - 16);
318     
319     TRACE( "(%p)\n", ptr );
320
321 #ifdef __DOSMEM_DEBUG__
322     DOSMEM_Available();
323 #endif
324     
325     if (!MCB_VALID (mcb))
326     {
327         ERR( "MCB invalid\n" );
328         MCB_DUMP( mcb );
329         return FALSE;
330     }
331     
332     mcb->psp = MCB_PSP_FREE;
333     DOSMEM_Collapse( mcb );
334     return TRUE;
335 }
336
337 /***********************************************************************
338  *           DOSMEM_ResizeBlock
339  *
340  * Resize DOS memory block in place. Returns block size or -1 on error.
341  *
342  * If exact is TRUE, returned value is either old or requested block
343  * size. If exact is FALSE, block is expanded even if there is not
344  * enough space for full requested block size.
345  *
346  * TODO: return also biggest block size
347  */
348 UINT DOSMEM_ResizeBlock(void *ptr, UINT size, BOOL exact)
349 {
350     MCB* mcb = (MCB*) ((char*)ptr - 16);
351     MCB* next;
352     
353     TRACE( "(%p,%04xh,%s)\n", ptr, size, exact ? "TRUE" : "FALSE" );
354     
355     /* round up to paragraph */
356     size = (size + 15) >> 4;
357
358 #ifdef __DOSMEM_DEBUG__
359     DOSMEM_Available();
360 #endif
361     
362     if (!MCB_VALID (mcb))
363     {
364         ERR( "MCB invalid\n" );
365         MCB_DUMP( mcb );
366         return -1;
367     }
368
369     /* resize needed? */
370     if (mcb->size == size)
371         return size;
372
373     /* collapse free blocks */
374     DOSMEM_Collapse( mcb );    
375     
376     /* shrink mcb ? */
377     if (mcb->size > size)
378     {
379         next = (MCB *) ((char*)mcb + ((size+1) << 4));
380         next->type = mcb->type;
381         next->psp = MCB_PSP_FREE;
382         next->size = mcb->size - (size+1);
383         mcb->type = MCB_TYPE_NORMAL;
384         mcb->size = size;
385         return size << 4;
386     }
387     
388     if (!exact)
389     {
390         return mcb->size << 4;
391     }
392     
393     return -1;
394 }
395
396 /***********************************************************************
397  *           DOSMEM_Available
398  */
399 UINT DOSMEM_Available(void)
400 {
401     UINT  available = 0;
402     UINT  total = 0;
403     MCB *curr = DOSMEM_root_block;
404     /* loop over all MCB and search the largest free MCB */
405     while (curr)
406     {
407 #ifdef __DOSMEM_DEBUG__
408         MCB_DUMP( curr );
409 #endif
410         if (!MCB_VALID (curr))
411         {
412             ERR( "MCB List Corrupt\n" );
413             MCB_DUMP( curr );
414             return 0;
415         }
416         if (curr->psp == MCB_PSP_FREE &&
417             curr->size > available )
418             available = curr->size;
419         
420         total += curr->size + 1;
421         curr = MCB_NEXT( curr );
422     }
423     TRACE( " %04xh of %04xh paragraphs available\n", available, total );
424     return available << 4;   
425 }
426
427 /***********************************************************************
428  *           DOSMEM_InitMemory
429  *
430  * Initialises the DOS memory structures.
431  */
432 static void DOSMEM_InitMemory(char* addr)
433 {
434     DOSMEM_FillBiosSegments();
435     DOSMEM_FillIsrTable();
436
437     /* align root block to paragraph */
438     DOSMEM_root_block = (MCB*) (( (DWORD_PTR)(addr+0xf) >> 4) << 4);
439     DOSMEM_root_block->type = MCB_TYPE_LAST;
440     DOSMEM_root_block->psp = MCB_PSP_FREE;
441     DOSMEM_root_block->size = (DOSMEM_MemoryTop() - ((char*)DOSMEM_root_block)) >> 4;
442
443     TRACE("DOS conventional memory initialized, %d bytes free.\n",
444           DOSMEM_Available());
445 }
446
447 /******************************************************************
448  *             DOSMEM_InitDosMemory
449  *
450  * When WineDOS is loaded, initializes the current DOS memory layout.
451  */
452 BOOL DOSMEM_InitDosMemory(void)
453 {
454     HMODULE16           hModule;
455     unsigned short      sel;
456     LDT_ENTRY           entry;
457     DWORD               reserve;
458
459     if (!(hModule = GetModuleHandle16("KERNEL"))) return FALSE;
460     /* KERNEL.194: __F000H */
461     sel = LOWORD(GetProcAddress16(hModule, (LPCSTR)(ULONG_PTR)194));
462     wine_ldt_get_entry(sel, &entry);
463     DOSMEM_dosmem = (char*)wine_ldt_get_base(&entry) - 0xF0000;
464     /* KERNEL.183: __0000H */
465     sel = LOWORD(GetProcAddress16(hModule, (LPCSTR)(DWORD_PTR)183));
466     wine_ldt_get_entry(sel, &entry);
467     DOSMEM_sysmem = wine_ldt_get_base(&entry);
468
469     /*
470      * Reserve either:
471      * - lowest 64k for NULL pointer catching (Win16)
472      * - lowest 1k for interrupt handlers and
473      *   another 0.5k for BIOS, DOS and intra-application
474      *   areas (DOS)
475      */
476     if (DOSMEM_dosmem != DOSMEM_sysmem)
477         reserve = 0x10000; /* 64k */
478     else
479         reserve = 0x600; /* 1.5k */
480
481     /*
482      * Round to paragraph boundary in order to make
483      * sure the alignment is correct.
484      */
485     reserve = ((reserve + 15) >> 4) << 4;
486
487     /*
488      * Set DOS memory base and initialize conventional memory.
489      */
490     DOSMEM_InitMemory(DOSMEM_dosmem + reserve);
491     return TRUE;
492 }
493
494 /******************************************************************
495  *              DOSMEM_MapDosLayout
496  *
497  * Initialize the first MB of memory to look like a real DOS setup
498  */
499 BOOL DOSMEM_MapDosLayout(void)
500 {
501     static int already_mapped;
502
503     if (!already_mapped)
504     {
505         HMODULE16       hModule;
506         unsigned short  sel;
507         LDT_ENTRY       entry;
508
509         if (DOSMEM_dosmem)
510         {
511             ERR( "Needs access to the first megabyte for DOS mode\n" );
512             ExitProcess(1);
513         }
514         MESSAGE( "Warning: unprotecting memory to allow real-mode calls.\n"
515                  "         NULL pointer accesses will no longer be caught.\n" );
516         VirtualProtect( NULL, DOSMEM_SIZE, PAGE_EXECUTE_READWRITE, NULL );
517         /* copy the BIOS and ISR area down */
518         memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
519         DOSMEM_sysmem = DOSMEM_dosmem;
520         hModule = GetModuleHandle16("KERNEL");
521         /* selector to 0000H */
522         sel = LOWORD(GetProcAddress16(hModule, (LPCSTR)(DWORD_PTR)183));
523         wine_ldt_get_entry(sel, &entry);
524         wine_ldt_set_base(&entry, NULL);
525         wine_ldt_set_entry(sel, &entry);
526         /* selector to BiosData */
527         sel = LOWORD(GetProcAddress16(hModule, (LPCSTR)(DWORD_PTR)193));
528         wine_ldt_get_entry(sel, &entry);
529         wine_ldt_set_base(&entry, (const void*)0x400);
530         wine_ldt_set_entry(sel, &entry);
531         /* we may now need the actual interrupt stubs, and since we've just moved the
532          * interrupt vector table away, we can fill the area with stubs instead... */
533         DOSMEM_MakeIsrStubs();
534         already_mapped = 1;
535     }
536     return TRUE;
537 }