4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
16 #include "wine/winbase16.h"
20 #include "wine/unicode.h"
21 #include "selectors.h"
25 #include "debugtools.h"
27 DEFAULT_DEBUG_CHANNEL(heap);
29 /* address where we try to map the system heap */
30 #define SYSTEM_HEAP_BASE ((void*)0x65430000)
31 #define SYSTEM_HEAP_SIZE 0x100000 /* Default heap size = 1Mb */
34 #define HTABLE_SIZE 0x10000
35 #define HTABLE_PAGESIZE 0x1000
36 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
39 typedef struct _LOCAL32HEADER
41 WORD freeListFirst[HTABLE_NPAGES];
42 WORD freeListSize[HTABLE_NPAGES];
43 WORD freeListLast[HTABLE_NPAGES];
45 DWORD selectorTableOffset;
46 WORD selectorTableSize;
61 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
63 static HANDLE systemHeap; /* globally shared heap */
65 /***********************************************************************
66 * HEAP_CreateSystemHeap
68 * Create the system heap.
70 inline static HANDLE HEAP_CreateSystemHeap(void)
75 UNICODE_STRING event_name;
76 OBJECT_ATTRIBUTES event_attr;
78 if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
79 0, SYSTEM_HEAP_SIZE, "__SystemHeap" ))) return 0;
80 created = (GetLastError() != ERROR_ALREADY_EXISTS);
82 if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
84 /* pre-defined address not available */
85 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
89 /* create the system heap event */
90 RtlCreateUnicodeStringFromAsciiz( &event_name, "__SystemHeapEvent" );
91 event_attr.Length = sizeof(event_attr);
92 event_attr.RootDirectory = 0;
93 event_attr.ObjectName = &event_name;
94 event_attr.Attributes = 0;
95 event_attr.SecurityDescriptor = NULL;
96 event_attr.SecurityQualityOfService = NULL;
97 NtCreateEvent( &event, EVENT_ALL_ACCESS, &event_attr, TRUE, FALSE );
99 if (created) /* newly created heap */
101 systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
102 SYSTEM_HEAP_SIZE, NULL, NULL );
103 NtSetEvent( event, NULL );
107 /* wait for the heap to be initialized */
108 WaitForSingleObject( event, INFINITE );
115 /***********************************************************************
116 * HeapCreate (KERNEL32.@)
118 * Handle of heap: Success
121 HANDLE WINAPI HeapCreate(
122 DWORD flags, /* [in] Heap allocation flag */
123 DWORD initialSize, /* [in] Initial heap size */
124 DWORD maxSize /* [in] Maximum heap size */
128 if ( flags & HEAP_SHARED )
130 if (!systemHeap) HEAP_CreateSystemHeap();
131 else WARN( "Shared Heap requested, returning system heap.\n" );
136 ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
137 if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
142 /***********************************************************************
143 * HeapDestroy (KERNEL32.@)
148 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
150 if (heap == systemHeap)
152 WARN( "attempt to destroy system heap, returning TRUE!\n" );
155 if (!RtlDestroyHeap( heap )) return TRUE;
156 SetLastError( ERROR_INVALID_HANDLE );
161 /***********************************************************************
162 * HeapCompact (KERNEL32.@)
164 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
166 return RtlCompactHeap( heap, flags );
170 /***********************************************************************
171 * HeapLock (KERNEL32.@)
172 * Attempts to acquire the critical section object for a specified heap.
178 BOOL WINAPI HeapLock(
179 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
181 return RtlLockHeap( heap );
185 /***********************************************************************
186 * HeapUnlock (KERNEL32.@)
187 * Releases ownership of the critical section object.
193 BOOL WINAPI HeapUnlock(
194 HANDLE heap /* [in] Handle to the heap to unlock */
196 return RtlUnlockHeap( heap );
200 /***********************************************************************
201 * HeapValidate (KERNEL32.@)
202 * Validates a specified heap.
211 BOOL WINAPI HeapValidate(
212 HANDLE heap, /* [in] Handle to the heap */
213 DWORD flags, /* [in] Bit flags that control access during operation */
214 LPCVOID block /* [in] Optional pointer to memory block to validate */
216 return RtlValidateHeap( heap, flags, block );
220 /***********************************************************************
221 * HeapWalk (KERNEL32.@)
222 * Enumerates the memory blocks in a specified heap.
225 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
226 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
232 BOOL WINAPI HeapWalk(
233 HANDLE heap, /* [in] Handle to heap to enumerate */
234 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
236 NTSTATUS ret = RtlWalkHeap( heap, entry );
237 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
242 /***********************************************************************
243 * GetProcessHeap (KERNEL32.@)
245 HANDLE WINAPI GetProcessHeap(void)
247 HANDLE *pdb = (HANDLE *)NtCurrentTeb()->process;
248 return pdb[0x18 / sizeof(HANDLE)]; /* get dword at offset 0x18 in pdb */
252 /***********************************************************************
253 * GetProcessHeaps (KERNEL32.@)
255 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
257 return RtlGetProcessHeaps( count, heaps );
261 /***********************************************************************
262 * 32-bit local heap functions (Win95; undocumented)
265 /***********************************************************************
268 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
269 DWORD heapSize, DWORD flags )
271 DWORD totSize, segSize = 0;
273 LOCAL32HEADER *header;
276 WORD selectorEven, selectorOdd;
279 /* Determine new heap size */
283 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
289 if ( heapSize == -1L )
290 heapSize = 1024L*1024L; /* FIXME */
292 heapSize = (heapSize + 0xffff) & 0xffff0000;
293 segSize = (segSize + 0x0fff) & 0xfffff000;
294 totSize = segSize + HTABLE_SIZE + heapSize;
297 /* Allocate memory and initialize heap */
299 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
302 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
303 MEM_COMMIT, PAGE_READWRITE ) )
305 VirtualFree( base, 0, MEM_RELEASE );
309 if (!(heap = RtlCreateHeap( 0, base + segSize + HTABLE_SIZE, heapSize, 0x10000, NULL, NULL )))
311 VirtualFree( base, 0, MEM_RELEASE );
316 /* Set up header and handle table */
318 header = (LOCAL32HEADER *)(base + segSize);
320 header->limit = HTABLE_PAGESIZE-1;
322 header->magic = LOCAL32_MAGIC;
325 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
326 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
327 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
329 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
330 *(DWORD *)((LPBYTE)header + i) = i+4;
332 header->freeListFirst[1] = 0xffff;
335 /* Set up selector table */
337 nrBlocks = (totSize + 0x7fff) >> 15;
338 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
339 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
340 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
341 if ( !selectorTable || !selectorEven || !selectorOdd )
343 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
344 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
345 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
346 HeapDestroy( header->heap );
347 VirtualFree( base, 0, MEM_RELEASE );
351 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
352 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
353 header->selectorDelta = selectorEven - selectorOdd;
354 header->segment = segment? segment : selectorEven;
356 for (i = 0; i < nrBlocks; i++)
357 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
358 : selectorEven + ((i >> 1) << __AHSHIFT);
360 /* Move old segment */
364 /* FIXME: This is somewhat ugly and relies on implementation
365 details about 16-bit global memory handles ... */
367 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
368 memcpy( base, oldBase, segSize );
369 GLOBAL_MoveBlock( segment, base, totSize );
370 HeapFree( GetProcessHeap(), 0, oldBase );
373 return (HANDLE)header;
376 /***********************************************************************
377 * Local32_SearchHandle
379 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
383 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
384 handle < (LPDWORD)((LPBYTE)header + header->limit);
394 /***********************************************************************
397 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
398 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
405 case -2: /* 16:16 pointer, no handles */
406 *ptr = MapSL( addr );
407 *handle = (LPDWORD)*ptr;
410 case -1: /* 32-bit offset, no handles */
411 *ptr = header->base + addr;
412 *handle = (LPDWORD)*ptr;
416 if ( addr >= sizeof(LOCAL32HEADER)
417 && addr < header->limit && !(addr & 3)
418 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
420 *handle = (LPDWORD)((LPBYTE)header + addr);
421 *ptr = header->base + **handle;
425 case 1: /* 16:16 pointer */
426 *ptr = MapSL( addr );
427 *handle = Local32_SearchHandle( header, *ptr - header->base );
430 case 2: /* 32-bit offset */
431 *ptr = header->base + addr;
432 *handle = Local32_SearchHandle( header, *ptr - header->base );
437 /***********************************************************************
440 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
441 DWORD *addr, LPDWORD handle, LPBYTE ptr )
445 case -2: /* 16:16 pointer */
448 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
449 DWORD offset = (LPBYTE)ptr - header->base;
450 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
454 case -1: /* 32-bit offset */
456 *addr = ptr - header->base;
460 *addr = (LPBYTE)handle - (LPBYTE)header;
465 /***********************************************************************
468 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
470 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
475 /* Allocate memory */
476 ptr = HeapAlloc( header->heap,
477 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
481 /* Allocate handle if requested */
486 /* Find first page of handle table with free slots */
487 for (page = 0; page < HTABLE_NPAGES; page++)
488 if (header->freeListFirst[page] != 0)
490 if (page == HTABLE_NPAGES)
492 WARN("Out of handles!\n" );
493 HeapFree( header->heap, 0, ptr );
497 /* If virgin page, initialize it */
498 if (header->freeListFirst[page] == 0xffff)
500 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
501 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
503 WARN("Cannot grow handle table!\n" );
504 HeapFree( header->heap, 0, ptr );
508 header->limit += HTABLE_PAGESIZE;
510 header->freeListFirst[page] = 0;
511 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
512 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
514 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
515 *(DWORD *)((LPBYTE)header + i) = i+4;
517 if (page < HTABLE_NPAGES-1)
518 header->freeListFirst[page+1] = 0xffff;
521 /* Allocate handle slot from page */
522 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
523 if (--header->freeListSize[page] == 0)
524 header->freeListFirst[page] = header->freeListLast[page] = 0;
526 header->freeListFirst[page] = *handle;
528 /* Store 32-bit offset in handle slot */
529 *handle = ptr - header->base;
533 handle = (LPDWORD)ptr;
538 /* Convert handle to requested output type */
539 Local32_FromHandle( header, type, &addr, handle, ptr );
543 /***********************************************************************
546 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
547 DWORD size, DWORD flags )
549 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
554 return Local32Alloc16( heap, size, type, flags );
556 /* Retrieve handle and pointer */
557 Local32_ToHandle( header, type, addr, &handle, &ptr );
558 if (!handle) return FALSE;
560 /* Reallocate memory block */
561 ptr = HeapReAlloc( header->heap,
562 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
568 *handle = ptr - header->base;
570 handle = (LPDWORD)ptr;
572 /* Convert handle to requested output type */
573 Local32_FromHandle( header, type, &addr, handle, ptr );
577 /***********************************************************************
580 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
582 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
586 /* Retrieve handle and pointer */
587 Local32_ToHandle( header, type, addr, &handle, &ptr );
588 if (!handle) return FALSE;
590 /* Free handle if necessary */
593 int offset = (LPBYTE)handle - (LPBYTE)header;
594 int page = offset >> 12;
596 /* Return handle slot to page free list */
597 if (header->freeListSize[page]++ == 0)
598 header->freeListFirst[page] = header->freeListLast[page] = offset;
600 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
601 header->freeListLast[page] = offset;
605 /* Shrink handle table when possible */
606 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
608 if ( VirtualFree( (LPBYTE)header +
609 (header->limit & ~(HTABLE_PAGESIZE-1)),
610 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
613 header->limit -= HTABLE_PAGESIZE;
614 header->freeListFirst[page] = 0xffff;
620 return HeapFree( header->heap, 0, ptr );
623 /***********************************************************************
626 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
628 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
632 Local32_ToHandle( header, type1, addr, &handle, &ptr );
633 if (!handle) return 0;
635 Local32_FromHandle( header, type2, &addr, handle, ptr );
639 /***********************************************************************
642 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
644 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
648 Local32_ToHandle( header, type, addr, &handle, &ptr );
649 if (!handle) return 0;
651 return HeapSize( header->heap, 0, ptr );
654 /***********************************************************************
657 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
659 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
663 Local32_ToHandle( header, 0, addr, &handle, &ptr );
664 return handle != NULL;
667 /***********************************************************************
670 WORD WINAPI Local32GetSegment16( HANDLE heap )
672 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
673 return header->segment;
676 /***********************************************************************
679 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
681 WORD selector = GlobalHandleToSel16( handle );
682 DWORD base = GetSelectorBase( selector );
683 DWORD limit = GetSelectorLimit16( selector );
685 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
688 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
689 return (LOCAL32HEADER *)base;
694 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
695 return (LOCAL32HEADER *)base;
700 /***********************************************************************
701 * Local32Info (KERNEL.444)
702 * Local32Info (TOOLHELP.84)
704 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
706 PROCESS_HEAP_ENTRY entry;
709 LOCAL32HEADER *header = Local32_GetHeap( handle );
710 if ( !header ) return FALSE;
712 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
715 pLocal32Info->dwMemReserved = 0;
716 pLocal32Info->dwMemCommitted = 0;
717 pLocal32Info->dwTotalFree = 0;
718 pLocal32Info->dwLargestFreeBlock = 0;
720 while (HeapWalk( header->heap, &entry ))
722 if (entry.wFlags & PROCESS_HEAP_REGION)
724 pLocal32Info->dwMemReserved += entry.u.Region.dwCommittedSize
725 + entry.u.Region.dwUnCommittedSize;
726 pLocal32Info->dwMemCommitted = entry.u.Region.dwCommittedSize;
728 else if (!(entry.wFlags & PROCESS_HEAP_ENTRY_BUSY))
730 DWORD size = entry.cbData + entry.cbOverhead;
731 pLocal32Info->dwTotalFree += size;
732 if (size > pLocal32Info->dwLargestFreeBlock) pLocal32Info->dwLargestFreeBlock = size;
736 pLocal32Info->dwcFreeHandles = 0;
737 for ( i = 0; i < HTABLE_NPAGES; i++ )
739 if ( header->freeListFirst[i] == 0xffff ) break;
740 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
742 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
747 /***********************************************************************
748 * Local32First (KERNEL.445)
749 * Local32First (TOOLHELP.85)
751 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
753 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
757 /***********************************************************************
758 * Local32Next (KERNEL.446)
759 * Local32Next (TOOLHELP.86)
761 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
763 FIXME("(%p): stub!\n", pLocal32Entry );