kernel32: Work around safety check on siglongjmp.
[wine/multimedia.git] / dlls / krnl386.exe16 / dosmem.c
blobc73faf14b9681e785b8711e0d399442ce0498e4a
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);
124 /***********************************************************************
125 * DOSMEM_FillIsrTable
127 * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
129 * NOTES:
130 * Linux normally only traps INTs performed from or destined to BIOSSEG
131 * for us to handle, if the int_revectored table is empty. Filling the
132 * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
133 * to hook interrupts, as well as use their familiar retf tricks to call
134 * them, AND let Wine handle any unhooked interrupts transparently.
136 static void DOSMEM_FillIsrTable(void)
138 SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
139 int x;
141 for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
144 static void DOSMEM_MakeIsrStubs(void)
146 DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
147 int x;
149 for (x=0; x<256; x++) stub[x]=VM_STUB(x);
152 BIOSDATA* DOSVM_BiosData(void)
154 return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
157 /**********************************************************************
158 * DOSMEM_GetTicksSinceMidnight
160 * Return number of clock ticks since midnight.
162 static DWORD DOSMEM_GetTicksSinceMidnight(void)
164 SYSTEMTIME time;
166 /* This should give us the (approximately) correct
167 * 18.206 clock ticks per second since midnight.
170 GetLocalTime( &time );
172 return (((time.wHour * 3600 + time.wMinute * 60 +
173 time.wSecond) * 18206) / 1000) +
174 (time.wMilliseconds * 1000 / 54927);
177 /***********************************************************************
178 * DOSMEM_FillBiosSegments
180 * Fill the BIOS data segment with dummy values.
182 static void DOSMEM_FillBiosSegments(void)
184 BYTE *pBiosSys = (BYTE*)DOSMEM_dosmem + 0xf0000;
185 BYTE *pBiosROMTable = pBiosSys+0xe6f5;
186 BIOSDATA *pBiosData = DOSVM_BiosData();
187 static const char bios_date[] = "13/01/99";
189 /* Clear all unused values */
190 memset( pBiosData, 0, sizeof(*pBiosData) );
192 /* FIXME: should check the number of configured drives and ports */
193 pBiosData->Com1Addr = 0x3f8;
194 pBiosData->Com2Addr = 0x2f8;
195 pBiosData->Lpt1Addr = 0x378;
196 pBiosData->Lpt2Addr = 0x278;
197 pBiosData->InstalledHardware = 0x5463;
198 pBiosData->MemSize = 640;
199 pBiosData->NextKbdCharPtr = 0x1e;
200 pBiosData->FirstKbdCharPtr = 0x1e;
201 pBiosData->VideoMode = 3;
202 pBiosData->VideoColumns = 80;
203 pBiosData->VideoPageSize = 80 * 25 * 2;
204 pBiosData->VideoPageStartAddr = 0xb800;
205 pBiosData->VideoCtrlAddr = 0x3d4;
206 pBiosData->Ticks = DOSMEM_GetTicksSinceMidnight();
207 pBiosData->NbHardDisks = 2;
208 pBiosData->KbdBufferStart = 0x1e;
209 pBiosData->KbdBufferEnd = 0x3e;
210 pBiosData->RowsOnScreenMinus1 = 24;
211 pBiosData->BytesPerChar = 0x10;
212 pBiosData->ModeOptions = 0x64;
213 pBiosData->FeatureBitsSwitches = 0xf9;
214 pBiosData->VGASettings = 0x51;
215 pBiosData->DisplayCombination = 0x08;
216 pBiosData->DiskDataRate = 0;
218 /* fill ROM configuration table (values from Award) */
219 *(pBiosROMTable+0x0) = 0x08; /* number of bytes following LO */
220 *(pBiosROMTable+0x1) = 0x00; /* number of bytes following HI */
221 *(pBiosROMTable+0x2) = 0xfc; /* model */
222 *(pBiosROMTable+0x3) = 0x01; /* submodel */
223 *(pBiosROMTable+0x4) = 0x00; /* BIOS revision */
224 *(pBiosROMTable+0x5) = 0x74; /* feature byte 1 */
225 *(pBiosROMTable+0x6) = 0x00; /* feature byte 2 */
226 *(pBiosROMTable+0x7) = 0x00; /* feature byte 3 */
227 *(pBiosROMTable+0x8) = 0x00; /* feature byte 4 */
228 *(pBiosROMTable+0x9) = 0x00; /* feature byte 5 */
230 /* BIOS date string */
231 memcpy(pBiosSys+0xfff5, bios_date, sizeof bios_date);
233 /* BIOS ID */
234 *(pBiosSys+0xfffe) = 0xfc;
236 /* Reboot vector (f000:fff0 or ffff:0000) */
237 *(DWORD*)(pBiosSys + 0xfff0) = VM_STUB(0x19);
240 /***********************************************************************
241 * BiosTick
243 * Increment the BIOS tick counter. Called by timer signal handler.
245 static void CALLBACK BiosTick( LPVOID arg, DWORD low, DWORD high )
247 BIOSDATA *pBiosData = arg;
248 pBiosData->Ticks++;
251 /***********************************************************************
252 * timer_thread
254 static DWORD CALLBACK timer_thread( void *arg )
256 LARGE_INTEGER when;
257 HANDLE timer;
259 if (!(timer = CreateWaitableTimerA( NULL, FALSE, NULL ))) return 0;
261 when.u.LowPart = when.u.HighPart = 0;
262 SetWaitableTimer( timer, &when, 55 /* actually 54.925 */, BiosTick, arg, FALSE );
263 for (;;) SleepEx( INFINITE, TRUE );
266 /***********************************************************************
267 * DOSMEM_Collapse
269 * Helper function for internal use only.
270 * Attach all following free blocks to this one, even if this one is not free.
272 static void DOSMEM_Collapse( MCB* mcb )
274 MCB* next = MCB_NEXT( mcb );
276 while (next && next->psp == MCB_PSP_FREE)
278 mcb->size = mcb->size + next->size + 1;
279 mcb->type = next->type; /* make sure keeping MCB_TYPE_LAST */
280 next = MCB_NEXT( next );
284 /******************************************************************
285 * DOSMEM_InitDosMemory
287 BOOL DOSMEM_InitDosMemory(void)
289 static int done;
290 static HANDLE hRunOnce;
292 if (done) return TRUE;
294 /* FIXME: this isn't 100% thread safe, as we won't catch accesses while initializing */
295 if (hRunOnce == 0)
297 HANDLE hEvent = CreateEventW( NULL, TRUE, FALSE, NULL );
298 if (InterlockedCompareExchangePointer( &hRunOnce, hEvent, 0 ) == 0)
300 BOOL ret;
301 DWORD reserve;
303 /* ok, we're the winning thread */
304 if (!(ret = VirtualProtect( DOSMEM_dosmem + DOSMEM_protect,
305 DOSMEM_SIZE - DOSMEM_protect,
306 PAGE_READWRITE, NULL )))
307 ERR("Cannot load access low 1Mb, DOS subsystem unavailable\n");
308 RtlRemoveVectoredExceptionHandler( dosmem_handler );
311 * Reserve either:
312 * - lowest 64k for NULL pointer catching (Win16)
313 * - lowest 1k for interrupt handlers and
314 * another 0.5k for BIOS, DOS and intra-application
315 * areas (DOS)
317 if (DOSMEM_dosmem != DOSMEM_sysmem)
318 reserve = 0x10000; /* 64k */
319 else
320 reserve = 0x600; /* 1.5k */
323 * Set DOS memory base and initialize conventional memory.
325 DOSMEM_FillBiosSegments();
326 DOSMEM_FillIsrTable();
328 /* align root block to paragraph */
329 DOSMEM_root_block = (MCB*)(DOSMEM_dosmem + reserve);
330 DOSMEM_root_block->type = MCB_TYPE_LAST;
331 DOSMEM_root_block->psp = MCB_PSP_FREE;
332 DOSMEM_root_block->size = (DOSMEM_dosmem + 0x9fffc - ((char*)DOSMEM_root_block)) >> 4;
334 TRACE("DOS conventional memory initialized, %d bytes free.\n",
335 DOSMEM_Available());
337 DOSVM_InitSegments();
338 CloseHandle( CreateThread( NULL, 0, timer_thread, DOSVM_BiosData(), 0, NULL ));
340 SetEvent( hRunOnce );
341 done = 1;
342 return ret;
344 /* someone beat us here... */
345 CloseHandle( hEvent );
348 /* and wait for the winner to have finished */
349 WaitForSingleObject( hRunOnce, INFINITE );
350 return TRUE;
353 /******************************************************************
354 * dosmem_handler
356 * Handler to catch access to our 1MB address space reserved for real memory
358 static LONG WINAPI dosmem_handler(EXCEPTION_POINTERS* except)
360 if (except->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
362 char *addr = (char *)except->ExceptionRecord->ExceptionInformation[1];
363 if (addr >= DOSMEM_dosmem + DOSMEM_protect && addr < DOSMEM_dosmem + DOSMEM_SIZE)
365 if (DOSMEM_InitDosMemory()) return EXCEPTION_CONTINUE_EXECUTION;
368 return EXCEPTION_CONTINUE_SEARCH;
371 /***********************************************************************
372 * DOSMEM_Init
374 * Create the dos memory segments, and store them into the KERNEL
375 * exported values.
377 BOOL DOSMEM_Init(void)
379 void *addr = (void *)1;
380 SIZE_T size = DOSMEM_SIZE - 1;
382 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 0, &size,
383 MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS ))
385 ERR( "Cannot allocate DOS memory\n" );
386 ExitProcess(1);
389 if (addr <= (void *)DOSMEM_64KB)
391 DOSMEM_dosmem = 0;
392 DOSMEM_protect = DOSMEM_64KB;
393 DOSMEM_sysmem = (char *)0xf0000; /* store sysmem in high addresses for now */
395 else
397 WARN( "First megabyte not available for DOS address space.\n" );
398 DOSMEM_dosmem = addr;
399 DOSMEM_protect = 0;
400 DOSMEM_sysmem = DOSMEM_dosmem;
403 RtlAddVectoredExceptionHandler(FALSE, dosmem_handler);
404 DOSMEM_0000H = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem,
405 DOSMEM_64KB, 0, WINE_LDT_FLAGS_DATA );
406 DOSMEM_BiosDataSeg = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem + 0x400,
407 0x100, 0, WINE_LDT_FLAGS_DATA );
408 DOSMEM_BiosSysSeg = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_dosmem + 0xf0000,
409 DOSMEM_64KB, 0, WINE_LDT_FLAGS_DATA );
411 return TRUE;
414 /***********************************************************************
415 * DOSMEM_MapLinearToDos
417 * Linear address to the DOS address space.
419 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
421 if (((char*)ptr >= DOSMEM_dosmem) &&
422 ((char*)ptr < DOSMEM_dosmem + DOSMEM_SIZE))
423 return (char *)ptr - DOSMEM_dosmem;
424 return (UINT)ptr;
428 /***********************************************************************
429 * DOSMEM_MapDosToLinear
431 * DOS linear address to the linear address space.
433 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
435 if (ptr < DOSMEM_SIZE) return DOSMEM_dosmem + ptr;
436 return (LPVOID)ptr;
440 /***********************************************************************
441 * DOSMEM_MapRealToLinear
443 * Real mode DOS address into a linear pointer
445 LPVOID DOSMEM_MapRealToLinear(DWORD x)
447 LPVOID lin;
449 lin = DOSMEM_dosmem + HIWORD(x) * 16 + LOWORD(x);
450 TRACE_(selector)("(0x%08x) returns %p.\n", x, lin );
451 return lin;
454 /***********************************************************************
455 * DOSMEM_AllocBlock
457 * Carve a chunk of the DOS memory block (without selector).
459 LPVOID DOSMEM_AllocBlock(UINT size, UINT16* pseg)
461 MCB *curr;
462 MCB *next = NULL;
463 WORD psp = DOSVM_psp;
465 DOSMEM_InitDosMemory();
467 curr = DOSMEM_root_block;
468 if (!(psp = DOSVM_psp)) psp = MCB_PSP_DOS;
470 *pseg = 0;
472 TRACE( "(%04xh)\n", size );
474 /* round up to paragraph */
475 size = (size + 15) >> 4;
477 #ifdef __DOSMEM_DEBUG__
478 DOSMEM_Available(); /* checks the whole MCB list */
479 #endif
481 /* loop over all MCB and search the next large enough MCB */
482 while (curr)
484 if (!MCB_VALID (curr))
486 ERR( "MCB List Corrupt\n" );
487 MCB_DUMP( curr );
488 return NULL;
490 if (curr->psp == MCB_PSP_FREE)
492 DOSMEM_Collapse( curr );
493 /* is it large enough (one paragraph for the MCB)? */
494 if (curr->size >= size)
496 if (curr->size > size)
498 /* split curr */
499 next = (MCB *) ((char*) curr + ((size+1) << 4));
500 next->psp = MCB_PSP_FREE;
501 next->size = curr->size - (size+1);
502 next->type = curr->type;
503 curr->type = MCB_TYPE_NORMAL;
504 curr->size = size;
506 /* curr is the found block */
507 curr->psp = psp;
508 if( pseg ) *pseg = (((char*)curr) + 16 - DOSMEM_dosmem) >> 4;
509 return (LPVOID) ((char*)curr + 16);
512 curr = MCB_NEXT(curr);
514 return NULL;
517 /***********************************************************************
518 * DOSMEM_FreeBlock
520 BOOL DOSMEM_FreeBlock(void* ptr)
522 MCB* mcb = (MCB*) ((char*)ptr - 16);
524 TRACE( "(%p)\n", ptr );
526 #ifdef __DOSMEM_DEBUG__
527 DOSMEM_Available();
528 #endif
530 if (!MCB_VALID (mcb))
532 ERR( "MCB invalid\n" );
533 MCB_DUMP( mcb );
534 return FALSE;
537 mcb->psp = MCB_PSP_FREE;
538 DOSMEM_Collapse( mcb );
539 return TRUE;
542 /***********************************************************************
543 * DOSMEM_ResizeBlock
545 * Resize DOS memory block in place. Returns block size or -1 on error.
547 * If exact is TRUE, returned value is either old or requested block
548 * size. If exact is FALSE, block is expanded even if there is not
549 * enough space for full requested block size.
551 * TODO: return also biggest block size
553 UINT DOSMEM_ResizeBlock(void *ptr, UINT size, BOOL exact)
555 MCB* mcb = (MCB*) ((char*)ptr - 16);
556 MCB* next;
558 TRACE( "(%p,%04xh,%s)\n", ptr, size, exact ? "TRUE" : "FALSE" );
560 /* round up to paragraph */
561 size = (size + 15) >> 4;
563 #ifdef __DOSMEM_DEBUG__
564 DOSMEM_Available();
565 #endif
567 if (!MCB_VALID (mcb))
569 ERR( "MCB invalid\n" );
570 MCB_DUMP( mcb );
571 return -1;
574 /* resize needed? */
575 if (mcb->size == size)
576 return size << 4;
578 /* collapse free blocks */
579 DOSMEM_Collapse( mcb );
581 /* shrink mcb ? */
582 if (mcb->size > size)
584 next = (MCB *) ((char*)mcb + ((size+1) << 4));
585 next->type = mcb->type;
586 next->psp = MCB_PSP_FREE;
587 next->size = mcb->size - (size+1);
588 mcb->type = MCB_TYPE_NORMAL;
589 mcb->size = size;
590 return size << 4;
593 if (!exact)
595 return mcb->size << 4;
598 return -1;
601 /***********************************************************************
602 * DOSMEM_Available
604 UINT DOSMEM_Available(void)
606 UINT available = 0;
607 UINT total = 0;
608 MCB *curr = DOSMEM_root_block;
609 /* loop over all MCB and search the largest free MCB */
610 while (curr)
612 #ifdef __DOSMEM_DEBUG__
613 MCB_DUMP( curr );
614 #endif
615 if (!MCB_VALID (curr))
617 ERR( "MCB List Corrupt\n" );
618 MCB_DUMP( curr );
619 return 0;
621 if (curr->psp == MCB_PSP_FREE &&
622 curr->size > available )
623 available = curr->size;
625 total += curr->size + 1;
626 curr = MCB_NEXT( curr );
628 TRACE( " %04xh of %04xh paragraphs available\n", available, total );
629 return available << 4;
632 /******************************************************************
633 * DOSMEM_MapDosLayout
635 * Initialize the first MB of memory to look like a real DOS setup
637 BOOL DOSMEM_MapDosLayout(void)
639 static int already_mapped;
641 if (!already_mapped)
643 if (DOSMEM_dosmem || !VirtualProtect( NULL, DOSMEM_SIZE, PAGE_EXECUTE_READWRITE, NULL ))
645 ERR( "Need full access to the first megabyte for DOS mode\n" );
646 ExitProcess(1);
648 /* copy the BIOS and ISR area down */
649 memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
650 DOSMEM_sysmem = DOSMEM_dosmem;
651 SetSelectorBase( DOSMEM_0000H, 0 );
652 SetSelectorBase( DOSMEM_BiosDataSeg, 0x400 );
653 /* we may now need the actual interrupt stubs, and since we've just moved the
654 * interrupt vector table away, we can fill the area with stubs instead... */
655 DOSMEM_MakeIsrStubs();
656 already_mapped = 1;
658 return TRUE;