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"
41 #include "stackframe.h"
43 #include "kernel_private.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(local);
51 WORD prev; /* Previous arena | arena type */
52 WORD next; /* Next arena */
53 /* Start of the memory block or free-list info */
54 WORD size; /* Size of the free block */
55 WORD free_prev; /* Previous free block */
56 WORD free_next; /* Next free block */
59 #define ARENA_HEADER_SIZE 4
60 #define ARENA_HEADER( handle) ((handle) - ARENA_HEADER_SIZE)
62 /* Arena types (stored in 'prev' field of the arena) */
63 #define LOCAL_ARENA_FREE 0
64 #define LOCAL_ARENA_FIXED 1
66 /* LocalNotify() msgs */
72 /* Layout of a handle entry table
74 * WORD count of entries
75 * LOCALHANDLEENTRY[count] entries
76 * WORD near ptr to next table
80 WORD addr; /* Address of the MOVEABLE block */
81 BYTE flags; /* Flags for this block */
82 BYTE lock; /* Lock count */
86 * We make addr = 4n + 2 and set *((WORD *)addr - 1) = &addr like Windows does
87 * in case something actually relies on this.
88 * Note that if the architecture does not allow unaligned accesses, we make
89 * addr = 4n + 4 to avoid returning unaligned pointers from LocalAlloc etc.
91 * An unused handle has lock = flags = 0xff. In windows addr is that of next
92 * free handle, at the moment in wine we set it to 0.
94 * A discarded block's handle has lock = addr = 0 and flags = 0x40
95 * (LMEM_DISCARDED >> 8)
98 #ifdef ALLOW_UNALIGNED_ACCESS
99 #define MOVEABLE_PREFIX sizeof(HLOCAL16)
101 #define MOVEABLE_PREFIX sizeof(int)
105 #include "pshpack1.h"
109 WORD check; /* 00 Heap checking flag */
110 WORD freeze; /* 02 Heap frozen flag */
111 WORD items; /* 04 Count of items on the heap */
112 WORD first; /* 06 First item of the heap */
113 WORD pad1; /* 08 Always 0 */
114 WORD last; /* 0a Last item of the heap */
115 WORD pad2; /* 0c Always 0 */
116 BYTE ncompact; /* 0e Compactions counter */
117 BYTE dislevel; /* 0f Discard level */
118 DWORD distotal; /* 10 Total bytes discarded */
119 WORD htable; /* 14 Pointer to handle table */
120 WORD hfree; /* 16 Pointer to free handle table */
121 WORD hdelta; /* 18 Delta to expand the handle table */
122 WORD expand; /* 1a Pointer to expand function (unused) */
123 WORD pstat; /* 1c Pointer to status structure (unused) */
124 FARPROC16 notify WINE_PACKED; /* 1e Pointer to LocalNotify() function */
125 WORD lock; /* 22 Lock count for the heap */
126 WORD extra; /* 24 Extra bytes to allocate when expanding */
127 WORD minsize; /* 26 Minimum size of the heap */
128 WORD magic; /* 28 Magic number */
133 #define LOCAL_HEAP_MAGIC 0x484c /* 'LH' */
135 /* All local heap allocations are aligned on 4-byte boundaries */
136 #define LALIGN(word) (((word) + 3) & ~3)
138 #define ARENA_PTR(ptr,arena) ((LOCALARENA *)((char*)(ptr)+(arena)))
139 #define ARENA_PREV(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & ~3)
140 #define ARENA_NEXT(ptr,arena) (ARENA_PTR((ptr),(arena))->next)
141 #define ARENA_FLAGS(ptr,arena) (ARENA_PTR((ptr),(arena))->prev & 3)
143 /* determine whether the handle belongs to a fixed or a moveable block */
144 #define HANDLE_FIXED(handle) (((handle) & 3) == 0)
145 #define HANDLE_MOVEABLE(handle) (((handle) & 3) == 2)
148 /* 32-bit heap definitions */
150 #define HTABLE_SIZE 0x10000
151 #define HTABLE_PAGESIZE 0x1000
152 #define HTABLE_NPAGES (HTABLE_SIZE / HTABLE_PAGESIZE)
154 #include "pshpack1.h"
155 typedef struct _LOCAL32HEADER
157 WORD freeListFirst[HTABLE_NPAGES];
158 WORD freeListSize[HTABLE_NPAGES];
159 WORD freeListLast[HTABLE_NPAGES];
161 DWORD selectorTableOffset;
162 WORD selectorTableSize;
177 #define LOCAL32_MAGIC ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
180 static inline BOOL16 call_notify_func( FARPROC16 proc, WORD msg, HLOCAL16 handle, WORD arg )
185 if (!proc) return FALSE;
189 WOWCallback16Ex( (DWORD)proc, WCB16_PASCAL, sizeof(args), args, &ret );
194 /***********************************************************************
197 * Return a pointer to the local heap, making sure it exists.
199 static LOCALHEAPINFO *LOCAL_GetHeap( HANDLE16 ds )
201 LOCALHEAPINFO *pInfo;
202 INSTANCEDATA *ptr = MapSL( MAKESEGPTR( ds, 0 ));
203 TRACE("Heap at %p, %04x\n", ptr, (ptr != NULL ? ptr->heap : 0xFFFF));
204 if (!ptr || !ptr->heap) return NULL;
205 if (IsBadReadPtr16( (SEGPTR)MAKELONG(ptr->heap,ds), sizeof(LOCALHEAPINFO)))
207 WARN("Bad pointer\n");
210 pInfo = (LOCALHEAPINFO*)((char*)ptr + ptr->heap);
211 if (pInfo->magic != LOCAL_HEAP_MAGIC)
220 /***********************************************************************
221 * LOCAL_MakeBlockFree
223 * Make a block free, inserting it in the free-list.
224 * 'block' is the handle of the block arena; 'baseptr' points to
225 * the beginning of the data segment containing the heap.
227 static void LOCAL_MakeBlockFree( char *baseptr, WORD block )
229 LOCALARENA *pArena, *pNext;
232 /* Mark the block as free */
234 pArena = ARENA_PTR( baseptr, block );
235 pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FREE;
236 pArena->size = pArena->next - block;
238 /* Find the next free block (last block is always free) */
243 pNext = ARENA_PTR( baseptr, next );
244 if ((pNext->prev & 3) == LOCAL_ARENA_FREE) break;
248 TRACE("%04x, next %04x\n", block, next );
249 /* Insert the free block in the free-list */
251 pArena->free_prev = pNext->free_prev;
252 pArena->free_next = next;
253 ARENA_PTR(baseptr,pNext->free_prev)->free_next = block;
254 pNext->free_prev = block;
258 /***********************************************************************
259 * LOCAL_RemoveFreeBlock
261 * Remove a block from the free-list.
262 * 'block' is the handle of the block arena; 'baseptr' points to
263 * the beginning of the data segment containing the heap.
265 static void LOCAL_RemoveFreeBlock( char *baseptr, WORD block )
267 /* Mark the block as fixed */
269 LOCALARENA *pArena = ARENA_PTR( baseptr, block );
270 pArena->prev = (pArena->prev & ~3) | LOCAL_ARENA_FIXED;
272 /* Remove it from the list */
274 ARENA_PTR(baseptr,pArena->free_prev)->free_next = pArena->free_next;
275 ARENA_PTR(baseptr,pArena->free_next)->free_prev = pArena->free_prev;
279 /***********************************************************************
282 * Insert a new block in the heap.
283 * 'new' is the handle of the new block arena; 'baseptr' points to
284 * the beginning of the data segment containing the heap; 'prev' is
285 * the block before the new one.
287 static void LOCAL_AddBlock( char *baseptr, WORD prev, WORD new )
289 LOCALARENA *pPrev = ARENA_PTR( baseptr, prev );
290 LOCALARENA *pNew = ARENA_PTR( baseptr, new );
292 pNew->prev = (prev & ~3) | LOCAL_ARENA_FIXED;
293 pNew->next = pPrev->next;
294 ARENA_PTR(baseptr,pPrev->next)->prev &= 3;
295 ARENA_PTR(baseptr,pPrev->next)->prev |= new;
300 /***********************************************************************
303 * Remove a block from the heap.
304 * 'block' is the handle of the block arena; 'baseptr' points to
305 * the beginning of the data segment containing the heap.
307 static void LOCAL_RemoveBlock( char *baseptr, WORD block )
309 LOCALARENA *pArena, *pTmp;
311 /* Remove the block from the free-list */
314 pArena = ARENA_PTR( baseptr, block );
315 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
316 LOCAL_RemoveFreeBlock( baseptr, block );
318 /* If the previous block is free, expand its size */
320 pTmp = ARENA_PTR( baseptr, pArena->prev & ~3 );
321 if ((pTmp->prev & 3) == LOCAL_ARENA_FREE)
322 pTmp->size += pArena->next - block;
324 /* Remove the block from the linked list */
326 pTmp->next = pArena->next;
327 pTmp = ARENA_PTR( baseptr, pArena->next );
328 pTmp->prev = (pTmp->prev & 3) | (pArena->prev & ~3);
332 /***********************************************************************
335 static void LOCAL_PrintHeap( HANDLE16 ds )
338 LOCALHEAPINFO *pInfo;
341 /* FIXME - the test should be done when calling the function!
342 plus is not clear that we should print this info
343 only when TRACE_ON is on! */
344 if(!TRACE_ON(local)) return;
346 ptr = MapSL( MAKESEGPTR( ds, 0 ));
347 pInfo = LOCAL_GetHeap( ds );
351 DPRINTF( "Local Heap corrupted! ds=%04x\n", ds );
354 DPRINTF( "Local Heap ds=%04x first=%04x last=%04x items=%d\n",
355 ds, pInfo->first, pInfo->last, pInfo->items );
357 arena = pInfo->first;
360 LOCALARENA *pArena = ARENA_PTR(ptr,arena);
361 DPRINTF( " %04x: prev=%04x next=%04x type=%d\n", arena,
362 pArena->prev & ~3, pArena->next, pArena->prev & 3 );
363 if (arena == pInfo->first)
365 DPRINTF( " size=%d free_prev=%04x free_next=%04x\n",
366 pArena->size, pArena->free_prev, pArena->free_next );
368 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
370 DPRINTF( " size=%d free_prev=%04x free_next=%04x\n",
371 pArena->size, pArena->free_prev, pArena->free_next );
372 if (pArena->next == arena) break; /* last one */
373 if (ARENA_PTR(ptr,pArena->free_next)->free_prev != arena)
375 DPRINTF( "*** arena->free_next->free_prev != arena\n" );
379 if (pArena->next == arena)
381 DPRINTF( "*** last block is not marked free\n" );
384 if ((ARENA_PTR(ptr,pArena->next)->prev & ~3) != arena)
386 DPRINTF( "*** arena->next->prev != arena (%04x, %04x)\n",
387 pArena->next, ARENA_PTR(ptr,pArena->next)->prev);
390 arena = pArena->next;
395 /***********************************************************************
396 * LocalInit (KERNEL.4)
398 BOOL16 WINAPI LocalInit16( HANDLE16 selector, WORD start, WORD end )
401 WORD heapInfoArena, freeArena, lastArena;
402 LOCALHEAPINFO *pHeapInfo;
403 LOCALARENA *pArena, *pFirstArena, *pLastArena;
406 /* The initial layout of the heap is: */
407 /* - first arena (FIXED) */
408 /* - heap info structure (FIXED) */
409 /* - large free block (FREE) */
410 /* - last arena (FREE) */
412 TRACE("%04x %04x-%04x\n", selector, start, end);
413 if (!selector) selector = CURRENT_DS;
417 /* If TRACE_ON(heap) is set, the global heap blocks are */
418 /* cleared before use, so we can test for double initialization. */
419 if (LOCAL_GetHeap(selector))
421 ERR("Heap %04x initialized twice.\n", selector);
422 LOCAL_PrintHeap(selector);
428 /* start == 0 means: put the local heap at the end of the segment */
430 DWORD size = GlobalSize16( GlobalHandle16( selector ) );
431 start = (WORD)(size > 0xffff ? 0xffff : size) - 1;
432 if ( end > 0xfffe ) end = 0xfffe;
436 ptr = MapSL( MAKESEGPTR( selector, 0 ) );
438 start = LALIGN( max( start, sizeof(INSTANCEDATA) ) );
439 heapInfoArena = LALIGN(start + sizeof(LOCALARENA) );
440 freeArena = LALIGN( heapInfoArena + ARENA_HEADER_SIZE
441 + sizeof(LOCALHEAPINFO) );
442 lastArena = (end - sizeof(LOCALARENA)) & ~3;
444 /* Make sure there's enough space. */
446 if (freeArena + sizeof(LOCALARENA) >= lastArena) goto done;
448 /* Initialise the first arena */
450 pFirstArena = ARENA_PTR( ptr, start );
451 pFirstArena->prev = start | LOCAL_ARENA_FIXED;
452 pFirstArena->next = heapInfoArena;
453 pFirstArena->size = LALIGN(sizeof(LOCALARENA));
454 pFirstArena->free_prev = start; /* this one */
455 pFirstArena->free_next = freeArena;
457 /* Initialise the arena of the heap info structure */
459 pArena = ARENA_PTR( ptr, heapInfoArena );
460 pArena->prev = start | LOCAL_ARENA_FIXED;
461 pArena->next = freeArena;
463 /* Initialise the heap info structure */
465 pHeapInfo = (LOCALHEAPINFO *) (ptr + heapInfoArena + ARENA_HEADER_SIZE );
466 memset( pHeapInfo, 0, sizeof(LOCALHEAPINFO) );
467 pHeapInfo->items = 4;
468 pHeapInfo->first = start;
469 pHeapInfo->last = lastArena;
470 pHeapInfo->htable = 0;
471 pHeapInfo->hdelta = 0x20;
472 pHeapInfo->extra = 0x200;
473 pHeapInfo->minsize = lastArena - freeArena;
474 pHeapInfo->magic = LOCAL_HEAP_MAGIC;
476 /* Initialise the large free block */
478 pArena = ARENA_PTR( ptr, freeArena );
479 pArena->prev = heapInfoArena | LOCAL_ARENA_FREE;
480 pArena->next = lastArena;
481 pArena->size = lastArena - freeArena;
482 pArena->free_prev = start;
483 pArena->free_next = lastArena;
485 /* Initialise the last block */
487 pLastArena = ARENA_PTR( ptr, lastArena );
488 pLastArena->prev = freeArena | LOCAL_ARENA_FREE;
489 pLastArena->next = lastArena; /* this one */
490 pLastArena->size = LALIGN(sizeof(LOCALARENA));
491 pLastArena->free_prev = freeArena;
492 pLastArena->free_next = lastArena; /* this one */
494 /* Store the local heap address in the instance data */
496 ((INSTANCEDATA *)ptr)->heap = heapInfoArena + ARENA_HEADER_SIZE;
497 LOCAL_PrintHeap( selector );
501 CURRENT_STACK16->ecx = ret; /* must be returned in cx too */
506 /***********************************************************************
509 static BOOL16 LOCAL_GrowHeap( HANDLE16 ds )
514 LOCALHEAPINFO *pHeapInfo;
515 WORD freeArena, lastArena;
516 LOCALARENA *pArena, *pLastArena;
519 hseg = GlobalHandle16( ds );
520 /* maybe mem allocated by Virtual*() ? */
521 if (!hseg) return FALSE;
523 oldsize = GlobalSize16( hseg );
524 /* if nothing can be gained, return */
525 if (oldsize > 0xfff0) return FALSE;
526 hseg = GlobalReAlloc16( hseg, 0x10000, GMEM_FIXED );
527 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
528 pHeapInfo = LOCAL_GetHeap( ds );
529 if (pHeapInfo == NULL) {
530 ERR("Heap not found\n" );
533 end = GlobalSize16( hseg );
534 lastArena = (end - sizeof(LOCALARENA)) & ~3;
536 /* Update the HeapInfo */
538 freeArena = pHeapInfo->last;
539 pHeapInfo->last = lastArena;
540 pHeapInfo->minsize += end - oldsize;
542 /* grow the old last block */
543 pArena = ARENA_PTR( ptr, freeArena );
544 pArena->size = lastArena - freeArena;
545 pArena->next = lastArena;
546 pArena->free_next = lastArena;
548 /* Initialise the new last block */
550 pLastArena = ARENA_PTR( ptr, lastArena );
551 pLastArena->prev = freeArena | LOCAL_ARENA_FREE;
552 pLastArena->next = lastArena; /* this one */
553 pLastArena->size = LALIGN(sizeof(LOCALARENA));
554 pLastArena->free_prev = freeArena;
555 pLastArena->free_next = lastArena; /* this one */
557 /* If block before freeArena is also free then merge them */
558 if((ARENA_PTR(ptr, (pArena->prev & ~3))->prev & 3) == LOCAL_ARENA_FREE)
560 LOCAL_RemoveBlock(ptr, freeArena);
564 TRACE("Heap expanded\n" );
565 LOCAL_PrintHeap( ds );
570 /***********************************************************************
573 static HLOCAL16 LOCAL_FreeArena( WORD ds, WORD arena )
575 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
576 LOCALHEAPINFO *pInfo;
577 LOCALARENA *pArena, *pPrev, *pNext;
579 TRACE("%04x ds=%04x\n", arena, ds );
580 if (!(pInfo = LOCAL_GetHeap( ds ))) return arena;
582 pArena = ARENA_PTR( ptr, arena );
583 if ((pArena->prev & 3) == LOCAL_ARENA_FREE)
585 /* shouldn't happen */
586 ERR("Trying to free block %04x twice!\n",
588 LOCAL_PrintHeap( ds );
592 /* Check if we can merge with the previous block */
594 pPrev = ARENA_PTR( ptr, pArena->prev & ~3 );
595 pNext = ARENA_PTR( ptr, pArena->next );
596 if ((pPrev->prev & 3) == LOCAL_ARENA_FREE)
598 arena = pArena->prev & ~3;
600 LOCAL_RemoveBlock( ptr, pPrev->next );
603 else /* Make a new free block */
605 LOCAL_MakeBlockFree( ptr, arena );
608 /* Check if we can merge with the next block */
610 if ((pArena->next == pArena->free_next) &&
611 (pArena->next != pInfo->last))
613 LOCAL_RemoveBlock( ptr, pArena->next );
620 /***********************************************************************
623 * Shrink an arena by creating a free block at its end if possible.
624 * 'size' includes the arena header, and must be aligned.
626 static void LOCAL_ShrinkArena( WORD ds, WORD arena, WORD size )
628 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
629 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
631 if (arena + size + LALIGN(sizeof(LOCALARENA)) < pArena->next)
633 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
635 LOCAL_AddBlock( ptr, arena, arena + size );
637 LOCAL_FreeArena( ds, arena + size );
642 /***********************************************************************
643 * LOCAL_GrowArenaDownward
645 * Grow an arena downward by using the previous arena (must be free).
647 static void LOCAL_GrowArenaDownward( WORD ds, WORD arena, WORD newsize )
649 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
650 LOCALHEAPINFO *pInfo;
651 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
652 WORD prevArena = pArena->prev & ~3;
653 LOCALARENA *pPrevArena = ARENA_PTR( ptr, prevArena );
657 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
658 offset = pPrevArena->size;
659 size = pArena->next - arena - ARENA_HEADER_SIZE;
660 LOCAL_RemoveFreeBlock( ptr, prevArena );
661 LOCAL_RemoveBlock( ptr, arena );
663 p = (char *)pPrevArena + ARENA_HEADER_SIZE;
664 while (offset < size)
666 memcpy( p, p + offset, offset );
670 if (size) memcpy( p, p + offset, size );
671 LOCAL_ShrinkArena( ds, prevArena, newsize );
676 /***********************************************************************
677 * LOCAL_GrowArenaUpward
679 * Grow an arena upward by using the next arena (must be free and big
680 * enough). Newsize includes the arena header and must be aligned.
682 static void LOCAL_GrowArenaUpward( WORD ds, WORD arena, WORD newsize )
684 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
685 LOCALHEAPINFO *pInfo;
686 LOCALARENA *pArena = ARENA_PTR( ptr, arena );
687 WORD nextArena = pArena->next;
689 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
690 LOCAL_RemoveBlock( ptr, nextArena );
692 LOCAL_ShrinkArena( ds, arena, newsize );
696 /***********************************************************************
699 static WORD LOCAL_GetFreeSpace(WORD ds, WORD countdiscard)
701 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
702 LOCALHEAPINFO *pInfo;
707 if (!(pInfo = LOCAL_GetHeap( ds )))
709 ERR("Local heap not found\n" );
713 arena = pInfo->first;
714 pArena = ARENA_PTR( ptr, arena );
715 while (arena != pArena->free_next)
717 arena = pArena->free_next;
718 pArena = ARENA_PTR( ptr, arena );
719 if (pArena->size >= freespace) freespace = pArena->size;
721 /* FIXME doesn't yet calculate space that would become free if everything
722 were discarded when countdiscard == 1 */
723 if (freespace < ARENA_HEADER_SIZE) freespace = 0;
724 else freespace -= ARENA_HEADER_SIZE;
729 /***********************************************************************
732 WORD LOCAL_Compact( HANDLE16 ds, UINT16 minfree, UINT16 flags )
734 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
735 LOCALHEAPINFO *pInfo;
736 LOCALARENA *pArena, *pMoveArena, *pFinalArena;
737 WORD arena, movearena, finalarena, table;
738 WORD count, movesize, size;
740 LOCALHANDLEENTRY *pEntry;
742 if (!(pInfo = LOCAL_GetHeap( ds )))
744 ERR("Local heap not found\n" );
748 TRACE("ds = %04x, minfree = %04x, flags = %04x\n",
750 freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1);
751 if(freespace >= minfree || (flags & LMEM_NOCOMPACT))
753 TRACE("Returning %04x.\n", freespace);
756 TRACE("Compacting heap %04x.\n", ds);
757 table = pInfo->htable;
760 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
761 for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++)
763 if((pEntry->lock == 0) && (pEntry->flags != (LMEM_DISCARDED >> 8)))
765 /* OK we can move this one if we want */
766 TRACE("handle %04x (block %04x) can be moved.\n",
767 (WORD)((char *)pEntry - ptr), pEntry->addr);
768 movearena = ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX);
769 pMoveArena = ARENA_PTR(ptr, movearena);
770 movesize = pMoveArena->next - movearena;
771 arena = pInfo->first;
772 pArena = ARENA_PTR(ptr, arena);
775 /* Try to find the smallest arena that will do, */
776 /* which is below us in memory */
779 arena = pArena->free_next;
780 pArena = ARENA_PTR(ptr, arena);
781 if(arena >= movearena)
783 if(arena == pArena->free_next)
785 if((pArena->size >= movesize) && (pArena->size < size))
791 if (finalarena) /* Actually got somewhere to move */
793 TRACE("Moving it to %04x.\n", finalarena);
794 pFinalArena = ARENA_PTR(ptr, finalarena);
795 size = pFinalArena->size;
796 LOCAL_RemoveFreeBlock(ptr, finalarena);
797 LOCAL_ShrinkArena( ds, finalarena, movesize );
798 /* Copy the arena to it's new location */
799 memcpy((char *)pFinalArena + ARENA_HEADER_SIZE,
800 (char *)pMoveArena + ARENA_HEADER_SIZE,
801 movesize - ARENA_HEADER_SIZE );
802 /* Free the old location */
803 LOCAL_FreeArena(ds, movearena);
804 call_notify_func(pInfo->notify, LN_MOVE,
805 (WORD)((char *)pEntry - ptr), pEntry->addr);
806 /* Update handle table entry */
807 pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX;
809 else if((ARENA_PTR(ptr, pMoveArena->prev & ~3)->prev & 3)
812 /* Previous arena is free (but < movesize) */
813 /* so we can 'slide' movearena down into it */
814 finalarena = pMoveArena->prev & ~3;
815 LOCAL_GrowArenaDownward( ds, movearena, movesize );
816 /* Update handle table entry */
817 pEntry->addr = finalarena + ARENA_HEADER_SIZE + MOVEABLE_PREFIX;
821 table = *(WORD *)pEntry;
823 freespace = LOCAL_GetFreeSpace(ds, minfree ? 0 : 1);
824 if(freespace >= minfree || (flags & LMEM_NODISCARD))
826 TRACE("Returning %04x.\n", freespace);
830 table = pInfo->htable;
833 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
834 for(count = *(WORD *)(ptr + table); count > 0; count--, pEntry++)
836 if(pEntry->addr && pEntry->lock == 0 &&
837 (pEntry->flags & (LMEM_DISCARDABLE >> 8)))
839 TRACE("Discarding handle %04x (block %04x).\n",
840 (char *)pEntry - ptr, pEntry->addr);
841 LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX));
842 call_notify_func(pInfo->notify, LN_DISCARD, (char *)pEntry - ptr, pEntry->flags);
844 pEntry->flags = (LMEM_DISCARDED >> 8);
847 table = *(WORD *)pEntry;
849 return LOCAL_Compact(ds, 0xffff, LMEM_NODISCARD);
853 /***********************************************************************
854 * LOCAL_FindFreeBlock
856 static HLOCAL16 LOCAL_FindFreeBlock( HANDLE16 ds, WORD size )
858 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
859 LOCALHEAPINFO *pInfo;
863 if (!(pInfo = LOCAL_GetHeap( ds )))
865 ERR("Local heap not found\n" );
870 arena = pInfo->first;
871 pArena = ARENA_PTR( ptr, arena );
873 arena = pArena->free_next;
874 pArena = ARENA_PTR( ptr, arena );
875 if (arena == pArena->free_next) break;
876 if (pArena->size >= size) return arena;
878 TRACE("not enough space\n" );
884 /***********************************************************************
887 static const char *get_heap_name( WORD ds )
889 HINSTANCE16 inst = LoadLibrary16( "GDI" );
890 if (ds == GlobalHandleToSel16( inst ))
892 FreeLibrary16( inst );
895 FreeLibrary16( inst );
896 inst = LoadLibrary16( "USER" );
897 if (ds == GlobalHandleToSel16( inst ))
899 FreeLibrary16( inst );
902 FreeLibrary16( inst );
906 /***********************************************************************
908 * The segment may get moved around in this function, so all callers
909 * should reset their pointer variables.
911 static HLOCAL16 LOCAL_GetBlock( HANDLE16 ds, WORD size, WORD flags )
913 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
914 LOCALHEAPINFO *pInfo;
918 if (!(pInfo = LOCAL_GetHeap( ds )))
920 ERR("Local heap not found\n");
925 size += ARENA_HEADER_SIZE;
926 size = LALIGN( max( size, sizeof(LOCALARENA) ) );
931 /* Find a suitable free block */
932 arena = LOCAL_FindFreeBlock( ds, size );
934 /* no space: try to make some */
935 LOCAL_Compact( ds, size, flags );
936 arena = LOCAL_FindFreeBlock( ds, size );
939 /* still no space: try to grow the segment */
940 if (!(LOCAL_GrowHeap( ds )))
943 /* FIXME: doesn't work correctly yet */
944 if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds - 20, size)) /* FIXME: "size" correct ? (should indicate bytes needed) */
947 ERR( "not enough space in %s heap %04x for %d bytes\n",
948 get_heap_name(ds), ds, size );
951 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
952 pInfo = LOCAL_GetHeap( ds );
953 arena = LOCAL_FindFreeBlock( ds, size );
956 ERR( "not enough space in %s heap %04x for %d bytes\n",
957 get_heap_name(ds), ds, size );
959 /* FIXME: "size" correct ? (should indicate bytes needed) */
960 if (call_notify_func(pInfo->notify, LN_OUTOFMEM, ds, size)) goto notify_done;
965 /* Make a block out of the free arena */
966 pArena = ARENA_PTR( ptr, arena );
967 TRACE("size = %04x, arena %04x size %04x\n",
968 size, arena, pArena->size );
969 LOCAL_RemoveFreeBlock( ptr, arena );
970 LOCAL_ShrinkArena( ds, arena, size );
972 if (flags & LMEM_ZEROINIT)
973 memset((char *)pArena + ARENA_HEADER_SIZE, 0, size-ARENA_HEADER_SIZE);
974 return arena + ARENA_HEADER_SIZE;
978 /***********************************************************************
981 static BOOL16 LOCAL_NewHTable( HANDLE16 ds )
983 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
984 LOCALHEAPINFO *pInfo;
985 LOCALHANDLEENTRY *pEntry;
990 if (!(pInfo = LOCAL_GetHeap( ds )))
992 ERR("Local heap not found\n");
997 if (!(handle = LOCAL_GetBlock( ds, pInfo->hdelta * sizeof(LOCALHANDLEENTRY)
998 + 2 * sizeof(WORD), LMEM_FIXED )))
1000 if (!(ptr = MapSL( MAKESEGPTR( ds, 0 ) )))
1001 ERR("ptr == NULL after GetBlock.\n");
1002 if (!(pInfo = LOCAL_GetHeap( ds )))
1003 ERR("pInfo == NULL after GetBlock.\n");
1005 /* Fill the entry table */
1007 *(WORD *)(ptr + handle) = pInfo->hdelta;
1008 pEntry = (LOCALHANDLEENTRY *)(ptr + handle + sizeof(WORD));
1009 for (i = pInfo->hdelta; i > 0; i--, pEntry++) {
1010 pEntry->lock = pEntry->flags = 0xff;
1013 *(WORD *)pEntry = pInfo->htable;
1014 pInfo->htable = handle;
1019 /***********************************************************************
1020 * LOCAL_GetNewHandleEntry
1022 static HLOCAL16 LOCAL_GetNewHandleEntry( HANDLE16 ds )
1024 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1025 LOCALHEAPINFO *pInfo;
1026 LOCALHANDLEENTRY *pEntry = NULL;
1029 if (!(pInfo = LOCAL_GetHeap( ds )))
1031 ERR("Local heap not found\n");
1032 LOCAL_PrintHeap(ds);
1036 /* Find a free slot in existing tables */
1038 table = pInfo->htable;
1041 WORD count = *(WORD *)(ptr + table);
1042 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
1043 for (; count > 0; count--, pEntry++)
1044 if (pEntry->lock == 0xff) break;
1046 table = *(WORD *)pEntry;
1049 if (!table) /* We need to create a new table */
1051 if (!LOCAL_NewHTable( ds )) return 0;
1052 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1053 pInfo = LOCAL_GetHeap( ds );
1054 pEntry = (LOCALHANDLEENTRY *)(ptr + pInfo->htable + sizeof(WORD));
1057 /* Now allocate this entry */
1061 TRACE("(%04x): %04x\n",
1062 ds, ((char *)pEntry - ptr) );
1063 return (HLOCAL16)((char *)pEntry - ptr);
1067 /***********************************************************************
1068 * LOCAL_FreeHandleEntry
1070 * Free a handle table entry.
1072 static void LOCAL_FreeHandleEntry( HANDLE16 ds, HLOCAL16 handle )
1074 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1075 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1076 LOCALHEAPINFO *pInfo;
1078 WORD table, count, i;
1080 if (!(pInfo = LOCAL_GetHeap( ds ))) return;
1082 /* Find the table where this handle comes from */
1084 pTable = &pInfo->htable;
1087 WORD size = (*(WORD *)(ptr + *pTable)) * sizeof(LOCALHANDLEENTRY);
1088 if ((handle >= *pTable + sizeof(WORD)) &&
1089 (handle < *pTable + sizeof(WORD) + size)) break; /* Found it */
1090 pTable = (WORD *)(ptr + *pTable + sizeof(WORD) + size);
1094 ERR("Invalid entry %04x\n", handle);
1095 LOCAL_PrintHeap( ds );
1099 /* Make the entry free */
1101 pEntry->addr = 0; /* just in case */
1102 pEntry->lock = 0xff;
1103 pEntry->flags = 0xff;
1104 /* Now check if all entries in this table are free */
1107 pEntry = (LOCALHANDLEENTRY *)(ptr + table + sizeof(WORD));
1108 count = *(WORD *)(ptr + table);
1109 for (i = count; i > 0; i--, pEntry++) if (pEntry->lock != 0xff) return;
1111 /* Remove the table from the linked list and free it */
1113 TRACE("(%04x): freeing table %04x\n",
1115 *pTable = *(WORD *)pEntry;
1116 LOCAL_FreeArena( ds, ARENA_HEADER( table ) );
1120 /***********************************************************************
1123 * Implementation of LocalFree().
1125 HLOCAL16 LOCAL_Free( HANDLE16 ds, HLOCAL16 handle )
1127 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1129 TRACE("%04x ds=%04x\n", handle, ds );
1131 if (!handle) { WARN("Handle is 0.\n" ); return 0; }
1132 if (HANDLE_FIXED( handle ))
1134 if (!LOCAL_FreeArena( ds, ARENA_HEADER( handle ) )) return 0; /* OK */
1135 else return handle; /* couldn't free it */
1139 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1140 if (pEntry->flags != (LMEM_DISCARDED >> 8))
1142 TRACE("real block at %04x\n",
1144 if (LOCAL_FreeArena( ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX) ))
1145 return handle; /* couldn't free it */
1147 LOCAL_FreeHandleEntry( ds, handle );
1153 /***********************************************************************
1156 * Implementation of LocalAlloc().
1159 HLOCAL16 LOCAL_Alloc( HANDLE16 ds, WORD flags, WORD size )
1164 TRACE("%04x %d ds=%04x\n", flags, size, ds );
1166 if(size > 0 && size <= 4) size = 5;
1167 if (flags & LMEM_MOVEABLE)
1169 LOCALHANDLEENTRY *plhe;
1174 if (!(hmem = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags )))
1177 else /* We just need to allocate a discarded handle */
1179 if (!(handle = LOCAL_GetNewHandleEntry( ds )))
1181 WARN("Couldn't get handle.\n");
1183 LOCAL_FreeArena( ds, ARENA_HEADER(hmem) );
1186 ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1187 plhe = (LOCALHANDLEENTRY *)(ptr + handle);
1191 plhe->addr = hmem + MOVEABLE_PREFIX;
1192 plhe->flags = (BYTE)((flags & 0x0f00) >> 8);
1193 *(HLOCAL16 *)(ptr + hmem) = handle;
1198 plhe->flags = LMEM_DISCARDED >> 8;
1205 handle = LOCAL_GetBlock( ds, size, flags );
1211 /***********************************************************************
1214 * Implementation of LocalReAlloc().
1216 HLOCAL16 LOCAL_ReAlloc( HANDLE16 ds, HLOCAL16 handle, WORD size, WORD flags )
1218 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1219 LOCALHEAPINFO *pInfo;
1220 LOCALARENA *pArena, *pNext;
1221 LOCALHANDLEENTRY *pEntry = NULL;
1222 WORD arena, oldsize;
1223 HLOCAL16 hmem, blockhandle;
1226 if (!handle) return 0;
1227 if(HANDLE_MOVEABLE(handle) &&
1228 ((LOCALHANDLEENTRY *)(ptr + handle))->lock == 0xff) /* An unused handle */
1231 TRACE("%04x %d %04x ds=%04x\n",
1232 handle, size, flags, ds );
1233 if (!(pInfo = LOCAL_GetHeap( ds ))) return 0;
1235 if (HANDLE_FIXED( handle ))
1236 blockhandle = handle;
1239 pEntry = (LOCALHANDLEENTRY *) (ptr + handle);
1240 if(pEntry->flags == (LMEM_DISCARDED >> 8))
1244 WARN("Dicarded block has non-zero addr.\n");
1245 TRACE("ReAllocating discarded block\n");
1246 if(size <= 4) size = 5;
1247 if (!(hl = LOCAL_GetBlock( ds, size + MOVEABLE_PREFIX, flags)))
1249 ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */
1250 pEntry = (LOCALHANDLEENTRY *) (ptr + handle);
1251 pEntry->addr = hl + MOVEABLE_PREFIX;
1254 *(HLOCAL16 *)(ptr + hl) = handle;
1257 if (((blockhandle = pEntry->addr - MOVEABLE_PREFIX) & 3) != 0)
1259 ERR("(%04x,%04x): invalid handle\n",
1263 if (*(HLOCAL16 *)(ptr + blockhandle) != handle) {
1264 ERR("Back ptr to handle is invalid\n");
1269 if (flags & LMEM_MODIFY)
1271 if (HANDLE_MOVEABLE(handle))
1273 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1274 pEntry->flags = (flags & 0x0f00) >> 8;
1275 TRACE("Changing flags to %x.\n", pEntry->flags);
1282 if (flags & LMEM_MOVEABLE)
1284 if (HANDLE_FIXED(handle))
1286 TRACE("Freeing fixed block.\n");
1287 return LOCAL_Free( ds, handle );
1289 else /* Moveable block */
1291 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1292 if (pEntry->lock == 0)
1294 /* discards moveable blocks */
1295 TRACE("Discarding block\n");
1296 LOCAL_FreeArena(ds, ARENA_HEADER(pEntry->addr - MOVEABLE_PREFIX));
1298 pEntry->flags = (LMEM_DISCARDED >> 8);
1306 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1307 if (pEntry->lock == 0)
1310 return LOCAL_Free( ds, handle );
1316 arena = ARENA_HEADER( blockhandle );
1317 TRACE("arena is %04x\n", arena );
1318 pArena = ARENA_PTR( ptr, arena );
1320 if(size <= 4) size = 5;
1321 if(HANDLE_MOVEABLE(handle)) size += MOVEABLE_PREFIX;
1322 oldsize = pArena->next - arena - ARENA_HEADER_SIZE;
1323 nextarena = LALIGN(blockhandle + size);
1325 /* Check for size reduction */
1327 if (nextarena <= pArena->next)
1329 TRACE("size reduction, making new free block\n");
1330 LOCAL_ShrinkArena(ds, arena, nextarena - arena);
1331 TRACE("returning %04x\n", handle );
1335 /* Check if the next block is free and large enough */
1337 pNext = ARENA_PTR( ptr, pArena->next );
1338 if (((pNext->prev & 3) == LOCAL_ARENA_FREE) &&
1339 (nextarena <= pNext->next))
1341 TRACE("size increase, making new free block\n");
1342 LOCAL_GrowArenaUpward(ds, arena, nextarena - arena);
1343 TRACE("returning %04x\n", handle );
1347 /* Now we have to allocate a new block, but not if (fixed block or locked
1348 block) and no LMEM_MOVEABLE */
1350 if (!(flags & LMEM_MOVEABLE))
1352 if (HANDLE_FIXED(handle))
1354 ERR("Needed to move fixed block, but LMEM_MOVEABLE not specified.\n");
1359 if(((LOCALHANDLEENTRY *)(ptr + handle))->lock != 0)
1361 ERR("Needed to move locked block, but LMEM_MOVEABLE not specified.\n");
1367 hmem = LOCAL_GetBlock( ds, size, flags );
1368 ptr = MapSL( MAKESEGPTR( ds, 0 )); /* Reload ptr */
1369 if(HANDLE_MOVEABLE(handle)) /* LOCAL_GetBlock might have triggered */
1370 { /* a compaction, which might in turn have */
1371 blockhandle = pEntry->addr - MOVEABLE_PREFIX; /* moved the very block we are resizing */
1372 arena = ARENA_HEADER( blockhandle ); /* thus, we reload arena, too */
1376 /* Remove the block from the heap and try again */
1377 LPSTR buffer = HeapAlloc( GetProcessHeap(), 0, oldsize );
1378 if (!buffer) return 0;
1379 memcpy( buffer, ptr + arena + ARENA_HEADER_SIZE, oldsize );
1380 LOCAL_FreeArena( ds, arena );
1381 if (!(hmem = LOCAL_GetBlock( ds, size, flags )))
1383 if (!(hmem = LOCAL_GetBlock( ds, oldsize, flags )))
1385 ERR("Can't restore saved block\n" );
1386 HeapFree( GetProcessHeap(), 0, buffer );
1391 ptr = MapSL( MAKESEGPTR( ds, 0 ) ); /* Reload ptr */
1392 memcpy( ptr + hmem, buffer, oldsize );
1393 HeapFree( GetProcessHeap(), 0, buffer );
1397 memcpy( ptr + hmem, ptr + (arena + ARENA_HEADER_SIZE), oldsize );
1398 LOCAL_FreeArena( ds, arena );
1400 if (HANDLE_MOVEABLE( handle ))
1402 TRACE("fixing handle\n");
1403 pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1404 pEntry->addr = hmem + MOVEABLE_PREFIX;
1405 /* Back ptr should still be correct */
1406 if(*(HLOCAL16 *)(ptr + hmem) != handle)
1407 ERR("back ptr is invalid.\n");
1410 if (size == oldsize) hmem = 0; /* Realloc failed */
1411 TRACE("returning %04x\n", hmem );
1416 /***********************************************************************
1417 * LOCAL_InternalLock
1419 static HLOCAL16 LOCAL_InternalLock( LPSTR heap, HLOCAL16 handle )
1421 HLOCAL16 old_handle = handle;
1423 if (HANDLE_MOVEABLE(handle))
1425 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(heap + handle);
1426 if (pEntry->flags == (LMEM_DISCARDED >> 8)) return 0;
1427 if (pEntry->lock < 0xfe) pEntry->lock++;
1428 handle = pEntry->addr;
1430 TRACE("%04x returning %04x\n",
1431 old_handle, handle );
1436 /***********************************************************************
1439 void *LOCAL_Lock( HANDLE16 ds, HLOCAL16 handle )
1441 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1442 return handle ? ptr + LOCAL_InternalLock( ptr, handle ) : NULL;
1446 /***********************************************************************
1449 BOOL16 LOCAL_Unlock( HANDLE16 ds, HLOCAL16 handle )
1451 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1453 TRACE("%04x\n", handle );
1454 if (HANDLE_MOVEABLE(handle))
1456 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1457 if (!pEntry->lock || (pEntry->lock == 0xff)) return FALSE;
1458 /* For moveable block, return the new lock count */
1459 /* (see _Windows_Internals_ p. 197) */
1460 return --pEntry->lock;
1466 /***********************************************************************
1469 * Implementation of LocalSize().
1471 WORD LOCAL_Size( HANDLE16 ds, HLOCAL16 handle )
1473 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1476 TRACE("%04x ds=%04x\n", handle, ds );
1478 if (!handle) return 0;
1479 if (HANDLE_MOVEABLE( handle ))
1481 handle = *(WORD *)(ptr + handle);
1482 if (!handle) return 0;
1483 pArena = ARENA_PTR( ptr, ARENA_HEADER(handle - MOVEABLE_PREFIX) );
1486 pArena = ARENA_PTR( ptr, ARENA_HEADER(handle) );
1488 return pArena->next - handle;
1492 /***********************************************************************
1495 * Implementation of LocalFlags().
1497 WORD LOCAL_Flags( HANDLE16 ds, HLOCAL16 handle )
1499 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1501 if (HANDLE_MOVEABLE(handle))
1503 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY *)(ptr + handle);
1504 TRACE("(%04x,%04x): returning %04x\n",
1505 ds, handle, pEntry->lock | (pEntry->flags << 8) );
1506 return pEntry->lock | (pEntry->flags << 8);
1510 TRACE("(%04x,%04x): returning 0\n",
1517 /***********************************************************************
1520 * Implementation of LocalHeapSize().
1522 WORD LOCAL_HeapSize( HANDLE16 ds )
1524 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
1525 if (!pInfo) return 0;
1526 return pInfo->last - pInfo->first;
1530 /***********************************************************************
1533 * Implementation of LocalCountFree().
1535 WORD LOCAL_CountFree( HANDLE16 ds )
1539 LOCALHEAPINFO *pInfo;
1540 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1542 if (!(pInfo = LOCAL_GetHeap( ds )))
1544 ERR("(%04x): Local heap not found\n", ds );
1545 LOCAL_PrintHeap( ds );
1550 arena = pInfo->first;
1551 pArena = ARENA_PTR( ptr, arena );
1554 arena = pArena->free_next;
1555 pArena = ARENA_PTR( ptr, arena );
1556 if (arena == pArena->free_next) break;
1557 total += pArena->size;
1559 TRACE("(%04x): returning %d\n", ds, total);
1564 /***********************************************************************
1567 * Implementation of LocalHandle().
1569 HLOCAL16 LOCAL_Handle( HANDLE16 ds, WORD addr )
1571 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1572 LOCALHEAPINFO *pInfo;
1575 if (!(pInfo = LOCAL_GetHeap( ds )))
1577 ERR("(%04x): Local heap not found\n", ds );
1578 LOCAL_PrintHeap( ds );
1582 /* Find the address in the entry tables */
1584 table = pInfo->htable;
1587 WORD count = *(WORD *)(ptr + table);
1588 LOCALHANDLEENTRY *pEntry = (LOCALHANDLEENTRY*)(ptr+table+sizeof(WORD));
1589 for (; count > 0; count--, pEntry++)
1590 if (pEntry->addr == addr) return (HLOCAL16)((char *)pEntry - ptr);
1591 table = *(WORD *)pEntry;
1594 return (HLOCAL16)addr; /* Fixed block handle is addr */
1598 /***********************************************************************
1599 * LocalAlloc (KERNEL.5)
1601 HLOCAL16 WINAPI LocalAlloc16( UINT16 flags, WORD size )
1603 HLOCAL16 ret = LOCAL_Alloc( CURRENT_DS, flags, size );
1604 CURRENT_STACK16->ecx = ret; /* must be returned in cx too */
1609 /***********************************************************************
1610 * LocalReAlloc (KERNEL.6)
1612 HLOCAL16 WINAPI LocalReAlloc16( HLOCAL16 handle, WORD size, UINT16 flags )
1614 return LOCAL_ReAlloc( CURRENT_DS, handle, size, flags );
1618 /***********************************************************************
1619 * LocalFree (KERNEL.7)
1621 HLOCAL16 WINAPI LocalFree16( HLOCAL16 handle )
1623 return LOCAL_Free( CURRENT_DS, handle );
1627 /***********************************************************************
1628 * LocalLock (KERNEL.8)
1630 * Note: only the offset part of the pointer is returned by the relay code.
1632 SEGPTR WINAPI LocalLock16( HLOCAL16 handle )
1634 WORD ds = CURRENT_DS;
1635 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1636 return MAKESEGPTR( ds, LOCAL_InternalLock( ptr, handle ) );
1640 /***********************************************************************
1641 * LocalUnlock (KERNEL.9)
1643 BOOL16 WINAPI LocalUnlock16( HLOCAL16 handle )
1645 return LOCAL_Unlock( CURRENT_DS, handle );
1649 /***********************************************************************
1650 * LocalSize (KERNEL.10)
1652 UINT16 WINAPI LocalSize16( HLOCAL16 handle )
1654 return LOCAL_Size( CURRENT_DS, handle );
1658 /***********************************************************************
1659 * LocalHandle (KERNEL.11)
1661 HLOCAL16 WINAPI LocalHandle16( WORD addr )
1663 return LOCAL_Handle( CURRENT_DS, addr );
1667 /***********************************************************************
1668 * LocalFlags (KERNEL.12)
1670 UINT16 WINAPI LocalFlags16( HLOCAL16 handle )
1672 return LOCAL_Flags( CURRENT_DS, handle );
1676 /***********************************************************************
1677 * LocalCompact (KERNEL.13)
1679 UINT16 WINAPI LocalCompact16( UINT16 minfree )
1681 TRACE("%04x\n", minfree );
1682 return LOCAL_Compact( CURRENT_DS, minfree, 0 );
1686 /***********************************************************************
1687 * LocalNotify (KERNEL.14)
1689 * Installs a callback function that is called for local memory events
1690 * Callback function prototype is
1691 * BOOL16 NotifyFunc(WORD wMsg, HLOCAL16 hMem, WORD wArg)
1694 * NotifyFunc seems to be responsible for allocating some memory,
1695 * returns TRUE for success.
1696 * wArg = number of bytes needed additionally
1698 * hMem = handle; wArg = old mem location
1700 * NotifyFunc seems to be strongly encouraged to return TRUE,
1701 * otherwise LogError() gets called.
1702 * hMem = handle; wArg = flags
1704 FARPROC16 WINAPI LocalNotify16( FARPROC16 func )
1706 LOCALHEAPINFO *pInfo;
1707 FARPROC16 oldNotify;
1708 HANDLE16 ds = CURRENT_DS;
1710 if (!(pInfo = LOCAL_GetHeap( ds )))
1712 ERR("(%04x): Local heap not found\n", ds );
1713 LOCAL_PrintHeap( ds );
1716 TRACE("(%04x): %08lx\n", ds, (DWORD)func );
1717 FIXME("Half implemented\n");
1718 oldNotify = pInfo->notify;
1719 pInfo->notify = func;
1724 /***********************************************************************
1725 * LocalShrink (KERNEL.121)
1727 UINT16 WINAPI LocalShrink16( HGLOBAL16 handle, UINT16 newsize )
1729 TRACE("%04x %04x\n", handle, newsize );
1734 /***********************************************************************
1735 * GetHeapSpaces (KERNEL.138)
1737 DWORD WINAPI GetHeapSpaces16( HMODULE16 module )
1742 if (!(pModule = NE_GetPtr( module ))) return 0;
1744 GlobalHandleToSel16((NE_SEG_TABLE( pModule ) + pModule->dgroup - 1)->hSeg);
1745 return MAKELONG( LOCAL_CountFree( ds ), LOCAL_HeapSize( ds ) );
1749 /***********************************************************************
1750 * LocalCountFree (KERNEL.161)
1752 WORD WINAPI LocalCountFree16(void)
1754 return LOCAL_CountFree( CURRENT_DS );
1758 /***********************************************************************
1759 * LocalHeapSize (KERNEL.162)
1761 WORD WINAPI LocalHeapSize16(void)
1764 return LOCAL_HeapSize( CURRENT_DS );
1768 /***********************************************************************
1769 * LocalHandleDelta (KERNEL.310)
1771 WORD WINAPI LocalHandleDelta16( WORD delta )
1773 LOCALHEAPINFO *pInfo;
1775 if (!(pInfo = LOCAL_GetHeap( CURRENT_DS )))
1777 ERR("Local heap not found\n");
1778 LOCAL_PrintHeap( CURRENT_DS );
1781 if (delta) pInfo->hdelta = delta;
1782 TRACE("returning %04x\n", pInfo->hdelta);
1783 return pInfo->hdelta;
1787 /***********************************************************************
1788 * LocalInfo (TOOLHELP.56)
1790 BOOL16 WINAPI LocalInfo16( LOCALINFO *pLocalInfo, HGLOBAL16 handle )
1792 LOCALHEAPINFO *pInfo = LOCAL_GetHeap(SELECTOROF(K32WOWGlobalLock16(handle)));
1793 if (!pInfo) return FALSE;
1794 pLocalInfo->wcItems = pInfo->items;
1799 /***********************************************************************
1800 * LocalFirst (TOOLHELP.57)
1802 BOOL16 WINAPI LocalFirst16( LOCALENTRY *pLocalEntry, HGLOBAL16 handle )
1804 WORD ds = GlobalHandleToSel16( handle );
1805 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1806 LOCALHEAPINFO *pInfo = LOCAL_GetHeap( ds );
1807 if (!pInfo) return FALSE;
1809 pLocalEntry->hHandle = pInfo->first + ARENA_HEADER_SIZE;
1810 pLocalEntry->wAddress = pLocalEntry->hHandle;
1811 pLocalEntry->wFlags = LF_FIXED;
1812 pLocalEntry->wcLock = 0;
1813 pLocalEntry->wType = LT_NORMAL;
1814 pLocalEntry->hHeap = handle;
1815 pLocalEntry->wHeapType = NORMAL_HEAP;
1816 pLocalEntry->wNext = ARENA_PTR(ptr,pInfo->first)->next;
1817 pLocalEntry->wSize = pLocalEntry->wNext - pLocalEntry->hHandle;
1822 /***********************************************************************
1823 * LocalNext (TOOLHELP.58)
1825 BOOL16 WINAPI LocalNext16( LOCALENTRY *pLocalEntry )
1827 WORD ds = GlobalHandleToSel16( pLocalEntry->hHeap );
1828 char *ptr = MapSL( MAKESEGPTR( ds, 0 ) );
1831 if (!LOCAL_GetHeap( ds )) return FALSE;
1832 if (!pLocalEntry->wNext) return FALSE;
1833 pArena = ARENA_PTR( ptr, pLocalEntry->wNext );
1835 pLocalEntry->hHandle = pLocalEntry->wNext + ARENA_HEADER_SIZE;
1836 pLocalEntry->wAddress = pLocalEntry->hHandle;
1837 pLocalEntry->wFlags = (pArena->prev & 3) + 1;
1838 pLocalEntry->wcLock = 0;
1839 pLocalEntry->wType = LT_NORMAL;
1840 if (pArena->next != pLocalEntry->wNext) /* last one? */
1841 pLocalEntry->wNext = pArena->next;
1843 pLocalEntry->wNext = 0;
1844 pLocalEntry->wSize = pLocalEntry->wNext - pLocalEntry->hHandle;
1849 /***********************************************************************
1850 * 32-bit local heap functions (Win95; undocumented)
1853 /***********************************************************************
1856 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1857 DWORD heapSize, DWORD flags )
1859 DWORD totSize, segSize = 0;
1861 LOCAL32HEADER *header;
1863 WORD *selectorTable;
1864 WORD selectorEven, selectorOdd;
1867 /* Determine new heap size */
1871 if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1877 if ( heapSize == -1L )
1878 heapSize = 1024L*1024L; /* FIXME */
1880 heapSize = (heapSize + 0xffff) & 0xffff0000;
1881 segSize = (segSize + 0x0fff) & 0xfffff000;
1882 totSize = segSize + HTABLE_SIZE + heapSize;
1885 /* Allocate memory and initialize heap */
1887 if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1890 if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE,
1891 MEM_COMMIT, PAGE_READWRITE ) )
1893 VirtualFree( base, 0, MEM_RELEASE );
1897 if (!(heap = RtlCreateHeap( 0, base + segSize + HTABLE_SIZE, heapSize, 0x10000, NULL, NULL )))
1899 VirtualFree( base, 0, MEM_RELEASE );
1904 /* Set up header and handle table */
1906 header = (LOCAL32HEADER *)(base + segSize);
1907 header->base = base;
1908 header->limit = HTABLE_PAGESIZE-1;
1910 header->magic = LOCAL32_MAGIC;
1911 header->heap = heap;
1913 header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1914 header->freeListLast[0] = HTABLE_PAGESIZE - 4;
1915 header->freeListSize[0] = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1917 for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1918 *(DWORD *)((LPBYTE)header + i) = i+4;
1920 header->freeListFirst[1] = 0xffff;
1923 /* Set up selector table */
1925 nrBlocks = (totSize + 0x7fff) >> 15;
1926 selectorTable = (LPWORD) HeapAlloc( header->heap, 0, nrBlocks * 2 );
1927 selectorEven = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1928 selectorOdd = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1929 if ( !selectorTable || !selectorEven || !selectorOdd )
1931 if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1932 if ( selectorEven ) SELECTOR_FreeBlock( selectorEven );
1933 if ( selectorOdd ) SELECTOR_FreeBlock( selectorOdd );
1934 HeapDestroy( header->heap );
1935 VirtualFree( base, 0, MEM_RELEASE );
1939 header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1940 header->selectorTableSize = nrBlocks * 4; /* ??? Win95 does it this way! */
1941 header->selectorDelta = selectorEven - selectorOdd;
1942 header->segment = segment? segment : selectorEven;
1944 for (i = 0; i < nrBlocks; i++)
1945 selectorTable[i] = (i & 1)? selectorOdd + ((i >> 1) << __AHSHIFT)
1946 : selectorEven + ((i >> 1) << __AHSHIFT);
1948 /* Move old segment */
1952 /* FIXME: This is somewhat ugly and relies on implementation
1953 details about 16-bit global memory handles ... */
1955 LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1956 memcpy( base, oldBase, segSize );
1957 GLOBAL_MoveBlock( segment, base, totSize );
1958 HeapFree( GetProcessHeap(), 0, oldBase );
1961 return (HANDLE)header;
1964 /***********************************************************************
1965 * Local32_SearchHandle
1967 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1971 for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1972 handle < (LPDWORD)((LPBYTE)header + header->limit);
1975 if (*handle == addr)
1982 /***********************************************************************
1985 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type,
1986 DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1993 case -2: /* 16:16 pointer, no handles */
1994 *ptr = MapSL( addr );
1995 *handle = (LPDWORD)*ptr;
1998 case -1: /* 32-bit offset, no handles */
1999 *ptr = header->base + addr;
2000 *handle = (LPDWORD)*ptr;
2003 case 0: /* handle */
2004 if ( addr >= sizeof(LOCAL32HEADER)
2005 && addr < header->limit && !(addr & 3)
2006 && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
2008 *handle = (LPDWORD)((LPBYTE)header + addr);
2009 *ptr = header->base + **handle;
2013 case 1: /* 16:16 pointer */
2014 *ptr = MapSL( addr );
2015 *handle = Local32_SearchHandle( header, *ptr - header->base );
2018 case 2: /* 32-bit offset */
2019 *ptr = header->base + addr;
2020 *handle = Local32_SearchHandle( header, *ptr - header->base );
2025 /***********************************************************************
2026 * Local32_FromHandle
2028 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type,
2029 DWORD *addr, LPDWORD handle, LPBYTE ptr )
2033 case -2: /* 16:16 pointer */
2036 WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
2037 DWORD offset = (LPBYTE)ptr - header->base;
2038 *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] );
2042 case -1: /* 32-bit offset */
2044 *addr = ptr - header->base;
2047 case 0: /* handle */
2048 *addr = (LPBYTE)handle - (LPBYTE)header;
2053 /***********************************************************************
2056 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
2058 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2063 /* Allocate memory */
2064 ptr = HeapAlloc( header->heap,
2065 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
2069 /* Allocate handle if requested */
2074 /* Find first page of handle table with free slots */
2075 for (page = 0; page < HTABLE_NPAGES; page++)
2076 if (header->freeListFirst[page] != 0)
2078 if (page == HTABLE_NPAGES)
2080 WARN("Out of handles!\n" );
2081 HeapFree( header->heap, 0, ptr );
2085 /* If virgin page, initialize it */
2086 if (header->freeListFirst[page] == 0xffff)
2088 if ( !VirtualAlloc( (LPBYTE)header + (page << 12),
2089 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
2091 WARN("Cannot grow handle table!\n" );
2092 HeapFree( header->heap, 0, ptr );
2096 header->limit += HTABLE_PAGESIZE;
2098 header->freeListFirst[page] = 0;
2099 header->freeListLast[page] = HTABLE_PAGESIZE - 4;
2100 header->freeListSize[page] = HTABLE_PAGESIZE / 4;
2102 for (i = 0; i < HTABLE_PAGESIZE; i += 4)
2103 *(DWORD *)((LPBYTE)header + i) = i+4;
2105 if (page < HTABLE_NPAGES-1)
2106 header->freeListFirst[page+1] = 0xffff;
2109 /* Allocate handle slot from page */
2110 handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
2111 if (--header->freeListSize[page] == 0)
2112 header->freeListFirst[page] = header->freeListLast[page] = 0;
2114 header->freeListFirst[page] = *handle;
2116 /* Store 32-bit offset in handle slot */
2117 *handle = ptr - header->base;
2121 handle = (LPDWORD)ptr;
2126 /* Convert handle to requested output type */
2127 Local32_FromHandle( header, type, &addr, handle, ptr );
2131 /***********************************************************************
2134 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
2135 DWORD size, DWORD flags )
2137 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2142 return Local32Alloc16( heap, size, type, flags );
2144 /* Retrieve handle and pointer */
2145 Local32_ToHandle( header, type, addr, &handle, &ptr );
2146 if (!handle) return FALSE;
2148 /* Reallocate memory block */
2149 ptr = HeapReAlloc( header->heap,
2150 (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0,
2156 *handle = ptr - header->base;
2158 handle = (LPDWORD)ptr;
2160 /* Convert handle to requested output type */
2161 Local32_FromHandle( header, type, &addr, handle, ptr );
2165 /***********************************************************************
2168 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2170 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2174 /* Retrieve handle and pointer */
2175 Local32_ToHandle( header, type, addr, &handle, &ptr );
2176 if (!handle) return FALSE;
2178 /* Free handle if necessary */
2181 int offset = (LPBYTE)handle - (LPBYTE)header;
2182 int page = offset >> 12;
2184 /* Return handle slot to page free list */
2185 if (header->freeListSize[page]++ == 0)
2186 header->freeListFirst[page] = header->freeListLast[page] = offset;
2188 *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2189 header->freeListLast[page] = offset;
2193 /* Shrink handle table when possible */
2194 while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2196 if ( VirtualFree( (LPBYTE)header +
2197 (header->limit & ~(HTABLE_PAGESIZE-1)),
2198 HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2201 header->limit -= HTABLE_PAGESIZE;
2202 header->freeListFirst[page] = 0xffff;
2208 return HeapFree( header->heap, 0, ptr );
2211 /***********************************************************************
2214 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2216 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2220 Local32_ToHandle( header, type1, addr, &handle, &ptr );
2221 if (!handle) return 0;
2223 Local32_FromHandle( header, type2, &addr, handle, ptr );
2227 /***********************************************************************
2230 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2232 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2236 Local32_ToHandle( header, type, addr, &handle, &ptr );
2237 if (!handle) return 0;
2239 return HeapSize( header->heap, 0, ptr );
2242 /***********************************************************************
2245 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2247 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2251 Local32_ToHandle( header, 0, addr, &handle, &ptr );
2252 return handle != NULL;
2255 /***********************************************************************
2258 WORD WINAPI Local32GetSegment16( HANDLE heap )
2260 LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2261 return header->segment;
2264 /***********************************************************************
2267 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2269 WORD selector = GlobalHandleToSel16( handle );
2270 DWORD base = GetSelectorBase( selector );
2271 DWORD limit = GetSelectorLimit16( selector );
2273 /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2276 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2277 return (LOCAL32HEADER *)base;
2282 if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2283 return (LOCAL32HEADER *)base;
2288 /***********************************************************************
2289 * Local32Info (KERNEL.444)
2290 * Local32Info (TOOLHELP.84)
2292 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2294 PROCESS_HEAP_ENTRY entry;
2297 LOCAL32HEADER *header = Local32_GetHeap( handle );
2298 if ( !header ) return FALSE;
2300 if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2303 pLocal32Info->dwMemReserved = 0;
2304 pLocal32Info->dwMemCommitted = 0;
2305 pLocal32Info->dwTotalFree = 0;
2306 pLocal32Info->dwLargestFreeBlock = 0;
2308 while (HeapWalk( header->heap, &entry ))
2310 if (entry.wFlags & PROCESS_HEAP_REGION)
2312 pLocal32Info->dwMemReserved += entry.u.Region.dwCommittedSize
2313 + entry.u.Region.dwUnCommittedSize;
2314 pLocal32Info->dwMemCommitted = entry.u.Region.dwCommittedSize;
2316 else if (!(entry.wFlags & PROCESS_HEAP_ENTRY_BUSY))
2318 DWORD size = entry.cbData + entry.cbOverhead;
2319 pLocal32Info->dwTotalFree += size;
2320 if (size > pLocal32Info->dwLargestFreeBlock) pLocal32Info->dwLargestFreeBlock = size;
2324 pLocal32Info->dwcFreeHandles = 0;
2325 for ( i = 0; i < HTABLE_NPAGES; i++ )
2327 if ( header->freeListFirst[i] == 0xffff ) break;
2328 pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2330 pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2335 /***********************************************************************
2336 * Local32First (KERNEL.445)
2337 * Local32First (TOOLHELP.85)
2339 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2341 FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2345 /***********************************************************************
2346 * Local32Next (KERNEL.446)
2347 * Local32Next (TOOLHELP.86)
2349 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2351 FIXME("(%p): stub!\n", pLocal32Entry );