2 * 16-bit local heap functions
4 * Copyright 1995 Alexandre Julliard
5 * Copyright 1996 Huw Davies
6 * Copyright 1998 Ulrich Weigand
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 * All local heap functions need the current DS as first parameter
26 * when called from the emulation library, so they take one more
27 * parameter than usual.
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
36 #include "wine/winbase16.h"
40 #include "kernel_private.h"
41 #include "kernel16_private.h"
42 #include "wine/debug.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(local);
49 WORD prev; /* Previous arena | arena type */
50 WORD next; /* Next arena */
51 /* Start of the memory block or free-list info */
52 WORD size; /* Size of the free block */
53 WORD free_prev; /* Previous free block */
54 WORD free_next; /* Next free block */
57 #define ARENA_HEADER_SIZE 4
58 #define ARENA_HEADER( handle) ((handle) - ARENA_HEADER_SIZE)
60 /* Arena types (stored in 'prev' field of the arena) */
61 #define LOCAL_ARENA_FREE 0
62 #define LOCAL_ARENA_FIXED 1
64 /* LocalNotify() msgs */
70 /* Layout of a handle entry table
72 * WORD count of entries
73 * LOCALHANDLEENTRY[count] entries
74 * WORD near ptr to next table
78 WORD addr; /* Address of the MOVEABLE block */
79 BYTE flags; /* Flags for this block */
80 BYTE lock; /* Lock count */
84 * We make addr = 4n + 2 and set *((WORD *)addr - 1) = &addr like Windows does
85 * in case something actually relies on this.
86 * Note that if the architecture does not allow unaligned accesses, we make
87 * addr = 4n + 4 to avoid returning unaligned pointers from LocalAlloc etc.
89 * An unused handle has lock = flags = 0xff. In windows addr is that of next
90 * free handle, at the moment in wine we set it to 0.
92 * A discarded block's handle has lock = addr = 0 and flags = 0x40
93 * (LMEM_DISCARDED >> 8)
96 #ifdef ALLOW_UNALIGNED_ACCESS
97 # define MOVEABLE_PREFIX sizeof(HLOCAL16)
99 # define MOVEABLE_PREFIX sizeof(int)
103 #include "pshpack1.h"
107 WORD check; /* 00 Heap checking flag */
108 WORD freeze; /* 02 Heap frozen flag */
109 WORD items; /* 04 Count of items on the heap */
110 WORD first; /* 06 First item of the heap */
111 WORD pad1; /* 08 Always 0 */
112 WORD last; /* 0a Last item of the heap */
113 WORD pad2; /* 0c Always 0 */
114 BYTE ncompact; /* 0e Compactions counter */
115 BYTE dislevel; /* 0f Discard level */
116 DWORD distotal; /* 10 Total bytes discarded */
117 WORD htable; /* 14 Pointer to handle table */
118 WORD hfree; /* 16 Pointer to free handle table */
119 WORD hdelta; /* 18 Delta to expand the handle table */
120 WORD expand; /* 1a Pointer to expand function (unused) */
121 WORD pstat; /* 1c Pointer to status structure (unused) */
122 FARPROC16 notify; /* 1e Pointer to LocalNotify() function */
123 WORD lock; /* 22 Lock count for the heap */
124 WORD extra; /* 24 Extra bytes to allocate when expanding */
125 WORD minsize; /* 26 Minimum size of the heap */
126 WORD magic; /* 28 Magic number */
131 #define LOCAL_HEAP_MAGIC 0x484c /* 'LH' */
133 /* All local heap allocations are aligned on 4-byte boundaries */
134 #define LALIGN(word) (((word) + 3) & ~3)
136 #define ARENA_PTR(ptr,arena) ((LOCALARENA *)((char *)(ptr)+(arena)))
137 #define ARENA_PREV(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & ~3)
138 #define ARENA_NEXT(ptr,arena) (ARENA_PTR((ptr),(arena))->next)
139 #define ARENA_FLAGS(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & 3)
141 /* determine whether the handle belongs to a fixed or a moveable block */
142 #define HANDLE_FIXED(handle) (((handle) & 3) == 0)
143 #define HANDLE_MOVEABLE(handle) (((handle) & 3) == 2)
146 /* 32-bit heap definitions */
148 #define HTABLE_SIZE 0x10000
149 #define HTABLE_PAGESIZE 0x1000
150 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
152 #include "pshpack1.h"
153 typedef struct _LOCAL32HEADER
155 WORD freeListFirst[HTABLE_NPAGES];
156 WORD freeListSize[HTABLE_NPAGES];
157 WORD freeListLast[HTABLE_NPAGES];
159 DWORD selectorTableOffset;
160 WORD selectorTableSize;
175 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
178 static inline BOOL16 call_notify_func( FARPROC16 proc, WORD msg, HLOCAL16 handle, WORD arg )
183 if (!proc) return FALSE;
187 WOWCallback16Ex( (DWORD)proc, WCB16_PASCAL, sizeof(args), args, &ret );
192 /***********************************************************************
195 * Return a pointer to the local heap, making sure it exists.
197 static LOCALHEAPINFO *LOCAL_GetHeap( HANDLE16 ds )
199 LOCALHEAPINFO *pInfo;
200 INSTANCEDATA *ptr = MapSL( MAKESEGPTR( ds, 0 ));
201 TRACE("Heap at %p, %04x\n", ptr, (ptr != NULL ? ptr->heap : 0xFFFF));
202 if (!ptr || !ptr->heap) return NULL;
203 if (IsBadReadPtr16( (SEGPTR)MAKELONG(ptr->heap,ds), sizeof(LOCALHEAPINFO)))
205 WARN("Bad pointer\n");
208 pInfo = (LOCALHEAPINFO*)((char*)ptr + ptr->heap);
209 if (pInfo->magic != LOCAL_HEAP_MAGIC)
218 /***********************************************************************
219 * LOCAL_MakeBlockFree
221 * Make a block free, inserting it in the free-list.
222 * 'block' is the handle of the block arena; 'baseptr' points to
223 * the beginning of the data segment containing the heap.
225 static void LOCAL_MakeBlockFree( char *baseptr, WORD block )
227 LOCALARENA *pArena, *pNext;
230 /* Mark the block as free */
232 pArena = ARENA_PTR( baseptr, block );
233 pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FREE;
234 pArena->size = pArena->next - block;
236 /* Find the next free block (last block is always free) */
241 pNext = ARENA_PTR( baseptr, next );
242 if ((pNext->prev & 3) == LOCAL_ARENA_FREE) break;
246 TRACE("%04x, next %04x\n", block, next );
247 /* Insert the free block in the free-list */
249 pArena->free_prev = pNext->free_prev;
250 pArena->free_next = next;
251 ARENA_PTR(baseptr,pNext->free_prev)->free_next = block;
252 pNext->free_prev = block;
256 /***********************************************************************
257 * LOCAL_RemoveFreeBlock
259 * Remove a block from the free-list.
260 * 'block' is the handle of the block arena; 'baseptr' points to
261 * the beginning of the data segment containing the heap.
263 static void LOCAL_RemoveFreeBlock( char *baseptr, WORD block )
265 /* Mark the block as fixed */
267 LOCALARENA *pArena = ARENA_PTR( baseptr, block );
268 pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FIXED;
270 /* Remove it from the list */
272 ARENA_PTR(baseptr,pArena->free_prev)->free_next = pArena->free_next;
273 ARENA_PTR(baseptr,pArena->free_next)->free_prev = pArena->free_prev;
277 /***********************************************************************
280 * Insert a new block in the heap.
281 * 'new' is the handle of the new block arena; 'baseptr' points to
282 * the beginning of the data segment containing the heap; 'prev' is
283 * the block before the new one.
285 static void LOCAL_AddBlock( char *baseptr, WORD prev, WORD new )
287 LOCALARENA *pPrev = ARENA_PTR( baseptr, prev );
288 LOCALARENA *pNew = ARENA_PTR( baseptr, new );
290 pNew->prev = (prev & ~3) | LOCAL_ARENA_FIXED;
291 pNew->next = pPrev->next;
292 ARENA_PTR(baseptr,pPrev->next)->prev &= 3;
293 ARENA_PTR(baseptr,pPrev->next)->prev |= new;
298 /***********************************************************************
301 * Remove a block from the heap.
302 * 'block' is the handle of the block arena; 'baseptr' points to
303 * the beginning of the data segment containing the heap.
305 static void LOCAL_RemoveBlock( char *baseptr, WORD block )
307 LOCALARENA *pArena, *pTmp;
309 /* Remove the block from the free-list */
312 pArena = ARENA_PTR( baseptr, block );
313 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
314 LOCAL_RemoveFreeBlock( baseptr, block );
316 /* If the previous block is free, expand its size */
318 pTmp = ARENA_PTR( baseptr, pArena->prev & ~3 );
319 if ((pTmp->prev & 3) == LOCAL_ARENA_FREE)
320 pTmp->size += pArena->next - block;
322 /* Remove the block from the linked list */
324 pTmp->next = pArena->next;
325 pTmp = ARENA_PTR( baseptr, pArena->next );
326 pTmp->prev = (pTmp->prev & 3) | (pArena->prev & ~3);
330 /***********************************************************************
333 static void LOCAL_PrintHeap( HANDLE16 ds )
336 LOCALHEAPINFO *pInfo;
339 /* FIXME - the test should be done when calling the function!
340 plus is not clear that we should print this info
341 only when TRACE_ON is on! */
342 if(!TRACE_ON(local)) return;
344 ptr = MapSL( MAKESEGPTR( ds, 0 ));
345 pInfo = LOCAL_GetHeap( ds );
349 ERR( "Local Heap corrupted! ds=%04x\n", ds );
352 TRACE( "Local Heap ds=%04x first=%04x last=%04x items=%d\n",
353 ds, pInfo->first, pInfo->last, pInfo->items );
355 arena = pInfo->first;
358 LOCALARENA *pArena = ARENA_PTR(ptr,arena);
359 TRACE( " %04x: prev=%04x next=%04x type=%d\n", arena,
360 pArena->prev & ~3, pArena->next, pArena->prev & 3 );
361 if (arena == pInfo->first)
363 TRACE( " size=%d free_prev=%04x free_next=%04x\n",
364 pArena->size, pArena->free_prev, pArena->free_next );
366 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
368 TRACE( " size=%d free_prev=%04x free_next=%04x\n",
369 pArena->size, pArena->free_prev, pArena->free_next );
370 if (pArena->next == arena) break; /* last one */
371 if (ARENA_PTR(ptr,pArena->free_next)->free_prev != arena)
373 TRACE( "*** arena->free_next->free_prev != arena\n" );
377 if (pArena->next == arena)
379 TRACE( "*** last block is not marked free\n" );
382 if ((ARENA_PTR(ptr,pArena->next)->prev & ~3) != arena)
384 TRACE( "*** arena->next->prev != arena (%04x, %04x)\n",
385 pArena->next, ARENA_PTR(ptr,pArena->next)->prev);
388 arena = pArena->next;
393 /***********************************************************************
394 * LocalInit (KERNEL.4)
396 BOOL16 WINAPI LocalInit16( HANDLE16 selector, WORD start, WORD end )
399 WORD heapInfoArena, freeArena, lastArena;
400 LOCALHEAPINFO *pHeapInfo;
401 LOCALARENA *pArena, *pFirstArena, *pLastArena;
404 /* The initial layout of the heap is: */
405 /* - first arena (FIXED) */
406 /* - heap info structure (FIXED) */
407 /* - large free block (FREE) */
408 /* - last arena (FREE) */
410 TRACE("%04x %04x-%04x\n", selector, start, end);
411 if (!selector) selector = CURRENT_DS;
415 /* If TRACE_ON(local) is set, the global heap blocks are */
416 /* cleared before use, so we can test for double initialization. */
417 if (LOCAL_GetHeap(selector))
419 ERR("Heap %04x initialized twice.\n", selector);
420 LOCAL_PrintHeap(selector);
426 /* start == 0 means: put the local heap at the end of the segment */
428 DWORD size = GlobalSize16( GlobalHandle16( selector ) );
429 start = (WORD)(size > 0xffff ? 0xffff : size) - 1;
430 if ( end > 0xfffe ) end = 0xfffe;
434 ptr = MapSL( MAKESEGPTR( selector, 0 ) );
436 start = LALIGN( max( start, sizeof(INSTANCEDATA) ) );
437 heapInfoArena = LALIGN(start + sizeof(LOCALARENA) );
438 freeArena = LALIGN( heapInfoArena + ARENA_HEADER_SIZE
439 + sizeof(LOCALHEAPINFO) );
440 lastArena = (end - sizeof(LOCALARENA)) & ~3;
442 /* Make sure there's enough space. */
444 if (freeArena + sizeof(LOCALARENA) >= lastArena) goto done;
446 /* Initialise the first arena */
448 pFirstArena = ARENA_PTR( ptr, start );
449 pFirstArena->prev = start | LOCAL_ARENA_FIXED;
450 pFirstArena->next = heapInfoArena;
451 pFirstArena->size = LALIGN(sizeof(LOCALARENA));
452 pFirstArena->free_prev = start; /* this one */
453 pFirstArena->free_next = freeArena;
455 /* Initialise the arena of the heap info structure */
457 pArena = ARENA_PTR( ptr, heapInfoArena );
458 pArena->prev = start | LOCAL_ARENA_FIXED;
459 pArena->next = freeArena;
461 /* Initialise the heap info structure */
463 pHeapInfo = (LOCALHEAPINFO *) (ptr + heapInfoArena + ARENA_HEADER_SIZE );
464 memset( pHeapInfo, 0, sizeof(LOCALHEAPINFO) );
465 pHeapInfo->items = 4;
466 pHeapInfo->first = start;
467 pHeapInfo->last = lastArena;
468 pHeapInfo->htable = 0;
469 pHeapInfo->hdelta = 0x20;
470 pHeapInfo->extra = 0x200;
471 pHeapInfo->minsize = lastArena - freeArena;
472 pHeapInfo->magic = LOCAL_HEAP_MAGIC;
474 /* Initialise the large free block */
476 pArena = ARENA_PTR( ptr, freeArena );
477 pArena->prev = heapInfoArena | LOCAL_ARENA_FREE;
478 pArena->next = lastArena;
479 pArena->size = lastArena - freeArena;
480 pArena->free_prev = start;
481 pArena->free_next = lastArena;
483 /* Initialise the last block */
485 pLastArena = ARENA_PTR( ptr, lastArena );
486 pLastArena->prev = freeArena | LOCAL_ARENA_FREE;
487 pLastArena->next = lastArena; /* this one */
488 pLastArena->size = LALIGN(sizeof(LOCALARENA));
489 pLastArena->free_prev = freeArena;
490 pLastArena->free_next = lastArena; /* this one */
492 /* Store the local heap address in the instance data */
494 ((INSTANCEDATA *)ptr)->heap = heapInfoArena + ARENA_HEADER_SIZE;
495 LOCAL_PrintHeap( selector );
499 CURRENT_STACK16->ecx = ret; /* must be returned in cx too */
504 /***********************************************************************
507 static BOOL16 LOCAL_GrowHeap( HANDLE16 ds )
512 LOCALHEAPINFO *pHeapInfo;
513 WORD freeArena, lastArena;
514 LOCALARENA *pArena, *pLastArena;
517 hseg = GlobalHandle16( ds );
518 /* maybe mem allocated by Virtual*() ? */
519 if (!hseg) return FALSE;
521 oldsize = GlobalSize16( hseg );
522 /* if nothing can be gained, return */
523 if (oldsize > 0xfff0) return FALSE;
524 hseg = GlobalReAlloc16( hseg, 0x10000, GMEM_FIXED );
525 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
526 pHeapInfo = LOCAL_GetHeap( ds );
527 if (pHeapInfo == NULL) {
528 ERR("Heap not found\n" );
531 end = GlobalSize16( hseg );
532 lastArena = (end - sizeof(LOCALARENA)) & ~3;
534 /* Update the HeapInfo */
536 freeArena = pHeapInfo->last;
537 pHeapInfo->last = lastArena;
538 pHeapInfo->minsize += end - oldsize;
540 /* grow the old last block */
541 pArena = ARENA_PTR( ptr, freeArena );
542 pArena->size = lastArena - freeArena;
543 pArena->next = lastArena;
544 pArena->free_next = lastArena;
546 /* Initialise the new last block */
548 pLastArena = ARENA_PTR( ptr, lastArena );
549 pLastArena->prev = freeArena | LOCAL_ARENA_FREE;
550 pLastArena->next = lastArena; /* this one */
551 pLastArena->size = LALIGN(sizeof(LOCALARENA));
552 pLastArena->free_prev = freeArena;
553 pLastArena->free_next = lastArena; /* this one */
555 /* If block before freeArena is also free then merge them */
556 if((ARENA_PTR(ptr, (pArena->prev & ~3))->prev & 3) == LOCAL_ARENA_FREE)
558 LOCAL_RemoveBlock(ptr, freeArena);
562 TRACE("Heap expanded\n" );
563 LOCAL_PrintHeap( ds );
568 /***********************************************************************
571 static HLOCAL16 LOCAL_FreeArena( WORD ds, WORD arena )
573 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
574 LOCALHEAPINFO *pInfo;
575 LOCALARENA *pArena, *pPrev;
577 TRACE("%04x ds=%04x\n", arena, ds );
578 if (!(pInfo = LOCAL_GetHeap( ds ))) return arena;
580 pArena = ARENA_PTR( ptr, arena );
581 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
583 /* shouldn't happen */
584 ERR("Trying to free block %04x twice!\n",
586 LOCAL_PrintHeap( ds );
590 /* Check if we can merge with the previous block */
592 pPrev = ARENA_PTR( ptr, pArena->prev & ~3 );
593 if ((pPrev->prev & 3) == LOCAL_ARENA_FREE)
595 arena = pArena->prev & ~3;
597 LOCAL_RemoveBlock( ptr, pPrev->next );
600 else /* Make a new free block */
602 LOCAL_MakeBlockFree( ptr, arena );
605 /* Check if we can merge with the next block */
607 if ((pArena->next == pArena->free_next) &&
608 (pArena->next != pInfo->last))
610 LOCAL_RemoveBlock( ptr, pArena->next );
617 /***********************************************************************
620 * Shrink an arena by creating a free block at its end if possible.
621 * 'size' includes the arena header, and must be aligned.
623 static void LOCAL_ShrinkArena( WORD ds, WORD arena, WORD size )
625 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
626 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
628 if (arena + size + LALIGN(sizeof(LOCALARENA)) < pArena->next)
630 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
632 LOCAL_AddBlock( ptr, arena, arena + size );
634 LOCAL_FreeArena( ds, arena + size );
639 /***********************************************************************
640 * LOCAL_GrowArenaDownward
642 * Grow an arena downward by using the previous arena (must be free).
644 static void LOCAL_GrowArenaDownward( WORD ds, WORD arena, WORD newsize )
646 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
647 LOCALHEAPINFO *pInfo;
648 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
649 WORD prevArena = pArena->prev & ~3;
650 LOCALARENA *pPrevArena = ARENA_PTR( ptr, prevArena );
654 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
655 offset = pPrevArena->size;
656 size = pArena->next - arena - ARENA_HEADER_SIZE;
657 LOCAL_RemoveFreeBlock( ptr, prevArena );
658 LOCAL_RemoveBlock( ptr, arena );
660 p = (char *)pPrevArena + ARENA_HEADER_SIZE;
661 while (offset < size)
663 memcpy( p, p + offset, offset );
667 if (size) memcpy( p, p + offset, size );
668 LOCAL_ShrinkArena( ds, prevArena, newsize );
673 /***********************************************************************
674 * LOCAL_GrowArenaUpward
676 * Grow an arena upward by using the next arena (must be free and big
677 * enough). Newsize includes the arena header and must be aligned.
679 static void LOCAL_GrowArenaUpward( WORD ds, WORD arena, WORD newsize )
681 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
682 LOCALHEAPINFO *pInfo;
683 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
684 WORD nextArena = pArena->next;
686 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
687 LOCAL_RemoveBlock( ptr, nextArena );
689 LOCAL_ShrinkArena( ds, arena, newsize );
693 /***********************************************************************
696 static WORD LOCAL_GetFreeSpace(WORD ds, WORD countdiscard)
698 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
699 LOCALHEAPINFO *pInfo;
704 if (!(pInfo = LOCAL_GetHeap( ds )))
706 ERR("Local heap not found\n" );
710 arena = pInfo->first;
711 pArena = ARENA_PTR( ptr, arena );
712 while (arena != pArena->free_next)
714 arena = pArena->free_next;
715 pArena = ARENA_PTR( ptr, arena );
716 if (pArena->size >= freespace) freespace = pArena->size;
718 /* FIXME doesn't yet calculate space that would become free if everything
719 were discarded when countdiscard == 1 */
720 if (freespace < ARENA_HEADER_SIZE) freespace = 0;
721 else freespace -= ARENA_HEADER_SIZE;
726 /***********************************************************************
729 static UINT16 LOCAL_Compact( HANDLE16 ds, UINT16 minfree, UINT16 flags )
731 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
732 LOCALHEAPINFO *pInfo;
733 LOCALARENA *pArena, *pMoveArena, *pFinalArena;
734 WORD arena, movearena, finalarena, table;
735 WORD count, movesize, size;
737 LOCALHANDLEENTRY *pEntry;
739 if (!(pInfo = LOCAL_GetHeap( ds )))
741 ERR("Local heap not found\n" );
745 TRACE("ds = %04x, minfree = %04x, flags = %04x\n",
747 freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1);
748 if(freespace >= minfree || (flags & LMEM_NOCOMPACT))
750 TRACE("Returning %04x.\n", freespace);
753 TRACE("Compacting heap %04x.\n", ds);
754 table = pInfo->htable;
757 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
758 for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++)
760 if((pEntry->lock == 0) && (pEntry->flags != (LMEM_DISCARDED >> 8)))
762 /* OK we can move this one if we want */
763 TRACE("handle %04x (block %04x) can be moved.\n",
764 (WORD)((char *)pEntry - ptr), pEntry->addr);
765 movearena = ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX);
766 pMoveArena = ARENA_PTR(ptr, movearena);
767 movesize = pMoveArena->next - movearena;
768 arena = pInfo->first;
769 pArena = ARENA_PTR(ptr, arena);
772 /* Try to find the smallest arena that will do, */
773 /* which is below us in memory */
776 arena = pArena->free_next;
777 pArena = ARENA_PTR(ptr, arena);
778 if(arena >= movearena)
780 if(arena == pArena->free_next)
782 if((pArena->size >= movesize) && (pArena->size < size))
788 if (finalarena) /* Actually got somewhere to move */
790 TRACE("Moving it to %04x.\n", finalarena);
791 pFinalArena = ARENA_PTR(ptr, finalarena);
792 size = pFinalArena->size;
793 LOCAL_RemoveFreeBlock(ptr, finalarena);
794 LOCAL_ShrinkArena( ds, finalarena, movesize );
795 /* Copy the arena to it's new location */
796 memcpy((char *)pFinalArena + ARENA_HEADER_SIZE,
797 (char *)pMoveArena + ARENA_HEADER_SIZE,
798 movesize - ARENA_HEADER_SIZE );
799 /* Free the old location */
800 LOCAL_FreeArena(ds, movearena);
801 call_notify_func(pInfo->notify, LN_MOVE,
802 (WORD)((char *)pEntry - ptr), pEntry->addr);
803 /* Update handle table entry */
804 pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX;
806 else if((ARENA_PTR(ptr, pMoveArena->prev & ~3)->prev & 3)
809 /* Previous arena is free (but < movesize) */
810 /* so we can 'slide' movearena down into it */
811 finalarena = pMoveArena->prev & ~3;
812 LOCAL_GrowArenaDownward( ds, movearena, movesize );
813 /* Update handle table entry */
814 pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX;
818 table = *(WORD *)pEntry;
820 freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1);
821 if(freespace >= minfree || (flags & LMEM_NODISCARD))
823 TRACE("Returning %04x.\n", freespace);
827 table = pInfo->htable;
830 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
831 for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++)
833 if(pEntry->addr && pEntry->lock == 0 &&
834 (pEntry->flags & (LMEM_DISCARDABLE >> 8)))
836 TRACE("Discarding handle %04x (block %04x).\n",
837 (char *)pEntry - ptr, pEntry->addr);
838 LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX));
839 call_notify_func(pInfo->notify, LN_DISCARD, (char *)pEntry - ptr, pEntry->flags);
841 pEntry->flags = (LMEM_DISCARDED >> 8);
844 table = *(WORD *)pEntry;
846 return LOCAL_Compact(ds, 0xffff, LMEM_NODISCARD);
850 /***********************************************************************
851 * LOCAL_FindFreeBlock
853 static HLOCAL16 LOCAL_FindFreeBlock( HANDLE16 ds, WORD size )
855 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
856 LOCALHEAPINFO *pInfo;
860 if (!(pInfo = LOCAL_GetHeap( ds )))
862 ERR("Local heap not found\n" );
867 arena = pInfo->first;
868 pArena = ARENA_PTR( ptr, arena );
870 arena = pArena->free_next;
871 pArena = ARENA_PTR( ptr, arena );
872 if (arena == pArena->free_next) break;
873 if (pArena->size >= size) return arena;
875 TRACE("not enough space\n" );
881 /***********************************************************************
884 static const char *get_heap_name( WORD ds )
886 HINSTANCE16 inst = LoadLibrary16( "GDI" );
887 if (ds == GlobalHandleToSel16( inst ))
889 FreeLibrary16( inst );
892 FreeLibrary16( inst );
893 inst = LoadLibrary16( "USER" );
894 if (ds == GlobalHandleToSel16( inst ))
896 FreeLibrary16( inst );
899 FreeLibrary16( inst );
903 /***********************************************************************
905 * The segment may get moved around in this function, so all callers
906 * should reset their pointer variables.
908 static HLOCAL16 LOCAL_GetBlock( HANDLE16 ds, WORD size, WORD flags )
910 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
911 LOCALHEAPINFO *pInfo;
915 if (!(pInfo = LOCAL_GetHeap( ds )))
917 ERR("Local heap not found\n");
922 size += ARENA_HEADER_SIZE;
923 size = LALIGN( max( size, sizeof(LOCALARENA) ) );
928 /* Find a suitable free block */
929 arena = LOCAL_FindFreeBlock( ds, size );
931 /* no space: try to make some */
932 LOCAL_Compact( ds, size, flags );
933 arena = LOCAL_FindFreeBlock( ds, size );
936 /* still no space: try to grow the segment */
937 if (!(LOCAL_GrowHeap( ds )))
940 /* FIXME: doesn't work correctly yet */
941 if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds - 20, size)) /* FIXME: "size" correct ? (should indicate bytes needed) */
944 ERR( "not enough space in %s heap %04x for %d bytes\n",
945 get_heap_name(ds), ds, size );
948 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
949 pInfo = LOCAL_GetHeap( ds );
950 arena = LOCAL_FindFreeBlock( ds, size );
953 ERR( "not enough space in %s heap %04x for %d bytes\n",
954 get_heap_name(ds), ds, size );
956 /* FIXME: "size" correct ? (should indicate bytes needed) */
957 if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds, size)) goto notify_done;
962 /* Make a block out of the free arena */
963 pArena = ARENA_PTR( ptr, arena );
964 TRACE("size = %04x, arena %04x size %04x\n", size, arena, pArena->size );
965 LOCAL_RemoveFreeBlock( ptr, arena );
966 LOCAL_ShrinkArena( ds, arena, size );
968 if (flags & LMEM_ZEROINIT)
969 memset((char *)pArena + ARENA_HEADER_SIZE, 0, size-ARENA_HEADER_SIZE);
970 return arena + ARENA_HEADER_SIZE;
974 /***********************************************************************
977 static BOOL16 LOCAL_NewHTable( HANDLE16 ds )
979 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
980 LOCALHEAPINFO *pInfo;
981 LOCALHANDLEENTRY *pEntry;
986 if (!(pInfo = LOCAL_GetHeap( ds )))
988 ERR("Local heap not found\n");
993 if (!(handle = LOCAL_GetBlock( ds, pInfo->hdelta * sizeof(LOCALHANDLEENTRY)
994 + 2 * sizeof(WORD), LMEM_FIXED )))
996 if (!(ptr = MapSL( MAKESEGPTR( ds, 0 ) )))
997 ERR("ptr == NULL after GetBlock.\n");
998 if (!(pInfo = LOCAL_GetHeap( ds )))
999 ERR("pInfo == NULL after GetBlock.\n");
1001 /* Fill the entry table */
1003 *(WORD *)(ptr + handle) = pInfo->hdelta;
1004 pEntry = (LOCALHANDLEENTRY *)(ptr + handle + sizeof(WORD));
1005 for (i = pInfo->hdelta; i > 0; i--, pEntry++) {
1006 pEntry->lock = pEntry->flags = 0xff;
1009 *(WORD *)pEntry = pInfo->htable;
1010 pInfo->htable = handle;
1015 /***********************************************************************
1016 * LOCAL_GetNewHandleEntry
1018 static HLOCAL16 LOCAL_GetNewHandleEntry( HANDLE16 ds )
1020 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1021 LOCALHEAPINFO *pInfo;
1022 LOCALHANDLEENTRY *pEntry = NULL;
1025 if (!(pInfo = LOCAL_GetHeap( ds )))
1027 ERR("Local heap not found\n");
1028 LOCAL_PrintHeap(ds);
1032 /* Find a free slot in existing tables */
1034 table = pInfo->htable;
1037 WORD count = *(WORD *)(ptr + table);
1038 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
1039 for (; count > 0; count--, pEntry++)
1040 if (pEntry->lock == 0xff) break;
1042 table = *(WORD *)pEntry;
1045 if (!table) /* We need to create a new table */
1047 if (!LOCAL_NewHTable( ds )) return 0;
1048 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1049 pInfo = LOCAL_GetHeap( ds );
1050 pEntry = (LOCALHANDLEENTRY *)(ptr + pInfo->htable + sizeof(WORD));
1053 /* Now allocate this entry */
1057 TRACE("(%04x): %04x\n", ds, ((char *)pEntry - ptr) );
1058 return (HLOCAL16)((char *)pEntry - ptr);
1062 /***********************************************************************
1063 * LOCAL_FreeHandleEntry
1065 * Free a handle table entry.
1067 static void LOCAL_FreeHandleEntry( HANDLE16 ds, HLOCAL16 handle )
1069 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1070 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1071 LOCALHEAPINFO *pInfo;
1073 WORD table, count, i;
1075 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
1077 /* Find the table where this handle comes from */
1079 pTable = &pInfo->htable;
1082 WORD size = (*(WORD *)(ptr + *pTable)) * sizeof(LOCALHANDLEENTRY);
1083 if ((handle >= *pTable + sizeof(WORD)) &&
1084 (handle < *pTable + sizeof(WORD) + size)) break; /* Found it */
1085 pTable = (WORD *)(ptr + *pTable + sizeof(WORD) + size);
1089 ERR("Invalid entry %04x\n", handle);
1090 LOCAL_PrintHeap( ds );
1094 /* Make the entry free */
1096 pEntry->addr = 0; /* just in case */
1097 pEntry->lock = 0xff;
1098 pEntry->flags = 0xff;
1099 /* Now check if all entries in this table are free */
1102 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
1103 count = *(WORD *)(ptr + table);
1104 for (i = count; i > 0; i--, pEntry++) if (pEntry->lock != 0xff) return;
1106 /* Remove the table from the linked list and free it */
1108 TRACE("(%04x): freeing table %04x\n", ds, table);
1109 *pTable = *(WORD *)pEntry;
1110 LOCAL_FreeArena( ds, ARENA_HEADER( table ) );
1114 /***********************************************************************
1115 * LocalFree (KERNEL.7)
1117 HLOCAL16 WINAPI LocalFree16( HLOCAL16 handle )
1119 HANDLE16 ds = CURRENT_DS;
1120 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1122 TRACE("%04x ds=%04x\n", handle, ds );
1124 if (!handle) { WARN("Handle is 0.\n" ); return 0; }
1125 if (HANDLE_FIXED( handle ))
1127 if (!LOCAL_FreeArena( ds, ARENA_HEADER( handle ) )) return 0; /* OK */
1128 else return handle; /* couldn't free it */
1132 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1133 if (pEntry->flags != (LMEM_DISCARDED >> 8))
1135 TRACE("real block at %04x\n", pEntry->addr );
1136 if (LOCAL_FreeArena( ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX) ))
1137 return handle; /* couldn't free it */
1139 LOCAL_FreeHandleEntry( ds, handle );
1145 /***********************************************************************
1146 * LocalAlloc (KERNEL.5)
1148 HLOCAL16 WINAPI LocalAlloc16( UINT16 flags, WORD size )
1150 HANDLE16 ds = CURRENT_DS;
1151 HLOCAL16 handle = 0;
1154 TRACE("%04x %d ds=%04x\n", flags, size, ds );
1156 if(size > 0 && size <= 4) size = 5;
1157 if (flags & LMEM_MOVEABLE)
1159 LOCALHANDLEENTRY *plhe;
1164 if (!(hmem = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags )))
1167 else /* We just need to allocate a discarded handle */
1169 if (!(handle = LOCAL_GetNewHandleEntry( ds )))
1171 WARN("Couldn't get handle.\n");
1173 LOCAL_FreeArena( ds, ARENA_HEADER(hmem) );
1176 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1177 plhe = (LOCALHANDLEENTRY *)(ptr + handle);
1181 plhe->addr = hmem + MOVEABLE_PREFIX;
1182 plhe->flags = (BYTE)((flags & 0x0f00) >> 8);
1183 *(HLOCAL16 *)(ptr + hmem) = handle;
1188 plhe->flags = LMEM_DISCARDED >> 8;
1193 if(size) handle = LOCAL_GetBlock( ds, size, flags );
1197 CURRENT_STACK16->ecx = handle; /* must be returned in cx too */
1202 /***********************************************************************
1203 * LocalReAlloc (KERNEL.6)
1205 HLOCAL16 WINAPI LocalReAlloc16( HLOCAL16 handle, WORD size, UINT16 flags )
1207 HANDLE16 ds = CURRENT_DS;
1208 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1209 LOCALHEAPINFO *pInfo;
1210 LOCALARENA *pArena, *pNext;
1211 LOCALHANDLEENTRY *pEntry = NULL;
1212 WORD arena, oldsize;
1213 HLOCAL16 hmem, blockhandle;
1216 if (!handle) return 0;
1217 if(HANDLE_MOVEABLE(handle) &&
1218 ((LOCALHANDLEENTRY *)(ptr + handle))->lock == 0xff) /* An unused handle */
1221 TRACE("%04x %d %04x ds=%04x\n", handle, size, flags, ds );
1222 if (!(pInfo = LOCAL_GetHeap( ds ))) return 0;
1224 if (HANDLE_FIXED( handle ))
1225 blockhandle = handle;
1228 pEntry = (LOCALHANDLEENTRY *) (ptr + handle);
1229 if(pEntry->flags == (LMEM_DISCARDED >> 8))
1233 WARN("Dicarded block has non-zero addr.\n");
1234 TRACE("ReAllocating discarded block\n");
1235 if(size <= 4) size = 5;
1236 if (!(hl = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags)))
1238 ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */
1239 pEntry = (LOCALHANDLEENTRY *) (ptr + handle);
1240 pEntry->addr = hl + MOVEABLE_PREFIX;
1243 *(HLOCAL16 *)(ptr + hl) = handle;
1246 if (((blockhandle = pEntry->addr - MOVEABLE_PREFIX) & 3) != 0)
1248 ERR("(%04x,%04x): invalid handle\n",
1252 if (*(HLOCAL16 *)(ptr + blockhandle) != handle) {
1253 ERR("Back ptr to handle is invalid\n");
1258 if (flags & LMEM_MODIFY)
1260 if (HANDLE_MOVEABLE(handle))
1262 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1263 pEntry->flags = (flags & 0x0f00) >> 8;
1264 TRACE("Changing flags to %x.\n", pEntry->flags);
1271 if (flags & LMEM_MOVEABLE)
1273 if (HANDLE_FIXED(handle))
1275 TRACE("Freeing fixed block.\n");
1276 return LocalFree16( handle );
1278 else /* Moveable block */
1280 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1281 if (pEntry->lock == 0)
1283 /* discards moveable blocks */
1284 TRACE("Discarding block\n");
1285 LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX));
1287 pEntry->flags = (LMEM_DISCARDED >> 8);
1295 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1296 if (pEntry->lock == 0)
1299 return LocalFree16( handle );
1305 arena = ARENA_HEADER( blockhandle );
1306 TRACE("arena is %04x\n", arena );
1307 pArena = ARENA_PTR( ptr, arena );
1309 if(size <= 4) size = 5;
1310 if(HANDLE_MOVEABLE(handle)) size += MOVEABLE_PREFIX;
1311 oldsize = pArena->next - arena - ARENA_HEADER_SIZE;
1312 nextarena = LALIGN(blockhandle + size);
1314 /* Check for size reduction */
1316 if (nextarena <= pArena->next)
1318 TRACE("size reduction, making new free block\n");
1319 LOCAL_ShrinkArena(ds, arena, nextarena - arena);
1320 TRACE("returning %04x\n", handle );
1324 /* Check if the next block is free and large enough */
1326 pNext = ARENA_PTR( ptr, pArena->next );
1327 if (((pNext->prev & 3) == LOCAL_ARENA_FREE) &&
1328 (nextarena <= pNext->next))
1330 TRACE("size increase, making new free block\n");
1331 LOCAL_GrowArenaUpward(ds, arena, nextarena - arena);
1332 if (flags & LMEM_ZEROINIT)
1334 char *oldend = (char *)pArena + ARENA_HEADER_SIZE + oldsize;
1335 char *newend = ptr + pArena->next;
1336 TRACE("Clearing memory from %p to %p (DS -> %p)\n", oldend, newend, ptr);
1337 memset(oldend, 0, newend - oldend);
1340 TRACE("returning %04x\n", handle );
1344 /* Now we have to allocate a new block, but not if (fixed block or locked
1345 block) and no LMEM_MOVEABLE */
1347 if (!(flags & LMEM_MOVEABLE))
1349 if (HANDLE_FIXED(handle))
1351 ERR("Needed to move fixed block, but LMEM_MOVEABLE not specified.\n");
1356 if(((LOCALHANDLEENTRY *)(ptr + handle))->lock != 0)
1358 ERR("Needed to move locked block, but LMEM_MOVEABLE not specified.\n");
1364 hmem = LOCAL_GetBlock( ds, size, flags );
1365 ptr = MapSL( MAKESEGPTR( ds, 0 )); /* Reload ptr */
1366 if(HANDLE_MOVEABLE(handle)) /* LOCAL_GetBlock might have triggered */
1367 { /* a compaction, which might in turn have */
1368 blockhandle = pEntry->addr - MOVEABLE_PREFIX; /* moved the very block we are resizing */
1369 arena = ARENA_HEADER( blockhandle ); /* thus, we reload arena, too */
1373 /* Remove the block from the heap and try again */
1374 LPSTR buffer = HeapAlloc( GetProcessHeap(), 0, oldsize );
1375 if (!buffer) return 0;
1376 memcpy( buffer, ptr + arena + ARENA_HEADER_SIZE, oldsize );
1377 LOCAL_FreeArena( ds, arena );
1378 if (!(hmem = LOCAL_GetBlock( ds, size, flags )))
1380 if (!(hmem = LOCAL_GetBlock( ds, oldsize, flags )))
1382 ERR("Can't restore saved block\n" );
1383 HeapFree( GetProcessHeap(), 0, buffer );
1388 ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */
1389 memcpy( ptr + hmem, buffer, oldsize );
1390 HeapFree( GetProcessHeap(), 0, buffer );
1394 memcpy( ptr + hmem, ptr + (arena + ARENA_HEADER_SIZE), oldsize );
1395 LOCAL_FreeArena( ds, arena );
1397 if (HANDLE_MOVEABLE( handle ))
1399 TRACE("fixing handle\n");
1400 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1401 pEntry->addr = hmem + MOVEABLE_PREFIX;
1402 /* Back ptr should still be correct */
1403 if(*(HLOCAL16 *)(ptr + hmem) != handle)
1404 ERR("back ptr is invalid.\n");
1407 if (size == oldsize) hmem = 0; /* Realloc failed */
1408 TRACE("returning %04x\n", hmem );
1413 /***********************************************************************
1414 * LOCAL_InternalLock
1416 static HLOCAL16 LOCAL_InternalLock( LPSTR heap, HLOCAL16 handle )
1418 HLOCAL16 old_handle = handle;
1420 if (HANDLE_MOVEABLE(handle))
1422 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(heap + handle);
1423 if (pEntry->flags == (LMEM_DISCARDED >> 8)) return 0;
1424 if (pEntry->lock < 0xfe) pEntry->lock++;
1425 handle = pEntry->addr;
1427 TRACE("%04x returning %04x\n", old_handle, handle );
1432 /***********************************************************************
1433 * LocalUnlock (KERNEL.9)
1435 BOOL16 WINAPI LocalUnlock16( HLOCAL16 handle )
1437 HANDLE16 ds = CURRENT_DS;
1438 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1440 TRACE("%04x\n", handle );
1441 if (HANDLE_MOVEABLE(handle))
1443 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1444 if (!pEntry->lock || (pEntry->lock == 0xff)) return FALSE;
1445 /* For moveable block, return the new lock count */
1446 /* (see _Windows_Internals_ p. 197) */
1447 return --pEntry->lock;
1453 /***********************************************************************
1454 * LocalSize (KERNEL.10)
1456 UINT16 WINAPI LocalSize16( HLOCAL16 handle )
1458 HANDLE16 ds = CURRENT_DS;
1459 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1462 TRACE("%04x ds=%04x\n", handle, ds );
1464 if (!handle) return 0;
1465 if (HANDLE_MOVEABLE( handle ))
1467 handle = *(WORD *)(ptr + handle);
1468 if (!handle) return 0;
1469 pArena = ARENA_PTR( ptr, ARENA_HEADER(handle - MOVEABLE_PREFIX) );
1472 pArena = ARENA_PTR( ptr, ARENA_HEADER(handle) );
1474 return pArena->next - handle;
1478 /***********************************************************************
1479 * LocalFlags (KERNEL.12)
1481 UINT16 WINAPI LocalFlags16( HLOCAL16 handle )
1483 HANDLE16 ds = CURRENT_DS;
1484 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1486 if (HANDLE_MOVEABLE(handle))
1488 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1489 TRACE("(%04x,%04x): returning %04x\n",
1490 ds, handle, pEntry->lock | (pEntry->flags << 8) );
1491 return pEntry->lock | (pEntry->flags << 8);
1495 TRACE("(%04x,%04x): returning 0\n",
1502 /***********************************************************************
1503 * LocalHeapSize (KERNEL.162)
1505 WORD WINAPI LocalHeapSize16(void)
1507 HANDLE16 ds = CURRENT_DS;
1508 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
1509 return pInfo ? pInfo->last - pInfo->first : 0;
1513 /***********************************************************************
1514 * LocalCountFree (KERNEL.161)
1516 WORD WINAPI LocalCountFree16(void)
1518 HANDLE16 ds = CURRENT_DS;
1521 LOCALHEAPINFO *pInfo;
1522 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1524 if (!(pInfo = LOCAL_GetHeap( ds )))
1526 ERR("(%04x): Local heap not found\n", ds );
1527 LOCAL_PrintHeap( ds );
1532 arena = pInfo->first;
1533 pArena = ARENA_PTR( ptr, arena );
1536 arena = pArena->free_next;
1537 pArena = ARENA_PTR( ptr, arena );
1538 if (arena == pArena->free_next) break;
1539 total += pArena->size;
1541 TRACE("(%04x): returning %d\n", ds, total);
1546 /***********************************************************************
1547 * LocalHandle (KERNEL.11)
1549 HLOCAL16 WINAPI LocalHandle16( WORD addr )
1551 HANDLE16 ds = CURRENT_DS;
1552 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1553 LOCALHEAPINFO *pInfo;
1556 if (!(pInfo = LOCAL_GetHeap( ds )))
1558 ERR("(%04x): Local heap not found\n", ds );
1559 LOCAL_PrintHeap( ds );
1563 /* Find the address in the entry tables */
1565 table = pInfo->htable;
1568 WORD count = *(WORD *)(ptr + table);
1569 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY*)(ptr+table+sizeof(WORD));
1570 for (; count > 0; count--, pEntry++)
1571 if (pEntry->addr == addr) return (HLOCAL16)((char *)pEntry - ptr);
1572 table = *(WORD *)pEntry;
1575 return (HLOCAL16)addr; /* Fixed block handle is addr */
1581 /***********************************************************************
1582 * LocalLock (KERNEL.8)
1584 * Note: only the offset part of the pointer is returned by the relay code.
1586 SEGPTR WINAPI LocalLock16( HLOCAL16 handle )
1588 WORD ds = CURRENT_DS;
1589 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1590 return MAKESEGPTR( ds, LOCAL_InternalLock( ptr, handle ) );
1594 /***********************************************************************
1595 * LocalCompact (KERNEL.13)
1597 UINT16 WINAPI LocalCompact16( UINT16 minfree )
1599 TRACE("%04x\n", minfree );
1600 return LOCAL_Compact( CURRENT_DS, minfree, 0 );
1604 /***********************************************************************
1605 * LocalNotify (KERNEL.14)
1607 * Installs a callback function that is called for local memory events
1608 * Callback function prototype is
1609 * BOOL16 NotifyFunc(WORD wMsg, HLOCAL16 hMem, WORD wArg)
1612 * NotifyFunc seems to be responsible for allocating some memory,
1613 * returns TRUE for success.
1614 * wArg = number of bytes needed additionally
1616 * hMem = handle; wArg = old mem location
1618 * NotifyFunc seems to be strongly encouraged to return TRUE,
1619 * otherwise LogError() gets called.
1620 * hMem = handle; wArg = flags
1622 FARPROC16 WINAPI LocalNotify16( FARPROC16 func )
1624 LOCALHEAPINFO *pInfo;
1625 FARPROC16 oldNotify;
1626 HANDLE16 ds = CURRENT_DS;
1628 if (!(pInfo = LOCAL_GetHeap( ds )))
1630 ERR("(%04x): Local heap not found\n", ds );
1631 LOCAL_PrintHeap( ds );
1634 TRACE("(%04x): %p\n", ds, func );
1635 FIXME("Half implemented\n");
1636 oldNotify = pInfo->notify;
1637 pInfo->notify = func;
1642 /***********************************************************************
1643 * LocalShrink (KERNEL.121)
1645 UINT16 WINAPI LocalShrink16( HGLOBAL16 handle, UINT16 newsize )
1647 TRACE("%04x %04x\n", handle, newsize );
1652 /***********************************************************************
1653 * GetHeapSpaces (KERNEL.138)
1655 DWORD WINAPI GetHeapSpaces16( HMODULE16 module )
1658 WORD oldDS = CURRENT_DS;
1661 if (!(pModule = NE_GetPtr( module ))) return 0;
1662 CURRENT_DS = GlobalHandleToSel16((NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1)->hSeg);
1663 spaces = MAKELONG( LocalCountFree16(), LocalHeapSize16() );
1669 /***********************************************************************
1670 * LocalHandleDelta (KERNEL.310)
1672 WORD WINAPI LocalHandleDelta16( WORD delta )
1674 LOCALHEAPINFO *pInfo;
1676 if (!(pInfo = LOCAL_GetHeap( CURRENT_DS )))
1678 ERR("Local heap not found\n");
1679 LOCAL_PrintHeap( CURRENT_DS );
1682 if (delta) pInfo->hdelta = delta;
1683 TRACE("returning %04x\n", pInfo->hdelta);
1684 return pInfo->hdelta;
1688 /***********************************************************************
1689 * LocalInfo (TOOLHELP.56)
1691 BOOL16 WINAPI LocalInfo16( LOCALINFO *pLocalInfo, HGLOBAL16 handle )
1693 LOCALHEAPINFO *pInfo = LOCAL_GetHeap(SELECTOROF(WOWGlobalLock16(handle)));
1694 if (!pInfo) return FALSE;
1695 pLocalInfo->wcItems = pInfo->items;
1700 /***********************************************************************
1701 * LocalFirst (TOOLHELP.57)
1703 BOOL16 WINAPI LocalFirst16( LOCALENTRY *pLocalEntry, HGLOBAL16 handle )
1705 WORD ds = GlobalHandleToSel16( handle );
1706 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1707 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
1708 if (!pInfo) return FALSE;
1710 pLocalEntry->hHandle = pInfo->first + ARENA_HEADER_SIZE;
1711 pLocalEntry->wAddress = pLocalEntry->hHandle;
1712 pLocalEntry->wFlags = LF_FIXED;
1713 pLocalEntry->wcLock = 0;
1714 pLocalEntry->wType = LT_NORMAL;
1715 pLocalEntry->hHeap = handle;
1716 pLocalEntry->wHeapType = NORMAL_HEAP;
1717 pLocalEntry->wNext = ARENA_PTR(ptr,pInfo->first)->next;
1718 pLocalEntry->wSize = pLocalEntry->wNext - pLocalEntry->hHandle;
1723 /***********************************************************************
1724 * LocalNext (TOOLHELP.58)
1726 BOOL16 WINAPI LocalNext16( LOCALENTRY *pLocalEntry )
1728 WORD ds = GlobalHandleToSel16( pLocalEntry->hHeap );
1729 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1732 if (!LOCAL_GetHeap( ds )) return FALSE;
1733 if (!pLocalEntry->wNext) return FALSE;
1734 pArena = ARENA_PTR( ptr, pLocalEntry->wNext );
1736 pLocalEntry->hHandle = pLocalEntry->wNext + ARENA_HEADER_SIZE;
1737 pLocalEntry->wAddress = pLocalEntry->hHandle;
1738 pLocalEntry->wFlags = (pArena->prev & 3) + 1;
1739 pLocalEntry->wcLock = 0;
1740 pLocalEntry->wType = LT_NORMAL;
1741 if (pArena->next != pLocalEntry->wNext) /* last one? */
1742 pLocalEntry->wNext = pArena->next;
1744 pLocalEntry->wNext = 0;
1745 pLocalEntry->wSize = pLocalEntry->wNext - pLocalEntry->hHandle;
1750 /***********************************************************************
1751 * 32-bit local heap functions (Win95; undocumented)
1754 /***********************************************************************
1757 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1758 DWORD heapSize, DWORD flags )
1760 DWORD totSize, segSize = 0;
1762 LOCAL32HEADER *header;
1764 WORD *selectorTable;
1765 WORD selectorEven, selectorOdd;
1768 /* Determine new heap size */
1772 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1778 if ( heapSize == (DWORD)-1 )
1779 heapSize = 1024*1024; /* FIXME */
1781 heapSize = (heapSize + 0xffff) & 0xffff0000;
1782 segSize = (segSize + 0x0fff) & 0xfffff000;
1783 totSize = segSize + HTABLE_SIZE + heapSize;
1786 /* Allocate memory and initialize heap */
1788 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1791 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1792 MEM_COMMIT, PAGE_READWRITE ) )
1794 VirtualFree( base, 0, MEM_RELEASE );
1798 if (!(heap = RtlCreateHeap( 0, base + segSize + HTABLE_SIZE, heapSize, 0x10000, NULL, NULL )))
1800 VirtualFree( base, 0, MEM_RELEASE );
1805 /* Set up header and handle table */
1807 header = (LOCAL32HEADER *)(base + segSize);
1808 header->base = base;
1809 header->limit = HTABLE_PAGESIZE-1;
1811 header->magic = LOCAL32_MAGIC;
1812 header->heap = heap;
1814 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1815 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1816 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1818 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1819 *(DWORD *)((LPBYTE)header + i) = i+4;
1821 header->freeListFirst[1] = 0xffff;
1824 /* Set up selector table */
1826 nrBlocks = (totSize + 0x7fff) >> 15;
1827 selectorTable = HeapAlloc( header->heap, 0, nrBlocks * 2 );
1828 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1829 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1830 if ( !selectorTable || !selectorEven || !selectorOdd )
1832 HeapFree( header->heap, 0, selectorTable );
1833 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1834 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1835 HeapDestroy( header->heap );
1836 VirtualFree( base, 0, MEM_RELEASE );
1840 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1841 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1842 header->selectorDelta = selectorEven - selectorOdd;
1843 header->segment = segment? segment : selectorEven;
1845 for (i = 0; i < nrBlocks; i++)
1846 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1847 : selectorEven + ((i >> 1) << __AHSHIFT);
1849 /* Move old segment */
1853 /* FIXME: This is somewhat ugly and relies on implementation
1854 details about 16-bit global memory handles ... */
1856 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1857 memcpy( base, oldBase, segSize );
1858 GLOBAL_MoveBlock( segment, base, totSize );
1859 HeapFree( GetProcessHeap(), 0, oldBase );
1862 return (HANDLE)header;
1865 /***********************************************************************
1866 * Local32_SearchHandle
1868 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1872 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1873 handle < (LPDWORD)((LPBYTE)header + header->limit);
1876 if (*handle == addr)
1883 /***********************************************************************
1886 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1887 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1894 case -2: /* 16:16 pointer, no handles */
1895 *ptr = MapSL( addr );
1896 *handle = (LPDWORD)*ptr;
1899 case -1: /* 32-bit offset, no handles */
1900 *ptr = header->base + addr;
1901 *handle = (LPDWORD)*ptr;
1904 case 0: /* handle */
1905 if ( addr >= sizeof(LOCAL32HEADER)
1906 && addr < header->limit && !(addr & 3)
1907 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1909 *handle = (LPDWORD)((LPBYTE)header + addr);
1910 *ptr = header->base + **handle;
1914 case 1: /* 16:16 pointer */
1915 *ptr = MapSL( addr );
1916 *handle = Local32_SearchHandle( header, *ptr - header->base );
1919 case 2: /* 32-bit offset */
1920 *ptr = header->base + addr;
1921 *handle = Local32_SearchHandle( header, *ptr - header->base );
1926 /***********************************************************************
1927 * Local32_FromHandle
1929 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
1930 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1935 case -2: /* 16:16 pointer */
1938 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1939 DWORD offset = ptr - header->base;
1940 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
1944 case -1: /* 32-bit offset */
1946 *addr = ptr - header->base;
1949 case 0: /* handle */
1950 *addr = (LPBYTE)handle - (LPBYTE)header;
1955 /***********************************************************************
1958 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1960 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1965 /* Allocate memory */
1966 ptr = HeapAlloc( header->heap,
1967 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1971 /* Allocate handle if requested */
1976 /* Find first page of handle table with free slots */
1977 for (page = 0; page < HTABLE_NPAGES; page++)
1978 if (header->freeListFirst[page] != 0)
1980 if (page == HTABLE_NPAGES)
1982 WARN("Out of handles!\n" );
1983 HeapFree( header->heap, 0, ptr );
1987 /* If virgin page, initialize it */
1988 if (header->freeListFirst[page] == 0xffff)
1990 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
1991 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1993 WARN("Cannot grow handle table!\n" );
1994 HeapFree( header->heap, 0, ptr );
1998 header->limit += HTABLE_PAGESIZE;
2000 header->freeListFirst[page] = 0;
2001 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
2002 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
2004 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
2005 *(DWORD *)((LPBYTE)header + i) = i+4;
2007 if (page < HTABLE_NPAGES-1)
2008 header->freeListFirst[page+1] = 0xffff;
2011 /* Allocate handle slot from page */
2012 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
2013 if (--header->freeListSize[page] == 0)
2014 header->freeListFirst[page] = header->freeListLast[page] = 0;
2016 header->freeListFirst[page] = *handle;
2018 /* Store 32-bit offset in handle slot */
2019 *handle = ptr - header->base;
2023 handle = (LPDWORD)ptr;
2028 /* Convert handle to requested output type */
2029 Local32_FromHandle( header, type, &addr, handle, ptr );
2033 /***********************************************************************
2036 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2037 DWORD size, DWORD flags )
2039 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2044 return Local32Alloc16( heap, size, type, flags );
2046 /* Retrieve handle and pointer */
2047 Local32_ToHandle( header, type, addr, &handle, &ptr );
2048 if (!handle) return FALSE;
2050 /* Reallocate memory block */
2051 ptr = HeapReAlloc( header->heap,
2052 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2058 *handle = ptr - header->base;
2060 handle = (LPDWORD)ptr;
2062 /* Convert handle to requested output type */
2063 Local32_FromHandle( header, type, &addr, handle, ptr );
2067 /***********************************************************************
2070 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2072 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2076 /* Retrieve handle and pointer */
2077 Local32_ToHandle( header, type, addr, &handle, &ptr );
2078 if (!handle) return FALSE;
2080 /* Free handle if necessary */
2083 int offset = (LPBYTE)handle - (LPBYTE)header;
2084 int page = offset >> 12;
2086 /* Return handle slot to page free list */
2087 if (header->freeListSize[page]++ == 0)
2088 header->freeListFirst[page] = header->freeListLast[page] = offset;
2090 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2091 header->freeListLast[page] = offset;
2095 /* Shrink handle table when possible */
2096 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2098 if ( VirtualFree( (LPBYTE)header +
2099 (header->limit & ~(HTABLE_PAGESIZE-1)),
2100 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2103 header->limit -= HTABLE_PAGESIZE;
2104 header->freeListFirst[page] = 0xffff;
2110 return HeapFree( header->heap, 0, ptr );
2113 /***********************************************************************
2116 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2118 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2122 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2123 if (!handle) return 0;
2125 Local32_FromHandle( header, type2, &addr, handle, ptr );
2129 /***********************************************************************
2132 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2134 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2138 Local32_ToHandle( header, type, addr, &handle, &ptr );
2139 if (!handle) return 0;
2141 return HeapSize( header->heap, 0, ptr );
2144 /***********************************************************************
2147 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2149 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2153 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2154 return handle != NULL;
2157 /***********************************************************************
2160 WORD WINAPI Local32GetSegment16( HANDLE heap )
2162 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2163 return header->segment;
2166 /***********************************************************************
2169 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2171 WORD selector = GlobalHandleToSel16( handle );
2172 DWORD base = GetSelectorBase( selector );
2173 DWORD limit = GetSelectorLimit16( selector );
2175 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2178 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2179 return (LOCAL32HEADER *)base;
2184 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2185 return (LOCAL32HEADER *)base;
2190 /***********************************************************************
2191 * Local32Info (KERNEL.444)
2192 * Local32Info (TOOLHELP.84)
2194 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2196 PROCESS_HEAP_ENTRY entry;
2199 LOCAL32HEADER *header = Local32_GetHeap( handle );
2200 if ( !header ) return FALSE;
2202 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2205 pLocal32Info->dwMemReserved = 0;
2206 pLocal32Info->dwMemCommitted = 0;
2207 pLocal32Info->dwTotalFree = 0;
2208 pLocal32Info->dwLargestFreeBlock = 0;
2210 while (HeapWalk( header->heap, &entry ))
2212 if (entry.wFlags & PROCESS_HEAP_REGION)
2214 pLocal32Info->dwMemReserved += entry.u.Region.dwCommittedSize
2215 + entry.u.Region.dwUnCommittedSize;
2216 pLocal32Info->dwMemCommitted = entry.u.Region.dwCommittedSize;
2218 else if (!(entry.wFlags & PROCESS_HEAP_ENTRY_BUSY))
2220 DWORD size = entry.cbData + entry.cbOverhead;
2221 pLocal32Info->dwTotalFree += size;
2222 if (size > pLocal32Info->dwLargestFreeBlock) pLocal32Info->dwLargestFreeBlock = size;
2226 pLocal32Info->dwcFreeHandles = 0;
2227 for ( i = 0; i < HTABLE_NPAGES; i++ )
2229 if ( header->freeListFirst[i] == 0xffff ) break;
2230 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2232 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2237 /***********************************************************************
2238 * Local32First (KERNEL.445)
2239 * Local32First (TOOLHELP.85)
2241 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2243 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2247 /***********************************************************************
2248 * Local32Next (KERNEL.446)
2249 * Local32Next (TOOLHELP.86)
2251 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2253 FIXME("(%p): stub!\n", pLocal32Entry );