twinapi.appcore: Implement Windows.System.Profile.AnalyticsInfo_get_DeviceFamily.
[wine.git] / dlls / krnl386.exe16 / dosmem.c
blob79ea4039d5d373bb58065523b01deb8125ceb6b7
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 <signal.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
28 #include "windef.h"
29 #include "winbase.h"
30 #include "excpt.h"
31 #include "winternl.h"
32 #include "wine/winbase16.h"
34 #include "kernel16_private.h"
35 #include "dosexe.h"
36 #include "wine/debug.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(dosmem);
39 WINE_DECLARE_DEBUG_CHANNEL(selector);
41 WORD DOSMEM_0000H; /* segment at 0:0 */
42 WORD DOSMEM_BiosDataSeg; /* BIOS data segment at 0x40:0 */
43 WORD DOSMEM_BiosSysSeg; /* BIOS ROM segment at 0xf000:0 */
45 WORD DOSVM_psp = 0;
46 WORD int16_sel = 0;
48 /* DOS memory highest address (including HMA) */
49 #define DOSMEM_SIZE 0x110000
50 #define DOSMEM_64KB 0x10000
53 * Memory Control Block (MCB) definition
54 * FIXME: implement Allocation Strategy
57 #define MCB_DUMP(mc) \
58 TRACE ("MCB_DUMP base=%p type=%02xh psp=%04xh size=%04xh\n", mc, mc->type, mc->psp , mc->size )
60 #define MCB_NEXT(mc) \
61 (MCB*) ((mc->type==MCB_TYPE_LAST) ? NULL : (char*)(mc) + ((mc->size + 1) << 4) )
63 /* FIXME: should we check more? */
64 #define MCB_VALID(mc) \
65 ((mc->type==MCB_TYPE_NORMAL) || (mc->type==MCB_TYPE_LAST))
68 #define MCB_TYPE_NORMAL 0x4d
69 #define MCB_TYPE_LAST 0x5a
71 #define MCB_PSP_DOS 0x0060
72 #define MCB_PSP_FREE 0
74 #include "pshpack1.h"
75 typedef struct {
76 BYTE type;
77 WORD psp; /* segment of owner psp */
78 WORD size; /* in paragraphs */
79 BYTE pad[3];
80 BYTE name[8];
81 } MCB;
82 #include "poppack.h"
85 #define __DOSMEM_DEBUG__
88 #define VM_STUB(x) (0x90CF00CD|(x<<8)) /* INT x; IRET; NOP */
89 #define VM_STUB_SEGMENT 0xf000 /* BIOS segment */
91 /* FIXME: this should be moved to the LOL */
92 static MCB* DOSMEM_root_block;
94 /* when looking at DOS and real mode memory, we activate in three different
95 * modes, depending the situation.
96 * 1/ By default (protected mode), the first MB of memory (actually 0x110000,
97 * when you also look at the HMA part) is always reserved, whatever you do.
98 * We allocated some PM selectors to this memory, even if this area is not
99 * committed at startup
100 * 2/ if a program tries to use the memory through the selectors, we actually
101 * commit this memory, made of: BIOS segment, but also some system
102 * information, usually low in memory that we map for the circumstance also
103 * in the BIOS segment, so that we keep the low memory protected (for NULL
104 * pointer deref catching for example). In this case, we're still in PM
105 * mode, accessing part of the "physical" real mode memory. In fact, we don't
106 * map all the first meg, we keep 64k uncommitted to still catch NULL
107 * pointers dereference
108 * 3/ if the process enters the real mode, then we (also) commit the full first
109 * MB of memory (and also initialize the DOS structures in it).
112 /* DOS memory base (linear in process address space) */
113 static char *DOSMEM_dosmem;
114 static char *DOSMEM_sysmem;
115 /* number of bytes protected from _dosmem. 0 when DOS memory is initialized,
116 * 64k otherwise to trap NULL pointers deref */
117 static DWORD DOSMEM_protect;
119 static LONG WINAPI dosmem_handler(EXCEPTION_POINTERS* except);
120 static void *vectored_handler;
122 /***********************************************************************
123 * DOSMEM_FillIsrTable
125 * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
127 * NOTES:
128 * Linux normally only traps INTs performed from or destined to BIOSSEG
129 * for us to handle, if the int_revectored table is empty. Filling the
130 * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
131 * to hook interrupts, as well as use their familiar retf tricks to call
132 * them, AND let Wine handle any unhooked interrupts transparently.
134 static void DOSMEM_FillIsrTable(void)
136 SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
137 int x;
139 for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
142 static void DOSMEM_MakeIsrStubs(void)
144 DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
145 int x;
147 for (x=0; x<256; x++) stub[x]=VM_STUB(x);
150 BIOSDATA* DOSVM_BiosData(void)
152 return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
155 /**********************************************************************
156 * DOSMEM_GetTicksSinceMidnight
158 * Return number of clock ticks since midnight.
160 static DWORD DOSMEM_GetTicksSinceMidnight(void)
162 SYSTEMTIME time;
164 /* This should give us the (approximately) correct
165 * 18.206 clock ticks per second since midnight.
168 GetLocalTime( &time );
170 return (((time.wHour * 3600 + time.wMinute * 60 +
171 time.wSecond) * 18206) / 1000) +
172 (time.wMilliseconds * 1000 / 54927);
175 /***********************************************************************
176 * DOSMEM_FillBiosSegments
178 * Fill the BIOS data segment with dummy values.
180 static void DOSMEM_FillBiosSegments(void)
182 BYTE *pBiosSys = (BYTE*)DOSMEM_dosmem + 0xf0000;
183 BYTE *pBiosROMTable = pBiosSys+0xe6f5;
184 BIOSDATA *pBiosData = DOSVM_BiosData();
185 static const char bios_date[] = "13/01/99";
187 /* Clear all unused values */
188 memset( pBiosData, 0, sizeof(*pBiosData) );
190 /* FIXME: should check the number of configured drives and ports */
191 pBiosData->Com1Addr = 0x3f8;
192 pBiosData->Com2Addr = 0x2f8;
193 pBiosData->Lpt1Addr = 0x378;
194 pBiosData->Lpt2Addr = 0x278;
195 pBiosData->InstalledHardware = 0x5463;
196 pBiosData->MemSize = 640;
197 pBiosData->NextKbdCharPtr = 0x1e;
198 pBiosData->FirstKbdCharPtr = 0x1e;
199 pBiosData->VideoMode = 3;
200 pBiosData->VideoColumns = 80;
201 pBiosData->VideoPageSize = 80 * 25 * 2;
202 pBiosData->VideoPageStartAddr = 0xb800;
203 pBiosData->VideoCtrlAddr = 0x3d4;
204 pBiosData->Ticks = DOSMEM_GetTicksSinceMidnight();
205 pBiosData->NbHardDisks = 2;
206 pBiosData->KbdBufferStart = 0x1e;
207 pBiosData->KbdBufferEnd = 0x3e;
208 pBiosData->RowsOnScreenMinus1 = 24;
209 pBiosData->BytesPerChar = 0x10;
210 pBiosData->ModeOptions = 0x64;
211 pBiosData->FeatureBitsSwitches = 0xf9;
212 pBiosData->VGASettings = 0x51;
213 pBiosData->DisplayCombination = 0x08;
214 pBiosData->DiskDataRate = 0;
216 /* fill ROM configuration table (values from Award) */
217 *(pBiosROMTable+0x0) = 0x08; /* number of bytes following LO */
218 *(pBiosROMTable+0x1) = 0x00; /* number of bytes following HI */
219 *(pBiosROMTable+0x2) = 0xfc; /* model */
220 *(pBiosROMTable+0x3) = 0x01; /* submodel */
221 *(pBiosROMTable+0x4) = 0x00; /* BIOS revision */
222 *(pBiosROMTable+0x5) = 0x74; /* feature byte 1 */
223 *(pBiosROMTable+0x6) = 0x00; /* feature byte 2 */
224 *(pBiosROMTable+0x7) = 0x00; /* feature byte 3 */
225 *(pBiosROMTable+0x8) = 0x00; /* feature byte 4 */
226 *(pBiosROMTable+0x9) = 0x00; /* feature byte 5 */
228 /* BIOS date string */
229 memcpy(pBiosSys+0xfff5, bios_date, sizeof bios_date);
231 /* BIOS ID */
232 *(pBiosSys+0xfffe) = 0xfc;
234 /* Reboot vector (f000:fff0 or ffff:0000) */
235 *(DWORD*)(pBiosSys + 0xfff0) = VM_STUB(0x19);
238 /***********************************************************************
239 * BiosTick
241 * Increment the BIOS tick counter. Called by timer signal handler.
243 static void CALLBACK BiosTick( LPVOID arg, DWORD low, DWORD high )
245 BIOSDATA *pBiosData = arg;
246 pBiosData->Ticks++;
249 /***********************************************************************
250 * timer_thread
252 static DWORD CALLBACK timer_thread( void *arg )
254 LARGE_INTEGER when;
255 HANDLE timer;
257 if (!(timer = CreateWaitableTimerA( NULL, FALSE, NULL ))) return 0;
259 when.u.LowPart = when.u.HighPart = 0;
260 SetWaitableTimer( timer, &when, 55 /* actually 54.925 */, BiosTick, arg, FALSE );
261 for (;;) SleepEx( INFINITE, TRUE );
264 /***********************************************************************
265 * DOSVM_start_bios_timer
267 * Start the BIOS ticks timer when the app accesses selector 0x40.
269 void DOSVM_start_bios_timer(void)
271 static LONG running;
273 if (!InterlockedExchange( &running, 1 ))
274 CloseHandle( CreateThread( NULL, 0, timer_thread, DOSVM_BiosData(), 0, NULL ));
277 /***********************************************************************
278 * DOSMEM_Collapse
280 * Helper function for internal use only.
281 * Attach all following free blocks to this one, even if this one is not free.
283 static void DOSMEM_Collapse( MCB* mcb )
285 MCB* next = MCB_NEXT( mcb );
287 while (next && next->psp == MCB_PSP_FREE)
289 mcb->size = mcb->size + next->size + 1;
290 mcb->type = next->type; /* make sure keeping MCB_TYPE_LAST */
291 next = MCB_NEXT( next );
296 /***********************************************************************
297 * DOSMEM_InitSegments
299 static void DOSMEM_InitSegments(void)
301 LPSTR ptr;
302 int i;
305 * PM / offset N*5: Interrupt N in 16-bit protected mode.
307 int16_sel = GLOBAL_Alloc( GMEM_FIXED, 5 * 256, 0, LDT_FLAGS_CODE );
308 ptr = GlobalLock16( int16_sel );
309 for(i=0; i<256; i++) {
311 * Each 16-bit interrupt handler is 5 bytes:
312 * 0xCD,<i> = int <i> (interrupt)
313 * 0xCA,0x02,0x00 = ret 2 (16-bit far return and pop 2 bytes / eflags)
315 ptr[i * 5 + 0] = 0xCD;
316 ptr[i * 5 + 1] = i;
317 ptr[i * 5 + 2] = 0xCA;
318 ptr[i * 5 + 3] = 0x02;
319 ptr[i * 5 + 4] = 0x00;
321 GlobalUnlock16( int16_sel );
324 /******************************************************************
325 * DOSMEM_InitDosMemory
327 BOOL DOSMEM_InitDosMemory(void)
329 static BOOL done;
330 static HANDLE hRunOnce;
331 DWORD old_prot;
333 if (done) return TRUE;
335 /* FIXME: this isn't 100% thread safe, as we won't catch accesses while initializing */
336 if (hRunOnce == 0)
338 HANDLE hEvent = CreateEventW( NULL, TRUE, FALSE, NULL );
339 if (InterlockedCompareExchangePointer( &hRunOnce, hEvent, 0 ) == 0)
341 BOOL ret;
342 DWORD reserve;
344 /* ok, we're the winning thread */
345 if (!(ret = VirtualProtect( DOSMEM_dosmem + DOSMEM_protect,
346 DOSMEM_SIZE - DOSMEM_protect,
347 PAGE_READWRITE, &old_prot )))
348 ERR("Cannot load access low 1Mb, DOS subsystem unavailable\n");
349 RemoveVectoredExceptionHandler( vectored_handler );
352 * Reserve either:
353 * - lowest 64k for NULL pointer catching (Win16)
354 * - lowest 1k for interrupt handlers and
355 * another 0.5k for BIOS, DOS and intra-application
356 * areas (DOS)
358 if (DOSMEM_dosmem != DOSMEM_sysmem)
359 reserve = 0x10000; /* 64k */
360 else
361 reserve = 0x600; /* 1.5k */
364 * Set DOS memory base and initialize conventional memory.
366 DOSMEM_FillBiosSegments();
367 DOSMEM_FillIsrTable();
369 /* align root block to paragraph */
370 DOSMEM_root_block = (MCB*)(DOSMEM_dosmem + reserve);
371 DOSMEM_root_block->type = MCB_TYPE_LAST;
372 DOSMEM_root_block->psp = MCB_PSP_FREE;
373 DOSMEM_root_block->size = (DOSMEM_dosmem + 0x9fffc - ((char*)DOSMEM_root_block)) >> 4;
375 TRACE("DOS conventional memory initialized, %d bytes free.\n",
376 DOSMEM_Available());
378 DOSMEM_InitSegments();
380 SetEvent( hRunOnce );
381 done = TRUE;
382 return ret;
384 /* someone beat us here... */
385 CloseHandle( hEvent );
388 /* and wait for the winner to have finished */
389 WaitForSingleObject( hRunOnce, INFINITE );
390 return TRUE;
393 /******************************************************************
394 * dosmem_handler
396 * Handler to catch access to our 1MB address space reserved for real memory
398 static LONG WINAPI dosmem_handler(EXCEPTION_POINTERS* except)
400 if (except->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
402 char *addr = (char *)except->ExceptionRecord->ExceptionInformation[1];
403 if (addr >= DOSMEM_dosmem + DOSMEM_protect && addr < DOSMEM_dosmem + DOSMEM_SIZE)
405 if (DOSMEM_InitDosMemory()) return EXCEPTION_CONTINUE_EXECUTION;
408 return EXCEPTION_CONTINUE_SEARCH;
411 /***********************************************************************
412 * DOSMEM_Init
414 * Create the dos memory segments, and store them into the KERNEL
415 * exported values.
417 BOOL DOSMEM_Init(void)
419 void *addr = (void *)1;
420 SIZE_T size = DOSMEM_SIZE - 1;
422 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 0, &size,
423 MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS ))
425 ERR( "Cannot allocate DOS memory\n" );
426 ExitProcess(1);
429 if (addr <= (void *)DOSMEM_64KB)
431 DOSMEM_dosmem = 0;
432 DOSMEM_protect = DOSMEM_64KB;
433 DOSMEM_sysmem = (char *)0xf0000; /* store sysmem in high addresses for now */
435 else
437 WARN( "First megabyte not available for DOS address space.\n" );
438 DOSMEM_dosmem = addr;
439 DOSMEM_protect = 0;
440 DOSMEM_sysmem = DOSMEM_dosmem;
443 vectored_handler = AddVectoredExceptionHandler(FALSE, dosmem_handler);
444 DOSMEM_0000H = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem,
445 DOSMEM_64KB, 0, LDT_FLAGS_DATA );
446 DOSMEM_BiosDataSeg = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem + 0x400,
447 0x100, 0, LDT_FLAGS_DATA );
448 DOSMEM_BiosSysSeg = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_dosmem + 0xf0000,
449 DOSMEM_64KB, 0, LDT_FLAGS_DATA );
451 return TRUE;
454 /***********************************************************************
455 * DOSMEM_MapLinearToDos
457 * Linear address to the DOS address space.
459 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
461 if (((char*)ptr >= DOSMEM_dosmem) &&
462 ((char*)ptr < DOSMEM_dosmem + DOSMEM_SIZE))
463 return (char *)ptr - DOSMEM_dosmem;
464 return (UINT)ptr;
468 /***********************************************************************
469 * DOSMEM_MapDosToLinear
471 * DOS linear address to the linear address space.
473 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
475 if (ptr < DOSMEM_SIZE) return DOSMEM_dosmem + ptr;
476 return (LPVOID)ptr;
480 /***********************************************************************
481 * DOSMEM_MapRealToLinear
483 * Real mode DOS address into a linear pointer
485 LPVOID DOSMEM_MapRealToLinear(DWORD x)
487 LPVOID lin;
489 lin = DOSMEM_dosmem + HIWORD(x) * 16 + LOWORD(x);
490 TRACE_(selector)("(0x%08lx) returns %p.\n", x, lin );
491 return lin;
494 /***********************************************************************
495 * DOSMEM_AllocBlock
497 * Carve a chunk of the DOS memory block (without selector).
499 LPVOID DOSMEM_AllocBlock(UINT size, UINT16* pseg)
501 MCB *curr;
502 MCB *next = NULL;
503 WORD psp;
505 DOSMEM_InitDosMemory();
507 curr = DOSMEM_root_block;
508 if (!(psp = DOSVM_psp)) psp = MCB_PSP_DOS;
510 if (pseg) *pseg = 0;
512 TRACE( "(%04xh)\n", size );
514 /* round up to paragraph */
515 size = (size + 15) >> 4;
517 #ifdef __DOSMEM_DEBUG__
518 DOSMEM_Available(); /* checks the whole MCB list */
519 #endif
521 /* loop over all MCB and search the next large enough MCB */
522 while (curr)
524 if (!MCB_VALID (curr))
526 ERR( "MCB List Corrupt\n" );
527 MCB_DUMP( curr );
528 return NULL;
530 if (curr->psp == MCB_PSP_FREE)
532 DOSMEM_Collapse( curr );
533 /* is it large enough (one paragraph for the MCB)? */
534 if (curr->size >= size)
536 if (curr->size > size)
538 /* split curr */
539 next = (MCB *) ((char*) curr + ((size+1) << 4));
540 next->psp = MCB_PSP_FREE;
541 next->size = curr->size - (size+1);
542 next->type = curr->type;
543 curr->type = MCB_TYPE_NORMAL;
544 curr->size = size;
546 /* curr is the found block */
547 curr->psp = psp;
548 if( pseg ) *pseg = (((char*)curr) + 16 - DOSMEM_dosmem) >> 4;
549 return (LPVOID) ((char*)curr + 16);
552 curr = MCB_NEXT(curr);
554 return NULL;
557 /***********************************************************************
558 * DOSMEM_FreeBlock
560 BOOL DOSMEM_FreeBlock(void* ptr)
562 MCB* mcb = (MCB*) ((char*)ptr - 16);
564 TRACE( "(%p)\n", ptr );
566 #ifdef __DOSMEM_DEBUG__
567 DOSMEM_Available();
568 #endif
570 if (!MCB_VALID (mcb))
572 ERR( "MCB invalid\n" );
573 MCB_DUMP( mcb );
574 return FALSE;
577 mcb->psp = MCB_PSP_FREE;
578 DOSMEM_Collapse( mcb );
579 return TRUE;
582 /***********************************************************************
583 * DOSMEM_ResizeBlock
585 * Resize DOS memory block in place. Returns block size or -1 on error.
587 * If exact is TRUE, returned value is either old or requested block
588 * size. If exact is FALSE, block is expanded even if there is not
589 * enough space for full requested block size.
591 * TODO: return also biggest block size
593 UINT DOSMEM_ResizeBlock(void *ptr, UINT size, BOOL exact)
595 MCB* mcb = (MCB*) ((char*)ptr - 16);
596 MCB* next;
598 TRACE( "(%p,%04xh,%s)\n", ptr, size, exact ? "TRUE" : "FALSE" );
600 /* round up to paragraph */
601 size = (size + 15) >> 4;
603 #ifdef __DOSMEM_DEBUG__
604 DOSMEM_Available();
605 #endif
607 if (!MCB_VALID (mcb))
609 ERR( "MCB invalid\n" );
610 MCB_DUMP( mcb );
611 return -1;
614 /* resize needed? */
615 if (mcb->size == size)
616 return size << 4;
618 /* collapse free blocks */
619 DOSMEM_Collapse( mcb );
621 /* shrink mcb ? */
622 if (mcb->size > size)
624 next = (MCB *) ((char*)mcb + ((size+1) << 4));
625 next->type = mcb->type;
626 next->psp = MCB_PSP_FREE;
627 next->size = mcb->size - (size+1);
628 mcb->type = MCB_TYPE_NORMAL;
629 mcb->size = size;
630 return size << 4;
633 if (!exact)
635 return mcb->size << 4;
638 return -1;
641 /***********************************************************************
642 * DOSMEM_Available
644 UINT DOSMEM_Available(void)
646 UINT available = 0;
647 UINT total = 0;
648 MCB *curr = DOSMEM_root_block;
649 /* loop over all MCB and search the largest free MCB */
650 while (curr)
652 #ifdef __DOSMEM_DEBUG__
653 MCB_DUMP( curr );
654 #endif
655 if (!MCB_VALID (curr))
657 ERR( "MCB List Corrupt\n" );
658 MCB_DUMP( curr );
659 return 0;
661 if (curr->psp == MCB_PSP_FREE &&
662 curr->size > available )
663 available = curr->size;
665 total += curr->size + 1;
666 curr = MCB_NEXT( curr );
668 TRACE( " %04xh of %04xh paragraphs available\n", available, total );
669 return available << 4;
672 /******************************************************************
673 * DOSMEM_MapDosLayout
675 * Initialize the first MB of memory to look like a real DOS setup
677 BOOL DOSMEM_MapDosLayout(void)
679 static BOOL already_mapped;
680 DWORD old_prot;
682 if (!already_mapped)
684 if (DOSMEM_dosmem || !VirtualProtect( NULL, DOSMEM_SIZE, PAGE_EXECUTE_READWRITE, &old_prot ))
686 ERR( "Need full access to the first megabyte for DOS mode\n" );
687 ExitProcess(1);
689 /* copy the BIOS and ISR area down */
690 memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
691 DOSMEM_sysmem = DOSMEM_dosmem;
692 SetSelectorBase( DOSMEM_0000H, 0 );
693 SetSelectorBase( DOSMEM_BiosDataSeg, 0x400 );
694 /* we may now need the actual interrupt stubs, and since we've just moved the
695 * interrupt vector table away, we can fill the area with stubs instead... */
696 DOSMEM_MakeIsrStubs();
697 already_mapped = TRUE;
699 return TRUE;