dbghelp: Parse the DWARF information in Mach-O modules.
[wine.git] / dlls / krnl386.exe16 / dosmem.c
blobb899f7b93802f470684ee658ffd25ac672cb3408
1 /*
2 * DOS memory emulation
4 * Copyright 1995 Alexandre Julliard
5 * Copyright 1996 Marcus Meissner
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.
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.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
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
34 #include "windef.h"
35 #include "winbase.h"
36 #include "excpt.h"
37 #include "winternl.h"
38 #include "wine/winbase16.h"
40 #include "kernel16_private.h"
41 #include "dosexe.h"
42 #include "wine/debug.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(dosmem);
45 WINE_DECLARE_DEBUG_CHANNEL(selector);
47 WORD DOSMEM_0000H; /* segment at 0:0 */
48 WORD DOSMEM_BiosDataSeg; /* BIOS data segment at 0x40:0 */
49 WORD DOSMEM_BiosSysSeg; /* BIOS ROM segment at 0xf000:0 */
51 /* DOS memory highest address (including HMA) */
52 #define DOSMEM_SIZE 0x110000
53 #define DOSMEM_64KB 0x10000
56 * Memory Control Block (MCB) definition
57 * FIXME: implement Allocation Strategy
60 #define MCB_DUMP(mc) \
61 TRACE ("MCB_DUMP base=%p type=%02xh psp=%04xh size=%04xh\n", mc, mc->type, mc->psp , mc->size )
63 #define MCB_NEXT(mc) \
64 (MCB*) ((mc->type==MCB_TYPE_LAST) ? NULL : (char*)(mc) + ((mc->size + 1) << 4) )
66 /* FIXME: should we check more? */
67 #define MCB_VALID(mc) \
68 ((mc->type==MCB_TYPE_NORMAL) || (mc->type==MCB_TYPE_LAST))
71 #define MCB_TYPE_NORMAL 0x4d
72 #define MCB_TYPE_LAST 0x5a
74 #define MCB_PSP_DOS 0x0060
75 #define MCB_PSP_FREE 0
77 #include "pshpack1.h"
78 typedef struct {
79 BYTE type;
80 WORD psp; /* segment of owner psp */
81 WORD size; /* in paragraphs */
82 BYTE pad[3];
83 BYTE name[8];
84 } MCB;
85 #include "poppack.h"
88 #define __DOSMEM_DEBUG__
91 #define VM_STUB(x) (0x90CF00CD|(x<<8)) /* INT x; IRET; NOP */
92 #define VM_STUB_SEGMENT 0xf000 /* BIOS segment */
94 /* FIXME: this should be moved to the LOL */
95 static MCB* DOSMEM_root_block;
97 /* when looking at DOS and real mode memory, we activate in three different
98 * modes, depending the situation.
99 * 1/ By default (protected mode), the first MB of memory (actually 0x110000,
100 * when you also look at the HMA part) is always reserved, whatever you do.
101 * We allocated some PM selectors to this memory, even if this area is not
102 * committed at startup
103 * 2/ if a program tries to use the memory through the selectors, we actually
104 * commit this memory, made of: BIOS segment, but also some system
105 * information, usually low in memory that we map for the circumstance also
106 * in the BIOS segment, so that we keep the low memory protected (for NULL
107 * pointer deref catching for example). In this case, we're still in PM
108 * mode, accessing part of the "physical" real mode memory. In fact, we don't
109 * map all the first meg, we keep 64k uncommitted to still catch NULL
110 * pointers dereference
111 * 3/ if the process enters the real mode, then we (also) commit the full first
112 * MB of memory (and also initialize the DOS structures in it).
115 /* DOS memory base (linear in process address space) */
116 static char *DOSMEM_dosmem;
117 static char *DOSMEM_sysmem;
118 /* number of bytes protected from _dosmem. 0 when DOS memory is initialized,
119 * 64k otherwise to trap NULL pointers deref */
120 static DWORD DOSMEM_protect;
122 static LONG WINAPI dosmem_handler(EXCEPTION_POINTERS* except);
123 static void *vectored_handler;
125 /***********************************************************************
126 * DOSMEM_FillIsrTable
128 * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
130 * NOTES:
131 * Linux normally only traps INTs performed from or destined to BIOSSEG
132 * for us to handle, if the int_revectored table is empty. Filling the
133 * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
134 * to hook interrupts, as well as use their familiar retf tricks to call
135 * them, AND let Wine handle any unhooked interrupts transparently.
137 static void DOSMEM_FillIsrTable(void)
139 SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
140 int x;
142 for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
145 static void DOSMEM_MakeIsrStubs(void)
147 DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
148 int x;
150 for (x=0; x<256; x++) stub[x]=VM_STUB(x);
153 BIOSDATA* DOSVM_BiosData(void)
155 return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
158 /**********************************************************************
159 * DOSMEM_GetTicksSinceMidnight
161 * Return number of clock ticks since midnight.
163 static DWORD DOSMEM_GetTicksSinceMidnight(void)
165 SYSTEMTIME time;
167 /* This should give us the (approximately) correct
168 * 18.206 clock ticks per second since midnight.
171 GetLocalTime( &time );
173 return (((time.wHour * 3600 + time.wMinute * 60 +
174 time.wSecond) * 18206) / 1000) +
175 (time.wMilliseconds * 1000 / 54927);
178 /***********************************************************************
179 * DOSMEM_FillBiosSegments
181 * Fill the BIOS data segment with dummy values.
183 static void DOSMEM_FillBiosSegments(void)
185 BYTE *pBiosSys = (BYTE*)DOSMEM_dosmem + 0xf0000;
186 BYTE *pBiosROMTable = pBiosSys+0xe6f5;
187 BIOSDATA *pBiosData = DOSVM_BiosData();
188 static const char bios_date[] = "13/01/99";
190 /* Clear all unused values */
191 memset( pBiosData, 0, sizeof(*pBiosData) );
193 /* FIXME: should check the number of configured drives and ports */
194 pBiosData->Com1Addr = 0x3f8;
195 pBiosData->Com2Addr = 0x2f8;
196 pBiosData->Lpt1Addr = 0x378;
197 pBiosData->Lpt2Addr = 0x278;
198 pBiosData->InstalledHardware = 0x5463;
199 pBiosData->MemSize = 640;
200 pBiosData->NextKbdCharPtr = 0x1e;
201 pBiosData->FirstKbdCharPtr = 0x1e;
202 pBiosData->VideoMode = 3;
203 pBiosData->VideoColumns = 80;
204 pBiosData->VideoPageSize = 80 * 25 * 2;
205 pBiosData->VideoPageStartAddr = 0xb800;
206 pBiosData->VideoCtrlAddr = 0x3d4;
207 pBiosData->Ticks = DOSMEM_GetTicksSinceMidnight();
208 pBiosData->NbHardDisks = 2;
209 pBiosData->KbdBufferStart = 0x1e;
210 pBiosData->KbdBufferEnd = 0x3e;
211 pBiosData->RowsOnScreenMinus1 = 24;
212 pBiosData->BytesPerChar = 0x10;
213 pBiosData->ModeOptions = 0x64;
214 pBiosData->FeatureBitsSwitches = 0xf9;
215 pBiosData->VGASettings = 0x51;
216 pBiosData->DisplayCombination = 0x08;
217 pBiosData->DiskDataRate = 0;
219 /* fill ROM configuration table (values from Award) */
220 *(pBiosROMTable+0x0) = 0x08; /* number of bytes following LO */
221 *(pBiosROMTable+0x1) = 0x00; /* number of bytes following HI */
222 *(pBiosROMTable+0x2) = 0xfc; /* model */
223 *(pBiosROMTable+0x3) = 0x01; /* submodel */
224 *(pBiosROMTable+0x4) = 0x00; /* BIOS revision */
225 *(pBiosROMTable+0x5) = 0x74; /* feature byte 1 */
226 *(pBiosROMTable+0x6) = 0x00; /* feature byte 2 */
227 *(pBiosROMTable+0x7) = 0x00; /* feature byte 3 */
228 *(pBiosROMTable+0x8) = 0x00; /* feature byte 4 */
229 *(pBiosROMTable+0x9) = 0x00; /* feature byte 5 */
231 /* BIOS date string */
232 memcpy(pBiosSys+0xfff5, bios_date, sizeof bios_date);
234 /* BIOS ID */
235 *(pBiosSys+0xfffe) = 0xfc;
237 /* Reboot vector (f000:fff0 or ffff:0000) */
238 *(DWORD*)(pBiosSys + 0xfff0) = VM_STUB(0x19);
241 /***********************************************************************
242 * BiosTick
244 * Increment the BIOS tick counter. Called by timer signal handler.
246 static void CALLBACK BiosTick( LPVOID arg, DWORD low, DWORD high )
248 BIOSDATA *pBiosData = arg;
249 pBiosData->Ticks++;
252 /***********************************************************************
253 * timer_thread
255 static DWORD CALLBACK timer_thread( void *arg )
257 LARGE_INTEGER when;
258 HANDLE timer;
260 if (!(timer = CreateWaitableTimerA( NULL, FALSE, NULL ))) return 0;
262 when.u.LowPart = when.u.HighPart = 0;
263 SetWaitableTimer( timer, &when, 55 /* actually 54.925 */, BiosTick, arg, FALSE );
264 for (;;) SleepEx( INFINITE, TRUE );
267 /***********************************************************************
268 * DOSVM_start_bios_timer
270 * Start the BIOS ticks timer when the app accesses selector 0x40.
272 void DOSVM_start_bios_timer(void)
274 static LONG running;
276 if (!InterlockedExchange( &running, 1 ))
277 CloseHandle( CreateThread( NULL, 0, timer_thread, DOSVM_BiosData(), 0, NULL ));
280 /***********************************************************************
281 * DOSMEM_Collapse
283 * Helper function for internal use only.
284 * Attach all following free blocks to this one, even if this one is not free.
286 static void DOSMEM_Collapse( MCB* mcb )
288 MCB* next = MCB_NEXT( mcb );
290 while (next && next->psp == MCB_PSP_FREE)
292 mcb->size = mcb->size + next->size + 1;
293 mcb->type = next->type; /* make sure keeping MCB_TYPE_LAST */
294 next = MCB_NEXT( next );
298 /******************************************************************
299 * DOSMEM_InitDosMemory
301 BOOL DOSMEM_InitDosMemory(void)
303 static BOOL done;
304 static HANDLE hRunOnce;
305 DWORD old_prot;
307 if (done) return TRUE;
309 /* FIXME: this isn't 100% thread safe, as we won't catch accesses while initializing */
310 if (hRunOnce == 0)
312 HANDLE hEvent = CreateEventW( NULL, TRUE, FALSE, NULL );
313 if (InterlockedCompareExchangePointer( &hRunOnce, hEvent, 0 ) == 0)
315 BOOL ret;
316 DWORD reserve;
318 /* ok, we're the winning thread */
319 if (!(ret = VirtualProtect( DOSMEM_dosmem + DOSMEM_protect,
320 DOSMEM_SIZE - DOSMEM_protect,
321 PAGE_READWRITE, &old_prot )))
322 ERR("Cannot load access low 1Mb, DOS subsystem unavailable\n");
323 RemoveVectoredExceptionHandler( vectored_handler );
326 * Reserve either:
327 * - lowest 64k for NULL pointer catching (Win16)
328 * - lowest 1k for interrupt handlers and
329 * another 0.5k for BIOS, DOS and intra-application
330 * areas (DOS)
332 if (DOSMEM_dosmem != DOSMEM_sysmem)
333 reserve = 0x10000; /* 64k */
334 else
335 reserve = 0x600; /* 1.5k */
338 * Set DOS memory base and initialize conventional memory.
340 DOSMEM_FillBiosSegments();
341 DOSMEM_FillIsrTable();
343 /* align root block to paragraph */
344 DOSMEM_root_block = (MCB*)(DOSMEM_dosmem + reserve);
345 DOSMEM_root_block->type = MCB_TYPE_LAST;
346 DOSMEM_root_block->psp = MCB_PSP_FREE;
347 DOSMEM_root_block->size = (DOSMEM_dosmem + 0x9fffc - ((char*)DOSMEM_root_block)) >> 4;
349 TRACE("DOS conventional memory initialized, %d bytes free.\n",
350 DOSMEM_Available());
352 DOSVM_InitSegments();
354 SetEvent( hRunOnce );
355 done = TRUE;
356 return ret;
358 /* someone beat us here... */
359 CloseHandle( hEvent );
362 /* and wait for the winner to have finished */
363 WaitForSingleObject( hRunOnce, INFINITE );
364 return TRUE;
367 /******************************************************************
368 * dosmem_handler
370 * Handler to catch access to our 1MB address space reserved for real memory
372 static LONG WINAPI dosmem_handler(EXCEPTION_POINTERS* except)
374 if (except->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
376 char *addr = (char *)except->ExceptionRecord->ExceptionInformation[1];
377 if (addr >= DOSMEM_dosmem + DOSMEM_protect && addr < DOSMEM_dosmem + DOSMEM_SIZE)
379 if (DOSMEM_InitDosMemory()) return EXCEPTION_CONTINUE_EXECUTION;
382 return EXCEPTION_CONTINUE_SEARCH;
385 /***********************************************************************
386 * DOSMEM_Init
388 * Create the dos memory segments, and store them into the KERNEL
389 * exported values.
391 BOOL DOSMEM_Init(void)
393 void *addr = (void *)1;
394 SIZE_T size = DOSMEM_SIZE - 1;
396 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 0, &size,
397 MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS ))
399 ERR( "Cannot allocate DOS memory\n" );
400 ExitProcess(1);
403 if (addr <= (void *)DOSMEM_64KB)
405 DOSMEM_dosmem = 0;
406 DOSMEM_protect = DOSMEM_64KB;
407 DOSMEM_sysmem = (char *)0xf0000; /* store sysmem in high addresses for now */
409 else
411 WARN( "First megabyte not available for DOS address space.\n" );
412 DOSMEM_dosmem = addr;
413 DOSMEM_protect = 0;
414 DOSMEM_sysmem = DOSMEM_dosmem;
417 vectored_handler = AddVectoredExceptionHandler(FALSE, dosmem_handler);
418 DOSMEM_0000H = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem,
419 DOSMEM_64KB, 0, WINE_LDT_FLAGS_DATA );
420 DOSMEM_BiosDataSeg = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem + 0x400,
421 0x100, 0, WINE_LDT_FLAGS_DATA );
422 DOSMEM_BiosSysSeg = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_dosmem + 0xf0000,
423 DOSMEM_64KB, 0, WINE_LDT_FLAGS_DATA );
425 return TRUE;
428 /***********************************************************************
429 * DOSMEM_MapLinearToDos
431 * Linear address to the DOS address space.
433 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
435 if (((char*)ptr >= DOSMEM_dosmem) &&
436 ((char*)ptr < DOSMEM_dosmem + DOSMEM_SIZE))
437 return (char *)ptr - DOSMEM_dosmem;
438 return (UINT)ptr;
442 /***********************************************************************
443 * DOSMEM_MapDosToLinear
445 * DOS linear address to the linear address space.
447 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
449 if (ptr < DOSMEM_SIZE) return DOSMEM_dosmem + ptr;
450 return (LPVOID)ptr;
454 /***********************************************************************
455 * DOSMEM_MapRealToLinear
457 * Real mode DOS address into a linear pointer
459 LPVOID DOSMEM_MapRealToLinear(DWORD x)
461 LPVOID lin;
463 lin = DOSMEM_dosmem + HIWORD(x) * 16 + LOWORD(x);
464 TRACE_(selector)("(0x%08x) returns %p.\n", x, lin );
465 return lin;
468 /***********************************************************************
469 * DOSMEM_AllocBlock
471 * Carve a chunk of the DOS memory block (without selector).
473 LPVOID DOSMEM_AllocBlock(UINT size, UINT16* pseg)
475 MCB *curr;
476 MCB *next = NULL;
477 WORD psp;
479 DOSMEM_InitDosMemory();
481 curr = DOSMEM_root_block;
482 if (!(psp = DOSVM_psp)) psp = MCB_PSP_DOS;
484 if (pseg) *pseg = 0;
486 TRACE( "(%04xh)\n", size );
488 /* round up to paragraph */
489 size = (size + 15) >> 4;
491 #ifdef __DOSMEM_DEBUG__
492 DOSMEM_Available(); /* checks the whole MCB list */
493 #endif
495 /* loop over all MCB and search the next large enough MCB */
496 while (curr)
498 if (!MCB_VALID (curr))
500 ERR( "MCB List Corrupt\n" );
501 MCB_DUMP( curr );
502 return NULL;
504 if (curr->psp == MCB_PSP_FREE)
506 DOSMEM_Collapse( curr );
507 /* is it large enough (one paragraph for the MCB)? */
508 if (curr->size >= size)
510 if (curr->size > size)
512 /* split curr */
513 next = (MCB *) ((char*) curr + ((size+1) << 4));
514 next->psp = MCB_PSP_FREE;
515 next->size = curr->size - (size+1);
516 next->type = curr->type;
517 curr->type = MCB_TYPE_NORMAL;
518 curr->size = size;
520 /* curr is the found block */
521 curr->psp = psp;
522 if( pseg ) *pseg = (((char*)curr) + 16 - DOSMEM_dosmem) >> 4;
523 return (LPVOID) ((char*)curr + 16);
526 curr = MCB_NEXT(curr);
528 return NULL;
531 /***********************************************************************
532 * DOSMEM_FreeBlock
534 BOOL DOSMEM_FreeBlock(void* ptr)
536 MCB* mcb = (MCB*) ((char*)ptr - 16);
538 TRACE( "(%p)\n", ptr );
540 #ifdef __DOSMEM_DEBUG__
541 DOSMEM_Available();
542 #endif
544 if (!MCB_VALID (mcb))
546 ERR( "MCB invalid\n" );
547 MCB_DUMP( mcb );
548 return FALSE;
551 mcb->psp = MCB_PSP_FREE;
552 DOSMEM_Collapse( mcb );
553 return TRUE;
556 /***********************************************************************
557 * DOSMEM_ResizeBlock
559 * Resize DOS memory block in place. Returns block size or -1 on error.
561 * If exact is TRUE, returned value is either old or requested block
562 * size. If exact is FALSE, block is expanded even if there is not
563 * enough space for full requested block size.
565 * TODO: return also biggest block size
567 UINT DOSMEM_ResizeBlock(void *ptr, UINT size, BOOL exact)
569 MCB* mcb = (MCB*) ((char*)ptr - 16);
570 MCB* next;
572 TRACE( "(%p,%04xh,%s)\n", ptr, size, exact ? "TRUE" : "FALSE" );
574 /* round up to paragraph */
575 size = (size + 15) >> 4;
577 #ifdef __DOSMEM_DEBUG__
578 DOSMEM_Available();
579 #endif
581 if (!MCB_VALID (mcb))
583 ERR( "MCB invalid\n" );
584 MCB_DUMP( mcb );
585 return -1;
588 /* resize needed? */
589 if (mcb->size == size)
590 return size << 4;
592 /* collapse free blocks */
593 DOSMEM_Collapse( mcb );
595 /* shrink mcb ? */
596 if (mcb->size > size)
598 next = (MCB *) ((char*)mcb + ((size+1) << 4));
599 next->type = mcb->type;
600 next->psp = MCB_PSP_FREE;
601 next->size = mcb->size - (size+1);
602 mcb->type = MCB_TYPE_NORMAL;
603 mcb->size = size;
604 return size << 4;
607 if (!exact)
609 return mcb->size << 4;
612 return -1;
615 /***********************************************************************
616 * DOSMEM_Available
618 UINT DOSMEM_Available(void)
620 UINT available = 0;
621 UINT total = 0;
622 MCB *curr = DOSMEM_root_block;
623 /* loop over all MCB and search the largest free MCB */
624 while (curr)
626 #ifdef __DOSMEM_DEBUG__
627 MCB_DUMP( curr );
628 #endif
629 if (!MCB_VALID (curr))
631 ERR( "MCB List Corrupt\n" );
632 MCB_DUMP( curr );
633 return 0;
635 if (curr->psp == MCB_PSP_FREE &&
636 curr->size > available )
637 available = curr->size;
639 total += curr->size + 1;
640 curr = MCB_NEXT( curr );
642 TRACE( " %04xh of %04xh paragraphs available\n", available, total );
643 return available << 4;
646 /******************************************************************
647 * DOSMEM_MapDosLayout
649 * Initialize the first MB of memory to look like a real DOS setup
651 BOOL DOSMEM_MapDosLayout(void)
653 static BOOL already_mapped;
654 DWORD old_prot;
656 if (!already_mapped)
658 if (DOSMEM_dosmem || !VirtualProtect( NULL, DOSMEM_SIZE, PAGE_EXECUTE_READWRITE, &old_prot ))
660 ERR( "Need full access to the first megabyte for DOS mode\n" );
661 ExitProcess(1);
663 /* copy the BIOS and ISR area down */
664 memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
665 DOSMEM_sysmem = DOSMEM_dosmem;
666 SetSelectorBase( DOSMEM_0000H, 0 );
667 SetSelectorBase( DOSMEM_BiosDataSeg, 0x400 );
668 /* we may now need the actual interrupt stubs, and since we've just moved the
669 * interrupt vector table away, we can fill the area with stubs instead... */
670 DOSMEM_MakeIsrStubs();
671 already_mapped = TRUE;
673 return TRUE;