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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 "stackframe.h"
42 #include "kernel_private.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(local);
50 WORD prev; /* Previous arena | arena type */
51 WORD next; /* Next arena */
52 /* Start of the memory block or free-list info */
53 WORD size; /* Size of the free block */
54 WORD free_prev; /* Previous free block */
55 WORD free_next; /* Next free block */
58 #define ARENA_HEADER_SIZE 4
59 #define ARENA_HEADER( handle) ((handle) - ARENA_HEADER_SIZE)
61 /* Arena types (stored in 'prev' field of the arena) */
62 #define LOCAL_ARENA_FREE 0
63 #define LOCAL_ARENA_FIXED 1
65 /* LocalNotify() msgs */
71 /* Layout of a handle entry table
73 * WORD count of entries
74 * LOCALHANDLEENTRY[count] entries
75 * WORD near ptr to next table
79 WORD addr; /* Address of the MOVEABLE block */
80 BYTE flags; /* Flags for this block */
81 BYTE lock; /* Lock count */
85 * We make addr = 4n + 2 and set *((WORD *)addr - 1) = &addr like Windows does
86 * in case something actually relies on this.
87 * Note that if the architecture does not allow unaligned accesses, we make
88 * addr = 4n + 4 to avoid returning unaligned pointers from LocalAlloc etc.
90 * An unused handle has lock = flags = 0xff. In windows addr is that of next
91 * free handle, at the moment in wine we set it to 0.
93 * A discarded block's handle has lock = addr = 0 and flags = 0x40
94 * (LMEM_DISCARDED >> 8)
97 #ifdef ALLOW_UNALIGNED_ACCESS
98 #define MOVEABLE_PREFIX sizeof(HLOCAL16)
100 #define MOVEABLE_PREFIX sizeof(int)
104 #include "pshpack1.h"
108 WORD check; /* 00 Heap checking flag */
109 WORD freeze; /* 02 Heap frozen flag */
110 WORD items; /* 04 Count of items on the heap */
111 WORD first; /* 06 First item of the heap */
112 WORD pad1; /* 08 Always 0 */
113 WORD last; /* 0a Last item of the heap */
114 WORD pad2; /* 0c Always 0 */
115 BYTE ncompact; /* 0e Compactions counter */
116 BYTE dislevel; /* 0f Discard level */
117 DWORD distotal; /* 10 Total bytes discarded */
118 WORD htable; /* 14 Pointer to handle table */
119 WORD hfree; /* 16 Pointer to free handle table */
120 WORD hdelta; /* 18 Delta to expand the handle table */
121 WORD expand; /* 1a Pointer to expand function (unused) */
122 WORD pstat; /* 1c Pointer to status structure (unused) */
123 FARPROC16 notify; /* 1e Pointer to LocalNotify() function */
124 WORD lock; /* 22 Lock count for the heap */
125 WORD extra; /* 24 Extra bytes to allocate when expanding */
126 WORD minsize; /* 26 Minimum size of the heap */
127 WORD magic; /* 28 Magic number */
132 #define LOCAL_HEAP_MAGIC 0x484c /* 'LH' */
134 /* All local heap allocations are aligned on 4-byte boundaries */
135 #define LALIGN(word) (((word) + 3) & ~3)
137 #define ARENA_PTR(ptr,arena) ((LOCALARENA *)((char*)(ptr)+(arena)))
138 #define ARENA_PREV(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & ~3)
139 #define ARENA_NEXT(ptr,arena) (ARENA_PTR((ptr),(arena))->next)
140 #define ARENA_FLAGS(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & 3)
142 /* determine whether the handle belongs to a fixed or a moveable block */
143 #define HANDLE_FIXED(handle) (((handle) & 3) == 0)
144 #define HANDLE_MOVEABLE(handle) (((handle) & 3) == 2)
147 /* 32-bit heap definitions */
149 #define HTABLE_SIZE 0x10000
150 #define HTABLE_PAGESIZE 0x1000
151 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
153 #include "pshpack1.h"
154 typedef struct _LOCAL32HEADER
156 WORD freeListFirst[HTABLE_NPAGES];
157 WORD freeListSize[HTABLE_NPAGES];
158 WORD freeListLast[HTABLE_NPAGES];
160 DWORD selectorTableOffset;
161 WORD selectorTableSize;
176 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
179 static inline BOOL16 call_notify_func( FARPROC16 proc, WORD msg, HLOCAL16 handle, WORD arg )
184 if (!proc) return FALSE;
188 WOWCallback16Ex( (DWORD)proc, WCB16_PASCAL, sizeof(args), args, &ret );
193 /***********************************************************************
196 * Return a pointer to the local heap, making sure it exists.
198 static LOCALHEAPINFO *LOCAL_GetHeap( HANDLE16 ds )
200 LOCALHEAPINFO *pInfo;
201 INSTANCEDATA *ptr = MapSL( MAKESEGPTR( ds, 0 ));
202 TRACE("Heap at %p, %04x\n", ptr, (ptr != NULL ? ptr->heap : 0xFFFF));
203 if (!ptr || !ptr->heap) return NULL;
204 if (IsBadReadPtr16( (SEGPTR)MAKELONG(ptr->heap,ds), sizeof(LOCALHEAPINFO)))
206 WARN("Bad pointer\n");
209 pInfo = (LOCALHEAPINFO*)((char*)ptr + ptr->heap);
210 if (pInfo->magic != LOCAL_HEAP_MAGIC)
219 /***********************************************************************
220 * LOCAL_MakeBlockFree
222 * Make a block free, inserting it in the free-list.
223 * 'block' is the handle of the block arena; 'baseptr' points to
224 * the beginning of the data segment containing the heap.
226 static void LOCAL_MakeBlockFree( char *baseptr, WORD block )
228 LOCALARENA *pArena, *pNext;
231 /* Mark the block as free */
233 pArena = ARENA_PTR( baseptr, block );
234 pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FREE;
235 pArena->size = pArena->next - block;
237 /* Find the next free block (last block is always free) */
242 pNext = ARENA_PTR( baseptr, next );
243 if ((pNext->prev & 3) == LOCAL_ARENA_FREE) break;
247 TRACE("%04x, next %04x\n", block, next );
248 /* Insert the free block in the free-list */
250 pArena->free_prev = pNext->free_prev;
251 pArena->free_next = next;
252 ARENA_PTR(baseptr,pNext->free_prev)->free_next = block;
253 pNext->free_prev = block;
257 /***********************************************************************
258 * LOCAL_RemoveFreeBlock
260 * Remove a block from the free-list.
261 * 'block' is the handle of the block arena; 'baseptr' points to
262 * the beginning of the data segment containing the heap.
264 static void LOCAL_RemoveFreeBlock( char *baseptr, WORD block )
266 /* Mark the block as fixed */
268 LOCALARENA *pArena = ARENA_PTR( baseptr, block );
269 pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FIXED;
271 /* Remove it from the list */
273 ARENA_PTR(baseptr,pArena->free_prev)->free_next = pArena->free_next;
274 ARENA_PTR(baseptr,pArena->free_next)->free_prev = pArena->free_prev;
278 /***********************************************************************
281 * Insert a new block in the heap.
282 * 'new' is the handle of the new block arena; 'baseptr' points to
283 * the beginning of the data segment containing the heap; 'prev' is
284 * the block before the new one.
286 static void LOCAL_AddBlock( char *baseptr, WORD prev, WORD new )
288 LOCALARENA *pPrev = ARENA_PTR( baseptr, prev );
289 LOCALARENA *pNew = ARENA_PTR( baseptr, new );
291 pNew->prev = (prev & ~3) | LOCAL_ARENA_FIXED;
292 pNew->next = pPrev->next;
293 ARENA_PTR(baseptr,pPrev->next)->prev &= 3;
294 ARENA_PTR(baseptr,pPrev->next)->prev |= new;
299 /***********************************************************************
302 * Remove a block from the heap.
303 * 'block' is the handle of the block arena; 'baseptr' points to
304 * the beginning of the data segment containing the heap.
306 static void LOCAL_RemoveBlock( char *baseptr, WORD block )
308 LOCALARENA *pArena, *pTmp;
310 /* Remove the block from the free-list */
313 pArena = ARENA_PTR( baseptr, block );
314 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
315 LOCAL_RemoveFreeBlock( baseptr, block );
317 /* If the previous block is free, expand its size */
319 pTmp = ARENA_PTR( baseptr, pArena->prev & ~3 );
320 if ((pTmp->prev & 3) == LOCAL_ARENA_FREE)
321 pTmp->size += pArena->next - block;
323 /* Remove the block from the linked list */
325 pTmp->next = pArena->next;
326 pTmp = ARENA_PTR( baseptr, pArena->next );
327 pTmp->prev = (pTmp->prev & 3) | (pArena->prev & ~3);
331 /***********************************************************************
334 static void LOCAL_PrintHeap( HANDLE16 ds )
337 LOCALHEAPINFO *pInfo;
340 /* FIXME - the test should be done when calling the function!
341 plus is not clear that we should print this info
342 only when TRACE_ON is on! */
343 if(!TRACE_ON(local)) return;
345 ptr = MapSL( MAKESEGPTR( ds, 0 ));
346 pInfo = LOCAL_GetHeap( ds );
350 DPRINTF( "Local Heap corrupted! ds=%04x\n", ds );
353 DPRINTF( "Local Heap ds=%04x first=%04x last=%04x items=%d\n",
354 ds, pInfo->first, pInfo->last, pInfo->items );
356 arena = pInfo->first;
359 LOCALARENA *pArena = ARENA_PTR(ptr,arena);
360 DPRINTF( " %04x: prev=%04x next=%04x type=%d\n", arena,
361 pArena->prev & ~3, pArena->next, pArena->prev & 3 );
362 if (arena == pInfo->first)
364 DPRINTF( " size=%d free_prev=%04x free_next=%04x\n",
365 pArena->size, pArena->free_prev, pArena->free_next );
367 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
369 DPRINTF( " size=%d free_prev=%04x free_next=%04x\n",
370 pArena->size, pArena->free_prev, pArena->free_next );
371 if (pArena->next == arena) break; /* last one */
372 if (ARENA_PTR(ptr,pArena->free_next)->free_prev != arena)
374 DPRINTF( "*** arena->free_next->free_prev != arena\n" );
378 if (pArena->next == arena)
380 DPRINTF( "*** last block is not marked free\n" );
383 if ((ARENA_PTR(ptr,pArena->next)->prev & ~3) != arena)
385 DPRINTF( "*** arena->next->prev != arena (%04x, %04x)\n",
386 pArena->next, ARENA_PTR(ptr,pArena->next)->prev);
389 arena = pArena->next;
394 /***********************************************************************
395 * LocalInit (KERNEL.4)
397 BOOL16 WINAPI LocalInit16( HANDLE16 selector, WORD start, WORD end )
400 WORD heapInfoArena, freeArena, lastArena;
401 LOCALHEAPINFO *pHeapInfo;
402 LOCALARENA *pArena, *pFirstArena, *pLastArena;
405 /* The initial layout of the heap is: */
406 /* - first arena (FIXED) */
407 /* - heap info structure (FIXED) */
408 /* - large free block (FREE) */
409 /* - last arena (FREE) */
411 TRACE("%04x %04x-%04x\n", selector, start, end);
412 if (!selector) selector = CURRENT_DS;
416 /* If TRACE_ON(heap) is set, the global heap blocks are */
417 /* cleared before use, so we can test for double initialization. */
418 if (LOCAL_GetHeap(selector))
420 ERR("Heap %04x initialized twice.\n", selector);
421 LOCAL_PrintHeap(selector);
427 /* start == 0 means: put the local heap at the end of the segment */
429 DWORD size = GlobalSize16( GlobalHandle16( selector ) );
430 start = (WORD)(size > 0xffff ? 0xffff : size) - 1;
431 if ( end > 0xfffe ) end = 0xfffe;
435 ptr = MapSL( MAKESEGPTR( selector, 0 ) );
437 start = LALIGN( max( start, sizeof(INSTANCEDATA) ) );
438 heapInfoArena = LALIGN(start + sizeof(LOCALARENA) );
439 freeArena = LALIGN( heapInfoArena + ARENA_HEADER_SIZE
440 + sizeof(LOCALHEAPINFO) );
441 lastArena = (end - sizeof(LOCALARENA)) & ~3;
443 /* Make sure there's enough space. */
445 if (freeArena + sizeof(LOCALARENA) >= lastArena) goto done;
447 /* Initialise the first arena */
449 pFirstArena = ARENA_PTR( ptr, start );
450 pFirstArena->prev = start | LOCAL_ARENA_FIXED;
451 pFirstArena->next = heapInfoArena;
452 pFirstArena->size = LALIGN(sizeof(LOCALARENA));
453 pFirstArena->free_prev = start; /* this one */
454 pFirstArena->free_next = freeArena;
456 /* Initialise the arena of the heap info structure */
458 pArena = ARENA_PTR( ptr, heapInfoArena );
459 pArena->prev = start | LOCAL_ARENA_FIXED;
460 pArena->next = freeArena;
462 /* Initialise the heap info structure */
464 pHeapInfo = (LOCALHEAPINFO *) (ptr + heapInfoArena + ARENA_HEADER_SIZE );
465 memset( pHeapInfo, 0, sizeof(LOCALHEAPINFO) );
466 pHeapInfo->items = 4;
467 pHeapInfo->first = start;
468 pHeapInfo->last = lastArena;
469 pHeapInfo->htable = 0;
470 pHeapInfo->hdelta = 0x20;
471 pHeapInfo->extra = 0x200;
472 pHeapInfo->minsize = lastArena - freeArena;
473 pHeapInfo->magic = LOCAL_HEAP_MAGIC;
475 /* Initialise the large free block */
477 pArena = ARENA_PTR( ptr, freeArena );
478 pArena->prev = heapInfoArena | LOCAL_ARENA_FREE;
479 pArena->next = lastArena;
480 pArena->size = lastArena - freeArena;
481 pArena->free_prev = start;
482 pArena->free_next = lastArena;
484 /* Initialise the last block */
486 pLastArena = ARENA_PTR( ptr, lastArena );
487 pLastArena->prev = freeArena | LOCAL_ARENA_FREE;
488 pLastArena->next = lastArena; /* this one */
489 pLastArena->size = LALIGN(sizeof(LOCALARENA));
490 pLastArena->free_prev = freeArena;
491 pLastArena->free_next = lastArena; /* this one */
493 /* Store the local heap address in the instance data */
495 ((INSTANCEDATA *)ptr)->heap = heapInfoArena + ARENA_HEADER_SIZE;
496 LOCAL_PrintHeap( selector );
500 CURRENT_STACK16->ecx = ret; /* must be returned in cx too */
505 /***********************************************************************
508 static BOOL16 LOCAL_GrowHeap( HANDLE16 ds )
513 LOCALHEAPINFO *pHeapInfo;
514 WORD freeArena, lastArena;
515 LOCALARENA *pArena, *pLastArena;
518 hseg = GlobalHandle16( ds );
519 /* maybe mem allocated by Virtual*() ? */
520 if (!hseg) return FALSE;
522 oldsize = GlobalSize16( hseg );
523 /* if nothing can be gained, return */
524 if (oldsize > 0xfff0) return FALSE;
525 hseg = GlobalReAlloc16( hseg, 0x10000, GMEM_FIXED );
526 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
527 pHeapInfo = LOCAL_GetHeap( ds );
528 if (pHeapInfo == NULL) {
529 ERR("Heap not found\n" );
532 end = GlobalSize16( hseg );
533 lastArena = (end - sizeof(LOCALARENA)) & ~3;
535 /* Update the HeapInfo */
537 freeArena = pHeapInfo->last;
538 pHeapInfo->last = lastArena;
539 pHeapInfo->minsize += end - oldsize;
541 /* grow the old last block */
542 pArena = ARENA_PTR( ptr, freeArena );
543 pArena->size = lastArena - freeArena;
544 pArena->next = lastArena;
545 pArena->free_next = lastArena;
547 /* Initialise the new last block */
549 pLastArena = ARENA_PTR( ptr, lastArena );
550 pLastArena->prev = freeArena | LOCAL_ARENA_FREE;
551 pLastArena->next = lastArena; /* this one */
552 pLastArena->size = LALIGN(sizeof(LOCALARENA));
553 pLastArena->free_prev = freeArena;
554 pLastArena->free_next = lastArena; /* this one */
556 /* If block before freeArena is also free then merge them */
557 if((ARENA_PTR(ptr, (pArena->prev & ~3))->prev & 3) == LOCAL_ARENA_FREE)
559 LOCAL_RemoveBlock(ptr, freeArena);
563 TRACE("Heap expanded\n" );
564 LOCAL_PrintHeap( ds );
569 /***********************************************************************
572 static HLOCAL16 LOCAL_FreeArena( WORD ds, WORD arena )
574 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
575 LOCALHEAPINFO *pInfo;
576 LOCALARENA *pArena, *pPrev, *pNext;
578 TRACE("%04x ds=%04x\n", arena, ds );
579 if (!(pInfo = LOCAL_GetHeap( ds ))) return arena;
581 pArena = ARENA_PTR( ptr, arena );
582 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
584 /* shouldn't happen */
585 ERR("Trying to free block %04x twice!\n",
587 LOCAL_PrintHeap( ds );
591 /* Check if we can merge with the previous block */
593 pPrev = ARENA_PTR( ptr, pArena->prev & ~3 );
594 pNext = ARENA_PTR( ptr, pArena->next );
595 if ((pPrev->prev & 3) == LOCAL_ARENA_FREE)
597 arena = pArena->prev & ~3;
599 LOCAL_RemoveBlock( ptr, pPrev->next );
602 else /* Make a new free block */
604 LOCAL_MakeBlockFree( ptr, arena );
607 /* Check if we can merge with the next block */
609 if ((pArena->next == pArena->free_next) &&
610 (pArena->next != pInfo->last))
612 LOCAL_RemoveBlock( ptr, pArena->next );
619 /***********************************************************************
622 * Shrink an arena by creating a free block at its end if possible.
623 * 'size' includes the arena header, and must be aligned.
625 static void LOCAL_ShrinkArena( WORD ds, WORD arena, WORD size )
627 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
628 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
630 if (arena + size + LALIGN(sizeof(LOCALARENA)) < pArena->next)
632 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
634 LOCAL_AddBlock( ptr, arena, arena + size );
636 LOCAL_FreeArena( ds, arena + size );
641 /***********************************************************************
642 * LOCAL_GrowArenaDownward
644 * Grow an arena downward by using the previous arena (must be free).
646 static void LOCAL_GrowArenaDownward( WORD ds, WORD arena, WORD newsize )
648 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
649 LOCALHEAPINFO *pInfo;
650 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
651 WORD prevArena = pArena->prev & ~3;
652 LOCALARENA *pPrevArena = ARENA_PTR( ptr, prevArena );
656 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
657 offset = pPrevArena->size;
658 size = pArena->next - arena - ARENA_HEADER_SIZE;
659 LOCAL_RemoveFreeBlock( ptr, prevArena );
660 LOCAL_RemoveBlock( ptr, arena );
662 p = (char *)pPrevArena + ARENA_HEADER_SIZE;
663 while (offset < size)
665 memcpy( p, p + offset, offset );
669 if (size) memcpy( p, p + offset, size );
670 LOCAL_ShrinkArena( ds, prevArena, newsize );
675 /***********************************************************************
676 * LOCAL_GrowArenaUpward
678 * Grow an arena upward by using the next arena (must be free and big
679 * enough). Newsize includes the arena header and must be aligned.
681 static void LOCAL_GrowArenaUpward( WORD ds, WORD arena, WORD newsize )
683 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
684 LOCALHEAPINFO *pInfo;
685 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
686 WORD nextArena = pArena->next;
688 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
689 LOCAL_RemoveBlock( ptr, nextArena );
691 LOCAL_ShrinkArena( ds, arena, newsize );
695 /***********************************************************************
698 static WORD LOCAL_GetFreeSpace(WORD ds, WORD countdiscard)
700 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
701 LOCALHEAPINFO *pInfo;
706 if (!(pInfo = LOCAL_GetHeap( ds )))
708 ERR("Local heap not found\n" );
712 arena = pInfo->first;
713 pArena = ARENA_PTR( ptr, arena );
714 while (arena != pArena->free_next)
716 arena = pArena->free_next;
717 pArena = ARENA_PTR( ptr, arena );
718 if (pArena->size >= freespace) freespace = pArena->size;
720 /* FIXME doesn't yet calculate space that would become free if everything
721 were discarded when countdiscard == 1 */
722 if (freespace < ARENA_HEADER_SIZE) freespace = 0;
723 else freespace -= ARENA_HEADER_SIZE;
728 /***********************************************************************
731 WORD LOCAL_Compact( HANDLE16 ds, UINT16 minfree, UINT16 flags )
733 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
734 LOCALHEAPINFO *pInfo;
735 LOCALARENA *pArena, *pMoveArena, *pFinalArena;
736 WORD arena, movearena, finalarena, table;
737 WORD count, movesize, size;
739 LOCALHANDLEENTRY *pEntry;
741 if (!(pInfo = LOCAL_GetHeap( ds )))
743 ERR("Local heap not found\n" );
747 TRACE("ds = %04x, minfree = %04x, flags = %04x\n",
749 freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1);
750 if(freespace >= minfree || (flags & LMEM_NOCOMPACT))
752 TRACE("Returning %04x.\n", freespace);
755 TRACE("Compacting heap %04x.\n", ds);
756 table = pInfo->htable;
759 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
760 for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++)
762 if((pEntry->lock == 0) && (pEntry->flags != (LMEM_DISCARDED >> 8)))
764 /* OK we can move this one if we want */
765 TRACE("handle %04x (block %04x) can be moved.\n",
766 (WORD)((char *)pEntry - ptr), pEntry->addr);
767 movearena = ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX);
768 pMoveArena = ARENA_PTR(ptr, movearena);
769 movesize = pMoveArena->next - movearena;
770 arena = pInfo->first;
771 pArena = ARENA_PTR(ptr, arena);
774 /* Try to find the smallest arena that will do, */
775 /* which is below us in memory */
778 arena = pArena->free_next;
779 pArena = ARENA_PTR(ptr, arena);
780 if(arena >= movearena)
782 if(arena == pArena->free_next)
784 if((pArena->size >= movesize) && (pArena->size < size))
790 if (finalarena) /* Actually got somewhere to move */
792 TRACE("Moving it to %04x.\n", finalarena);
793 pFinalArena = ARENA_PTR(ptr, finalarena);
794 size = pFinalArena->size;
795 LOCAL_RemoveFreeBlock(ptr, finalarena);
796 LOCAL_ShrinkArena( ds, finalarena, movesize );
797 /* Copy the arena to it's new location */
798 memcpy((char *)pFinalArena + ARENA_HEADER_SIZE,
799 (char *)pMoveArena + ARENA_HEADER_SIZE,
800 movesize - ARENA_HEADER_SIZE );
801 /* Free the old location */
802 LOCAL_FreeArena(ds, movearena);
803 call_notify_func(pInfo->notify, LN_MOVE,
804 (WORD)((char *)pEntry - ptr), pEntry->addr);
805 /* Update handle table entry */
806 pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX;
808 else if((ARENA_PTR(ptr, pMoveArena->prev & ~3)->prev & 3)
811 /* Previous arena is free (but < movesize) */
812 /* so we can 'slide' movearena down into it */
813 finalarena = pMoveArena->prev & ~3;
814 LOCAL_GrowArenaDownward( ds, movearena, movesize );
815 /* Update handle table entry */
816 pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX;
820 table = *(WORD *)pEntry;
822 freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1);
823 if(freespace >= minfree || (flags & LMEM_NODISCARD))
825 TRACE("Returning %04x.\n", freespace);
829 table = pInfo->htable;
832 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
833 for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++)
835 if(pEntry->addr && pEntry->lock == 0 &&
836 (pEntry->flags & (LMEM_DISCARDABLE >> 8)))
838 TRACE("Discarding handle %04x (block %04x).\n",
839 (char *)pEntry - ptr, pEntry->addr);
840 LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX));
841 call_notify_func(pInfo->notify, LN_DISCARD, (char *)pEntry - ptr, pEntry->flags);
843 pEntry->flags = (LMEM_DISCARDED >> 8);
846 table = *(WORD *)pEntry;
848 return LOCAL_Compact(ds, 0xffff, LMEM_NODISCARD);
852 /***********************************************************************
853 * LOCAL_FindFreeBlock
855 static HLOCAL16 LOCAL_FindFreeBlock( HANDLE16 ds, WORD size )
857 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
858 LOCALHEAPINFO *pInfo;
862 if (!(pInfo = LOCAL_GetHeap( ds )))
864 ERR("Local heap not found\n" );
869 arena = pInfo->first;
870 pArena = ARENA_PTR( ptr, arena );
872 arena = pArena->free_next;
873 pArena = ARENA_PTR( ptr, arena );
874 if (arena == pArena->free_next) break;
875 if (pArena->size >= size) return arena;
877 TRACE("not enough space\n" );
883 /***********************************************************************
886 static const char *get_heap_name( WORD ds )
888 HINSTANCE16 inst = LoadLibrary16( "GDI" );
889 if (ds == GlobalHandleToSel16( inst ))
891 FreeLibrary16( inst );
894 FreeLibrary16( inst );
895 inst = LoadLibrary16( "USER" );
896 if (ds == GlobalHandleToSel16( inst ))
898 FreeLibrary16( inst );
901 FreeLibrary16( inst );
905 /***********************************************************************
907 * The segment may get moved around in this function, so all callers
908 * should reset their pointer variables.
910 static HLOCAL16 LOCAL_GetBlock( HANDLE16 ds, WORD size, WORD flags )
912 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
913 LOCALHEAPINFO *pInfo;
917 if (!(pInfo = LOCAL_GetHeap( ds )))
919 ERR("Local heap not found\n");
924 size += ARENA_HEADER_SIZE;
925 size = LALIGN( max( size, sizeof(LOCALARENA) ) );
930 /* Find a suitable free block */
931 arena = LOCAL_FindFreeBlock( ds, size );
933 /* no space: try to make some */
934 LOCAL_Compact( ds, size, flags );
935 arena = LOCAL_FindFreeBlock( ds, size );
938 /* still no space: try to grow the segment */
939 if (!(LOCAL_GrowHeap( ds )))
942 /* FIXME: doesn't work correctly yet */
943 if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds - 20, size)) /* FIXME: "size" correct ? (should indicate bytes needed) */
946 ERR( "not enough space in %s heap %04x for %d bytes\n",
947 get_heap_name(ds), ds, size );
950 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
951 pInfo = LOCAL_GetHeap( ds );
952 arena = LOCAL_FindFreeBlock( ds, size );
955 ERR( "not enough space in %s heap %04x for %d bytes\n",
956 get_heap_name(ds), ds, size );
958 /* FIXME: "size" correct ? (should indicate bytes needed) */
959 if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds, size)) goto notify_done;
964 /* Make a block out of the free arena */
965 pArena = ARENA_PTR( ptr, arena );
966 TRACE("size = %04x, arena %04x size %04x\n",
967 size, arena, pArena->size );
968 LOCAL_RemoveFreeBlock( ptr, arena );
969 LOCAL_ShrinkArena( ds, arena, size );
971 if (flags & LMEM_ZEROINIT)
972 memset((char *)pArena + ARENA_HEADER_SIZE, 0, size-ARENA_HEADER_SIZE);
973 return arena + ARENA_HEADER_SIZE;
977 /***********************************************************************
980 static BOOL16 LOCAL_NewHTable( HANDLE16 ds )
982 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
983 LOCALHEAPINFO *pInfo;
984 LOCALHANDLEENTRY *pEntry;
989 if (!(pInfo = LOCAL_GetHeap( ds )))
991 ERR("Local heap not found\n");
996 if (!(handle = LOCAL_GetBlock( ds, pInfo->hdelta * sizeof(LOCALHANDLEENTRY)
997 + 2 * sizeof(WORD), LMEM_FIXED )))
999 if (!(ptr = MapSL( MAKESEGPTR( ds, 0 ) )))
1000 ERR("ptr == NULL after GetBlock.\n");
1001 if (!(pInfo = LOCAL_GetHeap( ds )))
1002 ERR("pInfo == NULL after GetBlock.\n");
1004 /* Fill the entry table */
1006 *(WORD *)(ptr + handle) = pInfo->hdelta;
1007 pEntry = (LOCALHANDLEENTRY *)(ptr + handle + sizeof(WORD));
1008 for (i = pInfo->hdelta; i > 0; i--, pEntry++) {
1009 pEntry->lock = pEntry->flags = 0xff;
1012 *(WORD *)pEntry = pInfo->htable;
1013 pInfo->htable = handle;
1018 /***********************************************************************
1019 * LOCAL_GetNewHandleEntry
1021 static HLOCAL16 LOCAL_GetNewHandleEntry( HANDLE16 ds )
1023 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1024 LOCALHEAPINFO *pInfo;
1025 LOCALHANDLEENTRY *pEntry = NULL;
1028 if (!(pInfo = LOCAL_GetHeap( ds )))
1030 ERR("Local heap not found\n");
1031 LOCAL_PrintHeap(ds);
1035 /* Find a free slot in existing tables */
1037 table = pInfo->htable;
1040 WORD count = *(WORD *)(ptr + table);
1041 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
1042 for (; count > 0; count--, pEntry++)
1043 if (pEntry->lock == 0xff) break;
1045 table = *(WORD *)pEntry;
1048 if (!table) /* We need to create a new table */
1050 if (!LOCAL_NewHTable( ds )) return 0;
1051 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1052 pInfo = LOCAL_GetHeap( ds );
1053 pEntry = (LOCALHANDLEENTRY *)(ptr + pInfo->htable + sizeof(WORD));
1056 /* Now allocate this entry */
1060 TRACE("(%04x): %04x\n",
1061 ds, ((char *)pEntry - ptr) );
1062 return (HLOCAL16)((char *)pEntry - ptr);
1066 /***********************************************************************
1067 * LOCAL_FreeHandleEntry
1069 * Free a handle table entry.
1071 static void LOCAL_FreeHandleEntry( HANDLE16 ds, HLOCAL16 handle )
1073 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1074 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1075 LOCALHEAPINFO *pInfo;
1077 WORD table, count, i;
1079 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
1081 /* Find the table where this handle comes from */
1083 pTable = &pInfo->htable;
1086 WORD size = (*(WORD *)(ptr + *pTable)) * sizeof(LOCALHANDLEENTRY);
1087 if ((handle >= *pTable + sizeof(WORD)) &&
1088 (handle < *pTable + sizeof(WORD) + size)) break; /* Found it */
1089 pTable = (WORD *)(ptr + *pTable + sizeof(WORD) + size);
1093 ERR("Invalid entry %04x\n", handle);
1094 LOCAL_PrintHeap( ds );
1098 /* Make the entry free */
1100 pEntry->addr = 0; /* just in case */
1101 pEntry->lock = 0xff;
1102 pEntry->flags = 0xff;
1103 /* Now check if all entries in this table are free */
1106 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
1107 count = *(WORD *)(ptr + table);
1108 for (i = count; i > 0; i--, pEntry++) if (pEntry->lock != 0xff) return;
1110 /* Remove the table from the linked list and free it */
1112 TRACE("(%04x): freeing table %04x\n",
1114 *pTable = *(WORD *)pEntry;
1115 LOCAL_FreeArena( ds, ARENA_HEADER( table ) );
1119 /***********************************************************************
1122 * Implementation of LocalFree().
1124 HLOCAL16 LOCAL_Free( HANDLE16 ds, HLOCAL16 handle )
1126 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1128 TRACE("%04x ds=%04x\n", handle, ds );
1130 if (!handle) { WARN("Handle is 0.\n" ); return 0; }
1131 if (HANDLE_FIXED( handle ))
1133 if (!LOCAL_FreeArena( ds, ARENA_HEADER( handle ) )) return 0; /* OK */
1134 else return handle; /* couldn't free it */
1138 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1139 if (pEntry->flags != (LMEM_DISCARDED >> 8))
1141 TRACE("real block at %04x\n",
1143 if (LOCAL_FreeArena( ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX) ))
1144 return handle; /* couldn't free it */
1146 LOCAL_FreeHandleEntry( ds, handle );
1152 /***********************************************************************
1155 * Implementation of LocalAlloc().
1158 HLOCAL16 LOCAL_Alloc( HANDLE16 ds, WORD flags, WORD size )
1163 TRACE("%04x %d ds=%04x\n", flags, size, ds );
1165 if(size > 0 && size <= 4) size = 5;
1166 if (flags & LMEM_MOVEABLE)
1168 LOCALHANDLEENTRY *plhe;
1173 if (!(hmem = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags )))
1176 else /* We just need to allocate a discarded handle */
1178 if (!(handle = LOCAL_GetNewHandleEntry( ds )))
1180 WARN("Couldn't get handle.\n");
1182 LOCAL_FreeArena( ds, ARENA_HEADER(hmem) );
1185 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1186 plhe = (LOCALHANDLEENTRY *)(ptr + handle);
1190 plhe->addr = hmem + MOVEABLE_PREFIX;
1191 plhe->flags = (BYTE)((flags & 0x0f00) >> 8);
1192 *(HLOCAL16 *)(ptr + hmem) = handle;
1197 plhe->flags = LMEM_DISCARDED >> 8;
1204 handle = LOCAL_GetBlock( ds, size, flags );
1210 /***********************************************************************
1213 * Implementation of LocalReAlloc().
1215 HLOCAL16 LOCAL_ReAlloc( HANDLE16 ds, HLOCAL16 handle, WORD size, WORD flags )
1217 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1218 LOCALHEAPINFO *pInfo;
1219 LOCALARENA *pArena, *pNext;
1220 LOCALHANDLEENTRY *pEntry = NULL;
1221 WORD arena, oldsize;
1222 HLOCAL16 hmem, blockhandle;
1225 if (!handle) return 0;
1226 if(HANDLE_MOVEABLE(handle) &&
1227 ((LOCALHANDLEENTRY *)(ptr + handle))->lock == 0xff) /* An unused handle */
1230 TRACE("%04x %d %04x ds=%04x\n",
1231 handle, size, flags, ds );
1232 if (!(pInfo = LOCAL_GetHeap( ds ))) return 0;
1234 if (HANDLE_FIXED( handle ))
1235 blockhandle = handle;
1238 pEntry = (LOCALHANDLEENTRY *) (ptr + handle);
1239 if(pEntry->flags == (LMEM_DISCARDED >> 8))
1243 WARN("Dicarded block has non-zero addr.\n");
1244 TRACE("ReAllocating discarded block\n");
1245 if(size <= 4) size = 5;
1246 if (!(hl = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags)))
1248 ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */
1249 pEntry = (LOCALHANDLEENTRY *) (ptr + handle);
1250 pEntry->addr = hl + MOVEABLE_PREFIX;
1253 *(HLOCAL16 *)(ptr + hl) = handle;
1256 if (((blockhandle = pEntry->addr - MOVEABLE_PREFIX) & 3) != 0)
1258 ERR("(%04x,%04x): invalid handle\n",
1262 if (*(HLOCAL16 *)(ptr + blockhandle) != handle) {
1263 ERR("Back ptr to handle is invalid\n");
1268 if (flags & LMEM_MODIFY)
1270 if (HANDLE_MOVEABLE(handle))
1272 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1273 pEntry->flags = (flags & 0x0f00) >> 8;
1274 TRACE("Changing flags to %x.\n", pEntry->flags);
1281 if (flags & LMEM_MOVEABLE)
1283 if (HANDLE_FIXED(handle))
1285 TRACE("Freeing fixed block.\n");
1286 return LOCAL_Free( ds, handle );
1288 else /* Moveable block */
1290 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1291 if (pEntry->lock == 0)
1293 /* discards moveable blocks */
1294 TRACE("Discarding block\n");
1295 LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX));
1297 pEntry->flags = (LMEM_DISCARDED >> 8);
1305 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1306 if (pEntry->lock == 0)
1309 return LOCAL_Free( ds, handle );
1315 arena = ARENA_HEADER( blockhandle );
1316 TRACE("arena is %04x\n", arena );
1317 pArena = ARENA_PTR( ptr, arena );
1319 if(size <= 4) size = 5;
1320 if(HANDLE_MOVEABLE(handle)) size += MOVEABLE_PREFIX;
1321 oldsize = pArena->next - arena - ARENA_HEADER_SIZE;
1322 nextarena = LALIGN(blockhandle + size);
1324 /* Check for size reduction */
1326 if (nextarena <= pArena->next)
1328 TRACE("size reduction, making new free block\n");
1329 LOCAL_ShrinkArena(ds, arena, nextarena - arena);
1330 TRACE("returning %04x\n", handle );
1334 /* Check if the next block is free and large enough */
1336 pNext = ARENA_PTR( ptr, pArena->next );
1337 if (((pNext->prev & 3) == LOCAL_ARENA_FREE) &&
1338 (nextarena <= pNext->next))
1340 TRACE("size increase, making new free block\n");
1341 LOCAL_GrowArenaUpward(ds, arena, nextarena - arena);
1342 TRACE("returning %04x\n", handle );
1346 /* Now we have to allocate a new block, but not if (fixed block or locked
1347 block) and no LMEM_MOVEABLE */
1349 if (!(flags & LMEM_MOVEABLE))
1351 if (HANDLE_FIXED(handle))
1353 ERR("Needed to move fixed block, but LMEM_MOVEABLE not specified.\n");
1358 if(((LOCALHANDLEENTRY *)(ptr + handle))->lock != 0)
1360 ERR("Needed to move locked block, but LMEM_MOVEABLE not specified.\n");
1366 hmem = LOCAL_GetBlock( ds, size, flags );
1367 ptr = MapSL( MAKESEGPTR( ds, 0 )); /* Reload ptr */
1368 if(HANDLE_MOVEABLE(handle)) /* LOCAL_GetBlock might have triggered */
1369 { /* a compaction, which might in turn have */
1370 blockhandle = pEntry->addr - MOVEABLE_PREFIX; /* moved the very block we are resizing */
1371 arena = ARENA_HEADER( blockhandle ); /* thus, we reload arena, too */
1375 /* Remove the block from the heap and try again */
1376 LPSTR buffer = HeapAlloc( GetProcessHeap(), 0, oldsize );
1377 if (!buffer) return 0;
1378 memcpy( buffer, ptr + arena + ARENA_HEADER_SIZE, oldsize );
1379 LOCAL_FreeArena( ds, arena );
1380 if (!(hmem = LOCAL_GetBlock( ds, size, flags )))
1382 if (!(hmem = LOCAL_GetBlock( ds, oldsize, flags )))
1384 ERR("Can't restore saved block\n" );
1385 HeapFree( GetProcessHeap(), 0, buffer );
1390 ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */
1391 memcpy( ptr + hmem, buffer, oldsize );
1392 HeapFree( GetProcessHeap(), 0, buffer );
1396 memcpy( ptr + hmem, ptr + (arena + ARENA_HEADER_SIZE), oldsize );
1397 LOCAL_FreeArena( ds, arena );
1399 if (HANDLE_MOVEABLE( handle ))
1401 TRACE("fixing handle\n");
1402 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1403 pEntry->addr = hmem + MOVEABLE_PREFIX;
1404 /* Back ptr should still be correct */
1405 if(*(HLOCAL16 *)(ptr + hmem) != handle)
1406 ERR("back ptr is invalid.\n");
1409 if (size == oldsize) hmem = 0; /* Realloc failed */
1410 TRACE("returning %04x\n", hmem );
1415 /***********************************************************************
1416 * LOCAL_InternalLock
1418 static HLOCAL16 LOCAL_InternalLock( LPSTR heap, HLOCAL16 handle )
1420 HLOCAL16 old_handle = handle;
1422 if (HANDLE_MOVEABLE(handle))
1424 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(heap + handle);
1425 if (pEntry->flags == (LMEM_DISCARDED >> 8)) return 0;
1426 if (pEntry->lock < 0xfe) pEntry->lock++;
1427 handle = pEntry->addr;
1429 TRACE("%04x returning %04x\n",
1430 old_handle, handle );
1435 /***********************************************************************
1438 void *LOCAL_Lock( HANDLE16 ds, HLOCAL16 handle )
1440 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1441 return handle ? ptr + LOCAL_InternalLock( ptr, handle ) : NULL;
1445 /***********************************************************************
1448 BOOL16 LOCAL_Unlock( HANDLE16 ds, HLOCAL16 handle )
1450 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1452 TRACE("%04x\n", handle );
1453 if (HANDLE_MOVEABLE(handle))
1455 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1456 if (!pEntry->lock || (pEntry->lock == 0xff)) return FALSE;
1457 /* For moveable block, return the new lock count */
1458 /* (see _Windows_Internals_ p. 197) */
1459 return --pEntry->lock;
1465 /***********************************************************************
1468 * Implementation of LocalSize().
1470 WORD LOCAL_Size( HANDLE16 ds, HLOCAL16 handle )
1472 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1475 TRACE("%04x ds=%04x\n", handle, ds );
1477 if (!handle) return 0;
1478 if (HANDLE_MOVEABLE( handle ))
1480 handle = *(WORD *)(ptr + handle);
1481 if (!handle) return 0;
1482 pArena = ARENA_PTR( ptr, ARENA_HEADER(handle - MOVEABLE_PREFIX) );
1485 pArena = ARENA_PTR( ptr, ARENA_HEADER(handle) );
1487 return pArena->next - handle;
1491 /***********************************************************************
1494 * Implementation of LocalFlags().
1496 WORD LOCAL_Flags( HANDLE16 ds, HLOCAL16 handle )
1498 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1500 if (HANDLE_MOVEABLE(handle))
1502 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1503 TRACE("(%04x,%04x): returning %04x\n",
1504 ds, handle, pEntry->lock | (pEntry->flags << 8) );
1505 return pEntry->lock | (pEntry->flags << 8);
1509 TRACE("(%04x,%04x): returning 0\n",
1516 /***********************************************************************
1519 * Implementation of LocalHeapSize().
1521 WORD LOCAL_HeapSize( HANDLE16 ds )
1523 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
1524 if (!pInfo) return 0;
1525 return pInfo->last - pInfo->first;
1529 /***********************************************************************
1532 * Implementation of LocalCountFree().
1534 WORD LOCAL_CountFree( HANDLE16 ds )
1538 LOCALHEAPINFO *pInfo;
1539 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1541 if (!(pInfo = LOCAL_GetHeap( ds )))
1543 ERR("(%04x): Local heap not found\n", ds );
1544 LOCAL_PrintHeap( ds );
1549 arena = pInfo->first;
1550 pArena = ARENA_PTR( ptr, arena );
1553 arena = pArena->free_next;
1554 pArena = ARENA_PTR( ptr, arena );
1555 if (arena == pArena->free_next) break;
1556 total += pArena->size;
1558 TRACE("(%04x): returning %d\n", ds, total);
1563 /***********************************************************************
1566 * Implementation of LocalHandle().
1568 HLOCAL16 LOCAL_Handle( HANDLE16 ds, WORD addr )
1570 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1571 LOCALHEAPINFO *pInfo;
1574 if (!(pInfo = LOCAL_GetHeap( ds )))
1576 ERR("(%04x): Local heap not found\n", ds );
1577 LOCAL_PrintHeap( ds );
1581 /* Find the address in the entry tables */
1583 table = pInfo->htable;
1586 WORD count = *(WORD *)(ptr + table);
1587 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY*)(ptr+table+sizeof(WORD));
1588 for (; count > 0; count--, pEntry++)
1589 if (pEntry->addr == addr) return (HLOCAL16)((char *)pEntry - ptr);
1590 table = *(WORD *)pEntry;
1593 return (HLOCAL16)addr; /* Fixed block handle is addr */
1597 /***********************************************************************
1598 * LocalAlloc (KERNEL.5)
1600 HLOCAL16 WINAPI LocalAlloc16( UINT16 flags, WORD size )
1602 HLOCAL16 ret = LOCAL_Alloc( CURRENT_DS, flags, size );
1603 CURRENT_STACK16->ecx = ret; /* must be returned in cx too */
1608 /***********************************************************************
1609 * LocalReAlloc (KERNEL.6)
1611 HLOCAL16 WINAPI LocalReAlloc16( HLOCAL16 handle, WORD size, UINT16 flags )
1613 return LOCAL_ReAlloc( CURRENT_DS, handle, size, flags );
1617 /***********************************************************************
1618 * LocalFree (KERNEL.7)
1620 HLOCAL16 WINAPI LocalFree16( HLOCAL16 handle )
1622 return LOCAL_Free( CURRENT_DS, handle );
1626 /***********************************************************************
1627 * LocalLock (KERNEL.8)
1629 * Note: only the offset part of the pointer is returned by the relay code.
1631 SEGPTR WINAPI LocalLock16( HLOCAL16 handle )
1633 WORD ds = CURRENT_DS;
1634 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1635 return MAKESEGPTR( ds, LOCAL_InternalLock( ptr, handle ) );
1639 /***********************************************************************
1640 * LocalUnlock (KERNEL.9)
1642 BOOL16 WINAPI LocalUnlock16( HLOCAL16 handle )
1644 return LOCAL_Unlock( CURRENT_DS, handle );
1648 /***********************************************************************
1649 * LocalSize (KERNEL.10)
1651 UINT16 WINAPI LocalSize16( HLOCAL16 handle )
1653 return LOCAL_Size( CURRENT_DS, handle );
1657 /***********************************************************************
1658 * LocalHandle (KERNEL.11)
1660 HLOCAL16 WINAPI LocalHandle16( WORD addr )
1662 return LOCAL_Handle( CURRENT_DS, addr );
1666 /***********************************************************************
1667 * LocalFlags (KERNEL.12)
1669 UINT16 WINAPI LocalFlags16( HLOCAL16 handle )
1671 return LOCAL_Flags( CURRENT_DS, handle );
1675 /***********************************************************************
1676 * LocalCompact (KERNEL.13)
1678 UINT16 WINAPI LocalCompact16( UINT16 minfree )
1680 TRACE("%04x\n", minfree );
1681 return LOCAL_Compact( CURRENT_DS, minfree, 0 );
1685 /***********************************************************************
1686 * LocalNotify (KERNEL.14)
1688 * Installs a callback function that is called for local memory events
1689 * Callback function prototype is
1690 * BOOL16 NotifyFunc(WORD wMsg, HLOCAL16 hMem, WORD wArg)
1693 * NotifyFunc seems to be responsible for allocating some memory,
1694 * returns TRUE for success.
1695 * wArg = number of bytes needed additionally
1697 * hMem = handle; wArg = old mem location
1699 * NotifyFunc seems to be strongly encouraged to return TRUE,
1700 * otherwise LogError() gets called.
1701 * hMem = handle; wArg = flags
1703 FARPROC16 WINAPI LocalNotify16( FARPROC16 func )
1705 LOCALHEAPINFO *pInfo;
1706 FARPROC16 oldNotify;
1707 HANDLE16 ds = CURRENT_DS;
1709 if (!(pInfo = LOCAL_GetHeap( ds )))
1711 ERR("(%04x): Local heap not found\n", ds );
1712 LOCAL_PrintHeap( ds );
1715 TRACE("(%04x): %08lx\n", ds, (DWORD)func );
1716 FIXME("Half implemented\n");
1717 oldNotify = pInfo->notify;
1718 pInfo->notify = func;
1723 /***********************************************************************
1724 * LocalShrink (KERNEL.121)
1726 UINT16 WINAPI LocalShrink16( HGLOBAL16 handle, UINT16 newsize )
1728 TRACE("%04x %04x\n", handle, newsize );
1733 /***********************************************************************
1734 * GetHeapSpaces (KERNEL.138)
1736 DWORD WINAPI GetHeapSpaces16( HMODULE16 module )
1741 if (!(pModule = NE_GetPtr( module ))) return 0;
1743 GlobalHandleToSel16((NE_SEG_TABLE( pModule ) + pModule->dgroup - 1)->hSeg);
1744 return MAKELONG( LOCAL_CountFree( ds ), LOCAL_HeapSize( ds ) );
1748 /***********************************************************************
1749 * LocalCountFree (KERNEL.161)
1751 WORD WINAPI LocalCountFree16(void)
1753 return LOCAL_CountFree( CURRENT_DS );
1757 /***********************************************************************
1758 * LocalHeapSize (KERNEL.162)
1760 WORD WINAPI LocalHeapSize16(void)
1763 return LOCAL_HeapSize( CURRENT_DS );
1767 /***********************************************************************
1768 * LocalHandleDelta (KERNEL.310)
1770 WORD WINAPI LocalHandleDelta16( WORD delta )
1772 LOCALHEAPINFO *pInfo;
1774 if (!(pInfo = LOCAL_GetHeap( CURRENT_DS )))
1776 ERR("Local heap not found\n");
1777 LOCAL_PrintHeap( CURRENT_DS );
1780 if (delta) pInfo->hdelta = delta;
1781 TRACE("returning %04x\n", pInfo->hdelta);
1782 return pInfo->hdelta;
1786 /***********************************************************************
1787 * LocalInfo (TOOLHELP.56)
1789 BOOL16 WINAPI LocalInfo16( LOCALINFO *pLocalInfo, HGLOBAL16 handle )
1791 LOCALHEAPINFO *pInfo = LOCAL_GetHeap(SELECTOROF(K32WOWGlobalLock16(handle)));
1792 if (!pInfo) return FALSE;
1793 pLocalInfo->wcItems = pInfo->items;
1798 /***********************************************************************
1799 * LocalFirst (TOOLHELP.57)
1801 BOOL16 WINAPI LocalFirst16( LOCALENTRY *pLocalEntry, HGLOBAL16 handle )
1803 WORD ds = GlobalHandleToSel16( handle );
1804 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1805 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
1806 if (!pInfo) return FALSE;
1808 pLocalEntry->hHandle = pInfo->first + ARENA_HEADER_SIZE;
1809 pLocalEntry->wAddress = pLocalEntry->hHandle;
1810 pLocalEntry->wFlags = LF_FIXED;
1811 pLocalEntry->wcLock = 0;
1812 pLocalEntry->wType = LT_NORMAL;
1813 pLocalEntry->hHeap = handle;
1814 pLocalEntry->wHeapType = NORMAL_HEAP;
1815 pLocalEntry->wNext = ARENA_PTR(ptr,pInfo->first)->next;
1816 pLocalEntry->wSize = pLocalEntry->wNext - pLocalEntry->hHandle;
1821 /***********************************************************************
1822 * LocalNext (TOOLHELP.58)
1824 BOOL16 WINAPI LocalNext16( LOCALENTRY *pLocalEntry )
1826 WORD ds = GlobalHandleToSel16( pLocalEntry->hHeap );
1827 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1830 if (!LOCAL_GetHeap( ds )) return FALSE;
1831 if (!pLocalEntry->wNext) return FALSE;
1832 pArena = ARENA_PTR( ptr, pLocalEntry->wNext );
1834 pLocalEntry->hHandle = pLocalEntry->wNext + ARENA_HEADER_SIZE;
1835 pLocalEntry->wAddress = pLocalEntry->hHandle;
1836 pLocalEntry->wFlags = (pArena->prev & 3) + 1;
1837 pLocalEntry->wcLock = 0;
1838 pLocalEntry->wType = LT_NORMAL;
1839 if (pArena->next != pLocalEntry->wNext) /* last one? */
1840 pLocalEntry->wNext = pArena->next;
1842 pLocalEntry->wNext = 0;
1843 pLocalEntry->wSize = pLocalEntry->wNext - pLocalEntry->hHandle;
1848 /***********************************************************************
1849 * 32-bit local heap functions (Win95; undocumented)
1852 /***********************************************************************
1855 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1856 DWORD heapSize, DWORD flags )
1858 DWORD totSize, segSize = 0;
1860 LOCAL32HEADER *header;
1862 WORD *selectorTable;
1863 WORD selectorEven, selectorOdd;
1866 /* Determine new heap size */
1870 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1876 if ( heapSize == -1L )
1877 heapSize = 1024L*1024L; /* FIXME */
1879 heapSize = (heapSize + 0xffff) & 0xffff0000;
1880 segSize = (segSize + 0x0fff) & 0xfffff000;
1881 totSize = segSize + HTABLE_SIZE + heapSize;
1884 /* Allocate memory and initialize heap */
1886 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1889 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1890 MEM_COMMIT, PAGE_READWRITE ) )
1892 VirtualFree( base, 0, MEM_RELEASE );
1896 if (!(heap = RtlCreateHeap( 0, base + segSize + HTABLE_SIZE, heapSize, 0x10000, NULL, NULL )))
1898 VirtualFree( base, 0, MEM_RELEASE );
1903 /* Set up header and handle table */
1905 header = (LOCAL32HEADER *)(base + segSize);
1906 header->base = base;
1907 header->limit = HTABLE_PAGESIZE-1;
1909 header->magic = LOCAL32_MAGIC;
1910 header->heap = heap;
1912 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1913 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1914 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1916 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1917 *(DWORD *)((LPBYTE)header + i) = i+4;
1919 header->freeListFirst[1] = 0xffff;
1922 /* Set up selector table */
1924 nrBlocks = (totSize + 0x7fff) >> 15;
1925 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1926 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1927 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1928 if ( !selectorTable || !selectorEven || !selectorOdd )
1930 HeapFree( header->heap, 0, selectorTable );
1931 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1932 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1933 HeapDestroy( header->heap );
1934 VirtualFree( base, 0, MEM_RELEASE );
1938 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1939 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1940 header->selectorDelta = selectorEven - selectorOdd;
1941 header->segment = segment? segment : selectorEven;
1943 for (i = 0; i < nrBlocks; i++)
1944 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1945 : selectorEven + ((i >> 1) << __AHSHIFT);
1947 /* Move old segment */
1951 /* FIXME: This is somewhat ugly and relies on implementation
1952 details about 16-bit global memory handles ... */
1954 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1955 memcpy( base, oldBase, segSize );
1956 GLOBAL_MoveBlock( segment, base, totSize );
1957 HeapFree( GetProcessHeap(), 0, oldBase );
1960 return (HANDLE)header;
1963 /***********************************************************************
1964 * Local32_SearchHandle
1966 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1970 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1971 handle < (LPDWORD)((LPBYTE)header + header->limit);
1974 if (*handle == addr)
1981 /***********************************************************************
1984 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1985 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1992 case -2: /* 16:16 pointer, no handles */
1993 *ptr = MapSL( addr );
1994 *handle = (LPDWORD)*ptr;
1997 case -1: /* 32-bit offset, no handles */
1998 *ptr = header->base + addr;
1999 *handle = (LPDWORD)*ptr;
2002 case 0: /* handle */
2003 if ( addr >= sizeof(LOCAL32HEADER)
2004 && addr < header->limit && !(addr & 3)
2005 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
2007 *handle = (LPDWORD)((LPBYTE)header + addr);
2008 *ptr = header->base + **handle;
2012 case 1: /* 16:16 pointer */
2013 *ptr = MapSL( addr );
2014 *handle = Local32_SearchHandle( header, *ptr - header->base );
2017 case 2: /* 32-bit offset */
2018 *ptr = header->base + addr;
2019 *handle = Local32_SearchHandle( header, *ptr - header->base );
2024 /***********************************************************************
2025 * Local32_FromHandle
2027 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
2028 DWORD *addr, LPDWORD handle, LPBYTE ptr )
2032 case -2: /* 16:16 pointer */
2035 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
2036 DWORD offset = (LPBYTE)ptr - header->base;
2037 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
2041 case -1: /* 32-bit offset */
2043 *addr = ptr - header->base;
2046 case 0: /* handle */
2047 *addr = (LPBYTE)handle - (LPBYTE)header;
2052 /***********************************************************************
2055 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
2057 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2062 /* Allocate memory */
2063 ptr = HeapAlloc( header->heap,
2064 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
2068 /* Allocate handle if requested */
2073 /* Find first page of handle table with free slots */
2074 for (page = 0; page < HTABLE_NPAGES; page++)
2075 if (header->freeListFirst[page] != 0)
2077 if (page == HTABLE_NPAGES)
2079 WARN("Out of handles!\n" );
2080 HeapFree( header->heap, 0, ptr );
2084 /* If virgin page, initialize it */
2085 if (header->freeListFirst[page] == 0xffff)
2087 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
2088 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
2090 WARN("Cannot grow handle table!\n" );
2091 HeapFree( header->heap, 0, ptr );
2095 header->limit += HTABLE_PAGESIZE;
2097 header->freeListFirst[page] = 0;
2098 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
2099 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
2101 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
2102 *(DWORD *)((LPBYTE)header + i) = i+4;
2104 if (page < HTABLE_NPAGES-1)
2105 header->freeListFirst[page+1] = 0xffff;
2108 /* Allocate handle slot from page */
2109 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
2110 if (--header->freeListSize[page] == 0)
2111 header->freeListFirst[page] = header->freeListLast[page] = 0;
2113 header->freeListFirst[page] = *handle;
2115 /* Store 32-bit offset in handle slot */
2116 *handle = ptr - header->base;
2120 handle = (LPDWORD)ptr;
2125 /* Convert handle to requested output type */
2126 Local32_FromHandle( header, type, &addr, handle, ptr );
2130 /***********************************************************************
2133 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2134 DWORD size, DWORD flags )
2136 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2141 return Local32Alloc16( heap, size, type, flags );
2143 /* Retrieve handle and pointer */
2144 Local32_ToHandle( header, type, addr, &handle, &ptr );
2145 if (!handle) return FALSE;
2147 /* Reallocate memory block */
2148 ptr = HeapReAlloc( header->heap,
2149 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2155 *handle = ptr - header->base;
2157 handle = (LPDWORD)ptr;
2159 /* Convert handle to requested output type */
2160 Local32_FromHandle( header, type, &addr, handle, ptr );
2164 /***********************************************************************
2167 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2169 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2173 /* Retrieve handle and pointer */
2174 Local32_ToHandle( header, type, addr, &handle, &ptr );
2175 if (!handle) return FALSE;
2177 /* Free handle if necessary */
2180 int offset = (LPBYTE)handle - (LPBYTE)header;
2181 int page = offset >> 12;
2183 /* Return handle slot to page free list */
2184 if (header->freeListSize[page]++ == 0)
2185 header->freeListFirst[page] = header->freeListLast[page] = offset;
2187 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2188 header->freeListLast[page] = offset;
2192 /* Shrink handle table when possible */
2193 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2195 if ( VirtualFree( (LPBYTE)header +
2196 (header->limit & ~(HTABLE_PAGESIZE-1)),
2197 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2200 header->limit -= HTABLE_PAGESIZE;
2201 header->freeListFirst[page] = 0xffff;
2207 return HeapFree( header->heap, 0, ptr );
2210 /***********************************************************************
2213 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2215 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2219 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2220 if (!handle) return 0;
2222 Local32_FromHandle( header, type2, &addr, handle, ptr );
2226 /***********************************************************************
2229 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2231 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2235 Local32_ToHandle( header, type, addr, &handle, &ptr );
2236 if (!handle) return 0;
2238 return HeapSize( header->heap, 0, ptr );
2241 /***********************************************************************
2244 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2246 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2250 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2251 return handle != NULL;
2254 /***********************************************************************
2257 WORD WINAPI Local32GetSegment16( HANDLE heap )
2259 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2260 return header->segment;
2263 /***********************************************************************
2266 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2268 WORD selector = GlobalHandleToSel16( handle );
2269 DWORD base = GetSelectorBase( selector );
2270 DWORD limit = GetSelectorLimit16( selector );
2272 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2275 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2276 return (LOCAL32HEADER *)base;
2281 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2282 return (LOCAL32HEADER *)base;
2287 /***********************************************************************
2288 * Local32Info (KERNEL.444)
2289 * Local32Info (TOOLHELP.84)
2291 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2293 PROCESS_HEAP_ENTRY entry;
2296 LOCAL32HEADER *header = Local32_GetHeap( handle );
2297 if ( !header ) return FALSE;
2299 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2302 pLocal32Info->dwMemReserved = 0;
2303 pLocal32Info->dwMemCommitted = 0;
2304 pLocal32Info->dwTotalFree = 0;
2305 pLocal32Info->dwLargestFreeBlock = 0;
2307 while (HeapWalk( header->heap, &entry ))
2309 if (entry.wFlags & PROCESS_HEAP_REGION)
2311 pLocal32Info->dwMemReserved += entry.u.Region.dwCommittedSize
2312 + entry.u.Region.dwUnCommittedSize;
2313 pLocal32Info->dwMemCommitted = entry.u.Region.dwCommittedSize;
2315 else if (!(entry.wFlags & PROCESS_HEAP_ENTRY_BUSY))
2317 DWORD size = entry.cbData + entry.cbOverhead;
2318 pLocal32Info->dwTotalFree += size;
2319 if (size > pLocal32Info->dwLargestFreeBlock) pLocal32Info->dwLargestFreeBlock = size;
2323 pLocal32Info->dwcFreeHandles = 0;
2324 for ( i = 0; i < HTABLE_NPAGES; i++ )
2326 if ( header->freeListFirst[i] == 0xffff ) break;
2327 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2329 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2334 /***********************************************************************
2335 * Local32First (KERNEL.445)
2336 * Local32First (TOOLHELP.85)
2338 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2340 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2344 /***********************************************************************
2345 * Local32Next (KERNEL.446)
2346 * Local32Next (TOOLHELP.86)
2348 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2350 FIXME("(%p): stub!\n", pLocal32Entry );