po: Update Lithuanian translation.
[wine.git] / dlls / kernel32 / heap.c
blobcac73ec55748984d8a9d9ff844df16e074af0954
1 /*
2 * Win32 heap functions
4 * Copyright 1995, 1996 Alexandre Julliard
5 * Copyright 1996 Huw Davies
6 * Copyright 1998 Ulrich Weigand
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <limits.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <time.h>
34 #ifdef HAVE_SYS_PARAM_H
35 #include <sys/param.h>
36 #endif
37 #ifdef HAVE_SYS_SYSCTL_H
38 #include <sys/sysctl.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43 #ifdef HAVE_MACH_MACH_H
44 #include <mach/mach.h>
45 #endif
47 #ifdef sun
48 /* FIXME: Unfortunately swapctl can't be used with largefile.... */
49 # undef _FILE_OFFSET_BITS
50 # define _FILE_OFFSET_BITS 32
51 # ifdef HAVE_SYS_RESOURCE_H
52 # include <sys/resource.h>
53 # endif
54 # ifdef HAVE_SYS_STAT_H
55 # include <sys/stat.h>
56 # endif
57 # include <sys/swap.h>
58 #endif
61 #include "windef.h"
62 #include "winbase.h"
63 #include "winerror.h"
64 #include "winnt.h"
65 #include "winternl.h"
66 #include "wine/exception.h"
67 #include "wine/debug.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(heap);
70 WINE_DECLARE_DEBUG_CHANNEL(globalmem);
72 /* address where we try to map the system heap */
73 #define SYSTEM_HEAP_BASE ((void*)0x80000000)
74 #define SYSTEM_HEAP_SIZE 0x1000000 /* Default heap size = 16Mb */
76 static HANDLE systemHeap; /* globally shared heap */
79 /***********************************************************************
80 * HEAP_CreateSystemHeap
82 * Create the system heap.
84 static inline HANDLE HEAP_CreateSystemHeap(void)
86 int created;
87 void *base;
88 HANDLE map, event;
90 /* create the system heap event first */
91 event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );
93 if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
94 0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
95 created = (GetLastError() != ERROR_ALREADY_EXISTS);
97 if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
99 /* pre-defined address not available */
100 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
101 return 0;
104 if (created) /* newly created heap */
106 systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
107 SYSTEM_HEAP_SIZE, NULL, NULL );
108 SetEvent( event );
110 else
112 /* wait for the heap to be initialized */
113 WaitForSingleObject( event, INFINITE );
114 systemHeap = base;
116 CloseHandle( map );
117 return systemHeap;
121 /***********************************************************************
122 * HeapCreate (KERNEL32.@)
124 * Create a heap object.
126 * RETURNS
127 * Handle of heap: Success
128 * NULL: Failure
130 HANDLE WINAPI HeapCreate(
131 DWORD flags, /* [in] Heap allocation flag */
132 SIZE_T initialSize, /* [in] Initial heap size */
133 SIZE_T maxSize /* [in] Maximum heap size */
135 HANDLE ret;
137 if ( flags & HEAP_SHARED )
139 if (!systemHeap) HEAP_CreateSystemHeap();
140 else WARN( "Shared Heap requested, returning system heap.\n" );
141 ret = systemHeap;
143 else
145 ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
146 if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
148 return ret;
152 /***********************************************************************
153 * HeapDestroy (KERNEL32.@)
155 * Destroy a heap object.
157 * RETURNS
158 * TRUE: Success
159 * FALSE: Failure
161 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
163 if (heap == systemHeap)
165 WARN( "attempt to destroy system heap, returning TRUE!\n" );
166 return TRUE;
168 if (!RtlDestroyHeap( heap )) return TRUE;
169 SetLastError( ERROR_INVALID_HANDLE );
170 return FALSE;
174 /***********************************************************************
175 * HeapCompact (KERNEL32.@)
177 SIZE_T WINAPI HeapCompact( HANDLE heap, DWORD flags )
179 return RtlCompactHeap( heap, flags );
183 /***********************************************************************
184 * HeapValidate (KERNEL32.@)
185 * Validates a specified heap.
187 * NOTES
188 * Flags is ignored.
190 * RETURNS
191 * TRUE: Success
192 * FALSE: Failure
194 BOOL WINAPI HeapValidate(
195 HANDLE heap, /* [in] Handle to the heap */
196 DWORD flags, /* [in] Bit flags that control access during operation */
197 LPCVOID block /* [in] Optional pointer to memory block to validate */
199 return RtlValidateHeap( heap, flags, block );
203 /***********************************************************************
204 * HeapWalk (KERNEL32.@)
205 * Enumerates the memory blocks in a specified heap.
207 * TODO
208 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
209 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
211 * RETURNS
212 * TRUE: Success
213 * FALSE: Failure
215 BOOL WINAPI HeapWalk(
216 HANDLE heap, /* [in] Handle to heap to enumerate */
217 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
219 NTSTATUS ret = RtlWalkHeap( heap, entry );
220 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
221 return !ret;
225 /***********************************************************************
226 * HeapLock (KERNEL32.@)
227 * Attempts to acquire the critical section object for a specified heap.
229 * RETURNS
230 * TRUE: Success
231 * FALSE: Failure
233 BOOL WINAPI HeapLock(
234 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
236 return RtlLockHeap( heap );
240 /***********************************************************************
241 * HeapUnlock (KERNEL32.@)
242 * Releases ownership of the critical section object.
244 * RETURNS
245 * TRUE: Success
246 * FALSE: Failure
248 BOOL WINAPI HeapUnlock(
249 HANDLE heap /* [in] Handle to the heap to unlock */
251 return RtlUnlockHeap( heap );
255 /***********************************************************************
256 * GetProcessHeaps (KERNEL32.@)
258 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
260 return RtlGetProcessHeaps( count, heaps );
264 /* These are needed so that we can call the functions from inside kernel itself */
266 /***********************************************************************
267 * HeapAlloc (KERNEL32.@)
269 LPVOID WINAPI HeapAlloc( HANDLE heap, DWORD flags, SIZE_T size )
271 return RtlAllocateHeap( heap, flags, size );
274 BOOL WINAPI HeapFree( HANDLE heap, DWORD flags, LPVOID ptr )
276 return RtlFreeHeap( heap, flags, ptr );
279 LPVOID WINAPI HeapReAlloc( HANDLE heap, DWORD flags, LPVOID ptr, SIZE_T size )
281 return RtlReAllocateHeap( heap, flags, ptr, size );
284 SIZE_T WINAPI HeapSize( HANDLE heap, DWORD flags, LPCVOID ptr )
286 return RtlSizeHeap( heap, flags, ptr );
289 BOOL WINAPI HeapQueryInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
290 PVOID info, SIZE_T size_in, PSIZE_T size_out)
292 NTSTATUS ret = RtlQueryHeapInformation( heap, info_class, info, size_in, size_out );
293 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
294 return !ret;
297 BOOL WINAPI HeapSetInformation( HANDLE heap, HEAP_INFORMATION_CLASS infoclass, PVOID info, SIZE_T size)
299 NTSTATUS ret = RtlSetHeapInformation( heap, infoclass, info, size );
300 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
301 return !ret;
305 * Win32 Global heap functions (GlobalXXX).
306 * These functions included in Win32 for compatibility with 16 bit Windows
307 * Especially the moveable blocks and handles are oldish.
308 * But the ability to directly allocate memory with GPTR and LPTR is widely
309 * used.
311 * The handle stuff looks horrible, but it's implemented almost like Win95
312 * does it.
316 #define MAGIC_GLOBAL_USED 0x5342
317 #define HANDLE_TO_INTERN(h) ((PGLOBAL32_INTERN)(((char *)(h))-2))
318 #define INTERN_TO_HANDLE(i) (&((i)->Pointer))
319 #define POINTER_TO_HANDLE(p) (*(((const HGLOBAL *)(p))-2))
320 #define ISHANDLE(h) (((ULONG_PTR)(h)&2)!=0)
321 #define ISPOINTER(h) (((ULONG_PTR)(h)&2)==0)
322 /* align the storage needed for the HGLOBAL on an 8byte boundary thus
323 * GlobalAlloc/GlobalReAlloc'ing with GMEM_MOVEABLE of memory with
324 * size = 8*k, where k=1,2,3,... alloc's exactly the given size.
325 * The Minolta DiMAGE Image Viewer heavily relies on this, corrupting
326 * the output jpeg's > 1 MB if not */
327 #define HGLOBAL_STORAGE (sizeof(HGLOBAL)*2)
329 #include "pshpack1.h"
331 typedef struct __GLOBAL32_INTERN
333 WORD Magic;
334 LPVOID Pointer;
335 BYTE Flags;
336 BYTE LockCount;
337 } GLOBAL32_INTERN, *PGLOBAL32_INTERN;
339 #include "poppack.h"
341 /***********************************************************************
342 * GlobalAlloc (KERNEL32.@)
344 * Allocate a global memory object.
346 * RETURNS
347 * Handle: Success
348 * NULL: Failure
350 HGLOBAL WINAPI GlobalAlloc(
351 UINT flags, /* [in] Object allocation attributes */
352 SIZE_T size /* [in] Number of bytes to allocate */
354 PGLOBAL32_INTERN pintern;
355 DWORD hpflags;
356 LPVOID palloc;
358 if(flags&GMEM_ZEROINIT)
359 hpflags=HEAP_ZERO_MEMORY;
360 else
361 hpflags=0;
363 if((flags & GMEM_MOVEABLE)==0) /* POINTER */
365 palloc=HeapAlloc(GetProcessHeap(), hpflags, size);
366 TRACE( "(flags=%04x) returning %p\n", flags, palloc );
367 return palloc;
369 else /* HANDLE */
371 if (size > INT_MAX-HGLOBAL_STORAGE)
373 SetLastError(ERROR_OUTOFMEMORY);
374 return 0;
377 pintern = HeapAlloc(GetProcessHeap(), 0, sizeof(GLOBAL32_INTERN));
378 if (pintern)
380 /* Mask out obsolete flags */
381 flags &= ~(GMEM_LOWER | GMEM_NOCOMPACT | GMEM_NOT_BANKED | GMEM_NOTIFY);
383 pintern->Magic = MAGIC_GLOBAL_USED;
384 pintern->Flags = flags >> 8;
385 pintern->LockCount = 0;
387 if (size)
389 palloc = HeapAlloc(GetProcessHeap(), hpflags, size+HGLOBAL_STORAGE);
390 if (!palloc)
392 HeapFree(GetProcessHeap(), 0, pintern);
393 pintern = NULL;
395 else
397 *(HGLOBAL *)palloc = INTERN_TO_HANDLE(pintern);
398 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
401 else
402 pintern->Pointer = NULL;
405 if (!pintern) return 0;
406 TRACE( "(flags=%04x) returning handle %p pointer %p\n",
407 flags, INTERN_TO_HANDLE(pintern), pintern->Pointer );
408 return INTERN_TO_HANDLE(pintern);
413 /***********************************************************************
414 * GlobalLock (KERNEL32.@)
416 * Lock a global memory object and return a pointer to first byte of the memory
418 * PARAMS
419 * hmem [I] Handle of the global memory object
421 * RETURNS
422 * Success: Pointer to first byte of the memory block
423 * Failure: NULL
425 * NOTES
426 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
429 LPVOID WINAPI GlobalLock(HGLOBAL hmem)
431 PGLOBAL32_INTERN pintern;
432 LPVOID palloc;
434 if (ISPOINTER(hmem))
435 return IsBadReadPtr(hmem, 1) ? NULL : hmem;
437 RtlLockHeap(GetProcessHeap());
438 __TRY
440 pintern = HANDLE_TO_INTERN(hmem);
441 if (pintern->Magic == MAGIC_GLOBAL_USED)
443 palloc = pintern->Pointer;
444 if (!pintern->Pointer)
445 SetLastError(ERROR_DISCARDED);
446 else if (pintern->LockCount < GMEM_LOCKCOUNT)
447 pintern->LockCount++;
449 else
451 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
452 palloc = NULL;
453 SetLastError(ERROR_INVALID_HANDLE);
456 __EXCEPT_PAGE_FAULT
458 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
459 palloc = NULL;
460 SetLastError(ERROR_INVALID_HANDLE);
462 __ENDTRY
463 RtlUnlockHeap(GetProcessHeap());
464 return palloc;
468 /***********************************************************************
469 * GlobalUnlock (KERNEL32.@)
471 * Unlock a global memory object.
473 * PARAMS
474 * hmem [I] Handle of the global memory object
476 * RETURNS
477 * Success: Object is still locked
478 * Failure: FALSE (The Object is unlocked)
480 * NOTES
481 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
484 BOOL WINAPI GlobalUnlock(HGLOBAL hmem)
486 PGLOBAL32_INTERN pintern;
487 BOOL locked;
489 if (ISPOINTER(hmem)) return TRUE;
491 RtlLockHeap(GetProcessHeap());
492 __TRY
494 pintern=HANDLE_TO_INTERN(hmem);
495 if(pintern->Magic==MAGIC_GLOBAL_USED)
497 if(pintern->LockCount)
499 pintern->LockCount--;
500 locked = (pintern->LockCount != 0);
501 if (!locked) SetLastError(NO_ERROR);
503 else
505 WARN("%p not locked\n", hmem);
506 SetLastError(ERROR_NOT_LOCKED);
507 locked = FALSE;
510 else
512 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
513 SetLastError(ERROR_INVALID_HANDLE);
514 locked=FALSE;
517 __EXCEPT_PAGE_FAULT
519 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
520 SetLastError( ERROR_INVALID_PARAMETER );
521 locked=FALSE;
523 __ENDTRY
524 RtlUnlockHeap(GetProcessHeap());
525 return locked;
529 /***********************************************************************
530 * GlobalHandle (KERNEL32.@)
532 * Get the handle associated with the pointer to a global memory block.
534 * RETURNS
535 * Handle: Success
536 * NULL: Failure
538 HGLOBAL WINAPI GlobalHandle(
539 LPCVOID pmem /* [in] Pointer to global memory block */
541 HGLOBAL handle;
542 PGLOBAL32_INTERN maybe_intern;
543 LPCVOID test;
545 if (!pmem)
547 SetLastError( ERROR_INVALID_PARAMETER );
548 return 0;
551 RtlLockHeap(GetProcessHeap());
552 __TRY
554 handle = 0;
556 /* note that if pmem is a pointer to a block allocated by */
557 /* GlobalAlloc with GMEM_MOVEABLE then magic test in HeapValidate */
558 /* will fail. */
559 if (ISPOINTER(pmem)) {
560 if (HeapValidate( GetProcessHeap(), 0, pmem )) {
561 handle = (HGLOBAL)pmem; /* valid fixed block */
562 break;
564 handle = POINTER_TO_HANDLE(pmem);
565 } else
566 handle = (HGLOBAL)pmem;
568 /* Now test handle either passed in or retrieved from pointer */
569 maybe_intern = HANDLE_TO_INTERN( handle );
570 if (maybe_intern->Magic == MAGIC_GLOBAL_USED) {
571 test = maybe_intern->Pointer;
572 if (HeapValidate( GetProcessHeap(), 0, (const char *)test - HGLOBAL_STORAGE ) && /* obj(-handle) valid arena? */
573 HeapValidate( GetProcessHeap(), 0, maybe_intern )) /* intern valid arena? */
574 break; /* valid moveable block */
576 handle = 0;
577 SetLastError( ERROR_INVALID_HANDLE );
579 __EXCEPT_PAGE_FAULT
581 SetLastError( ERROR_INVALID_HANDLE );
582 handle = 0;
584 __ENDTRY
585 RtlUnlockHeap(GetProcessHeap());
587 return handle;
591 /***********************************************************************
592 * GlobalReAlloc (KERNEL32.@)
594 * Change the size or attributes of a global memory object.
596 * RETURNS
597 * Handle: Success
598 * NULL: Failure
600 HGLOBAL WINAPI GlobalReAlloc(
601 HGLOBAL hmem, /* [in] Handle of global memory object */
602 SIZE_T size, /* [in] New size of block */
603 UINT flags /* [in] How to reallocate object */
605 LPVOID palloc;
606 HGLOBAL hnew;
607 PGLOBAL32_INTERN pintern;
608 DWORD heap_flags = (flags & GMEM_ZEROINIT) ? HEAP_ZERO_MEMORY : 0;
610 hnew = 0;
611 RtlLockHeap(GetProcessHeap());
612 if(flags & GMEM_MODIFY) /* modify flags */
614 if( ISPOINTER(hmem) && (flags & GMEM_MOVEABLE))
616 /* make a fixed block moveable
617 * actually only NT is able to do this. But it's soo simple
619 if (hmem == 0)
621 WARN("GlobalReAlloc with null handle!\n");
622 SetLastError( ERROR_NOACCESS );
623 hnew = 0;
625 else
627 size = HeapSize(GetProcessHeap(), 0, hmem);
628 hnew = GlobalAlloc(flags, size);
629 palloc = GlobalLock(hnew);
630 memcpy(palloc, hmem, size);
631 GlobalUnlock(hnew);
632 GlobalFree(hmem);
635 else if( ISPOINTER(hmem) &&(flags & GMEM_DISCARDABLE))
637 /* change the flags to make our block "discardable" */
638 pintern=HANDLE_TO_INTERN(hmem);
639 pintern->Flags = pintern->Flags | (GMEM_DISCARDABLE >> 8);
640 hnew=hmem;
642 else
644 SetLastError(ERROR_INVALID_PARAMETER);
645 hnew = 0;
648 else
650 if(ISPOINTER(hmem))
652 /* reallocate fixed memory */
653 if (!(flags & GMEM_MOVEABLE))
654 heap_flags |= HEAP_REALLOC_IN_PLACE_ONLY;
655 hnew=HeapReAlloc(GetProcessHeap(), heap_flags, hmem, size);
657 else
659 /* reallocate a moveable block */
660 pintern=HANDLE_TO_INTERN(hmem);
662 #if 0
663 /* Apparently Windows doesn't care whether the handle is locked at this point */
664 /* See also the same comment in GlobalFree() */
665 if(pintern->LockCount>1) {
666 ERR("handle 0x%08lx is still locked, cannot realloc!\n",(DWORD)hmem);
667 SetLastError(ERROR_INVALID_HANDLE);
668 } else
669 #endif
670 if(size!=0)
672 hnew=hmem;
673 if(pintern->Pointer)
675 if(size > INT_MAX-HGLOBAL_STORAGE)
677 SetLastError(ERROR_OUTOFMEMORY);
678 hnew = 0;
680 else if((palloc = HeapReAlloc(GetProcessHeap(), heap_flags,
681 (char *) pintern->Pointer-HGLOBAL_STORAGE,
682 size+HGLOBAL_STORAGE)) == NULL)
683 hnew = 0; /* Block still valid */
684 else
685 pintern->Pointer = (char *)palloc+HGLOBAL_STORAGE;
687 else
689 if(size > INT_MAX-HGLOBAL_STORAGE)
691 SetLastError(ERROR_OUTOFMEMORY);
692 hnew = 0;
694 else if((palloc=HeapAlloc(GetProcessHeap(), heap_flags, size+HGLOBAL_STORAGE))
695 == NULL)
696 hnew = 0;
697 else
699 *(HGLOBAL *)palloc = hmem;
700 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
704 else
706 if (pintern->LockCount == 0)
708 if(pintern->Pointer)
710 HeapFree(GetProcessHeap(), 0, (char *) pintern->Pointer-HGLOBAL_STORAGE);
711 pintern->Pointer = NULL;
713 hnew = hmem;
715 else
716 WARN("not freeing memory associated with locked handle\n");
720 RtlUnlockHeap(GetProcessHeap());
721 return hnew;
725 /***********************************************************************
726 * GlobalFree (KERNEL32.@)
728 * Free a global memory object.
730 * PARAMS
731 * hmem [I] Handle of the global memory object
733 * RETURNS
734 * Success: NULL
735 * Failure: The provided handle
737 * NOTES
738 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
741 HGLOBAL WINAPI GlobalFree(HGLOBAL hmem)
743 PGLOBAL32_INTERN pintern;
744 HGLOBAL hreturned;
746 RtlLockHeap(GetProcessHeap());
747 __TRY
749 hreturned = 0;
750 if(ISPOINTER(hmem)) /* POINTER */
752 if(!HeapFree(GetProcessHeap(), 0, hmem))
754 SetLastError(ERROR_INVALID_HANDLE);
755 hreturned = hmem;
758 else /* HANDLE */
760 pintern=HANDLE_TO_INTERN(hmem);
762 if(pintern->Magic==MAGIC_GLOBAL_USED)
764 pintern->Magic = 0xdead;
766 /* WIN98 does not make this test. That is you can free a */
767 /* block you have not unlocked. Go figure!! */
768 /* if(pintern->LockCount!=0) */
769 /* SetLastError(ERROR_INVALID_HANDLE); */
771 if(pintern->Pointer)
772 if(!HeapFree(GetProcessHeap(), 0, (char *)(pintern->Pointer)-HGLOBAL_STORAGE))
773 hreturned=hmem;
774 if(!HeapFree(GetProcessHeap(), 0, pintern))
775 hreturned=hmem;
777 else
779 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
780 SetLastError(ERROR_INVALID_HANDLE);
781 hreturned = hmem;
785 __EXCEPT_PAGE_FAULT
787 ERR("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
788 SetLastError( ERROR_INVALID_PARAMETER );
789 hreturned = hmem;
791 __ENDTRY
792 RtlUnlockHeap(GetProcessHeap());
793 return hreturned;
797 /***********************************************************************
798 * GlobalSize (KERNEL32.@)
800 * Get the size of a global memory object.
802 * PARAMS
803 * hmem [I] Handle of the global memory object
805 * RETURNS
806 * Failure: 0
807 * Success: Size in Bytes of the global memory object
809 * NOTES
810 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
813 SIZE_T WINAPI GlobalSize(HGLOBAL hmem)
815 SIZE_T retval;
816 PGLOBAL32_INTERN pintern;
818 if (!((ULONG_PTR)hmem >> 16))
820 SetLastError(ERROR_INVALID_HANDLE);
821 return 0;
824 if(ISPOINTER(hmem))
826 retval=HeapSize(GetProcessHeap(), 0, hmem);
828 if (retval == ~0ul) /* It might be a GMEM_MOVEABLE data pointer */
830 retval = HeapSize(GetProcessHeap(), 0, (char*)hmem - HGLOBAL_STORAGE);
831 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
834 else
836 RtlLockHeap(GetProcessHeap());
837 pintern=HANDLE_TO_INTERN(hmem);
839 if(pintern->Magic==MAGIC_GLOBAL_USED)
841 if (!pintern->Pointer) /* handle case of GlobalAlloc( ??,0) */
842 retval = 0;
843 else
845 retval = HeapSize(GetProcessHeap(), 0, (char *)pintern->Pointer - HGLOBAL_STORAGE );
846 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
849 else
851 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
852 SetLastError(ERROR_INVALID_HANDLE);
853 retval=0;
855 RtlUnlockHeap(GetProcessHeap());
857 if (retval == ~0ul) retval = 0;
858 return retval;
862 /***********************************************************************
863 * GlobalWire (KERNEL32.@)
865 LPVOID WINAPI GlobalWire(HGLOBAL hmem)
867 return GlobalLock( hmem );
871 /***********************************************************************
872 * GlobalUnWire (KERNEL32.@)
874 BOOL WINAPI GlobalUnWire(HGLOBAL hmem)
876 return GlobalUnlock( hmem);
880 /***********************************************************************
881 * GlobalFix (KERNEL32.@)
883 VOID WINAPI GlobalFix(HGLOBAL hmem)
885 GlobalLock( hmem );
889 /***********************************************************************
890 * GlobalUnfix (KERNEL32.@)
892 VOID WINAPI GlobalUnfix(HGLOBAL hmem)
894 GlobalUnlock( hmem);
898 /***********************************************************************
899 * GlobalFlags (KERNEL32.@)
901 * Get information about a global memory object.
903 * PARAMS
904 * hmem [I] Handle of the global memory object
906 * RETURNS
907 * Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid
908 * Success: Value specifying allocation flags and lock count
911 UINT WINAPI GlobalFlags(HGLOBAL hmem)
913 DWORD retval;
914 PGLOBAL32_INTERN pintern;
916 if(ISPOINTER(hmem))
918 retval=0;
920 else
922 RtlLockHeap(GetProcessHeap());
923 pintern=HANDLE_TO_INTERN(hmem);
924 if(pintern->Magic==MAGIC_GLOBAL_USED)
926 retval=pintern->LockCount + (pintern->Flags<<8);
927 if(pintern->Pointer==0)
928 retval|= GMEM_DISCARDED;
930 else
932 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
933 SetLastError(ERROR_INVALID_HANDLE);
934 retval = GMEM_INVALID_HANDLE;
936 RtlUnlockHeap(GetProcessHeap());
938 return retval;
942 /***********************************************************************
943 * GlobalCompact (KERNEL32.@)
945 SIZE_T WINAPI GlobalCompact( DWORD minfree )
947 return 0; /* GlobalCompact does nothing in Win32 */
951 /***********************************************************************
952 * LocalAlloc (KERNEL32.@)
954 * Allocate a local memory object.
956 * RETURNS
957 * Handle: Success
958 * NULL: Failure
960 * NOTES
961 * Windows memory management does not provide a separate local heap
962 * and global heap.
964 HLOCAL WINAPI LocalAlloc(
965 UINT flags, /* [in] Allocation attributes */
966 SIZE_T size /* [in] Number of bytes to allocate */
968 return GlobalAlloc( flags, size );
972 /***********************************************************************
973 * LocalCompact (KERNEL32.@)
975 SIZE_T WINAPI LocalCompact( UINT minfree )
977 return 0; /* LocalCompact does nothing in Win32 */
981 /***********************************************************************
982 * LocalFlags (KERNEL32.@)
984 * Get information about a local memory object.
986 * RETURNS
987 * Value specifying allocation flags and lock count.
988 * LMEM_INVALID_HANDLE: Failure
990 * NOTES
991 * Windows memory management does not provide a separate local heap
992 * and global heap.
994 UINT WINAPI LocalFlags(
995 HLOCAL handle /* [in] Handle of memory object */
997 return GlobalFlags( handle );
1001 /***********************************************************************
1002 * LocalFree (KERNEL32.@)
1004 * Free a local memory object.
1006 * RETURNS
1007 * NULL: Success
1008 * Handle: Failure
1010 * NOTES
1011 * Windows memory management does not provide a separate local heap
1012 * and global heap.
1014 HLOCAL WINAPI LocalFree(
1015 HLOCAL handle /* [in] Handle of memory object */
1017 return GlobalFree( handle );
1021 /***********************************************************************
1022 * LocalHandle (KERNEL32.@)
1024 * Get the handle associated with the pointer to a local memory block.
1026 * RETURNS
1027 * Handle: Success
1028 * NULL: Failure
1030 * NOTES
1031 * Windows memory management does not provide a separate local heap
1032 * and global heap.
1034 HLOCAL WINAPI LocalHandle(
1035 LPCVOID ptr /* [in] Address of local memory block */
1037 return GlobalHandle( ptr );
1041 /***********************************************************************
1042 * LocalLock (KERNEL32.@)
1043 * Locks a local memory object and returns pointer to the first byte
1044 * of the memory block.
1046 * RETURNS
1047 * Pointer: Success
1048 * NULL: Failure
1050 * NOTES
1051 * Windows memory management does not provide a separate local heap
1052 * and global heap.
1054 LPVOID WINAPI LocalLock(
1055 HLOCAL handle /* [in] Address of local memory object */
1057 return GlobalLock( handle );
1061 /***********************************************************************
1062 * LocalReAlloc (KERNEL32.@)
1064 * Change the size or attributes of a local memory object.
1066 * RETURNS
1067 * Handle: Success
1068 * NULL: Failure
1070 * NOTES
1071 * Windows memory management does not provide a separate local heap
1072 * and global heap.
1074 HLOCAL WINAPI LocalReAlloc(
1075 HLOCAL handle, /* [in] Handle of memory object */
1076 SIZE_T size, /* [in] New size of block */
1077 UINT flags /* [in] How to reallocate object */
1079 return GlobalReAlloc( handle, size, flags );
1083 /***********************************************************************
1084 * LocalShrink (KERNEL32.@)
1086 SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
1088 return 0; /* LocalShrink does nothing in Win32 */
1092 /***********************************************************************
1093 * LocalSize (KERNEL32.@)
1095 * Get the size of a local memory object.
1097 * RETURNS
1098 * Size: Success
1099 * 0: Failure
1101 * NOTES
1102 * Windows memory management does not provide a separate local heap
1103 * and global heap.
1105 SIZE_T WINAPI LocalSize(
1106 HLOCAL handle /* [in] Handle of memory object */
1108 return GlobalSize( handle );
1112 /***********************************************************************
1113 * LocalUnlock (KERNEL32.@)
1115 * Unlock a local memory object.
1117 * RETURNS
1118 * TRUE: Object is still locked
1119 * FALSE: Object is unlocked
1121 * NOTES
1122 * Windows memory management does not provide a separate local heap
1123 * and global heap.
1125 BOOL WINAPI LocalUnlock(
1126 HLOCAL handle /* [in] Handle of memory object */
1129 if (ISPOINTER( handle ))
1131 SetLastError( ERROR_NOT_LOCKED );
1132 return FALSE;
1135 return GlobalUnlock( handle );
1139 /***********************************************************************
1140 * GlobalMemoryStatusEx (KERNEL32.@)
1141 * A version of GlobalMemoryStatus that can deal with memory over 4GB
1143 * RETURNS
1144 * TRUE
1146 BOOL WINAPI GlobalMemoryStatusEx( LPMEMORYSTATUSEX lpmemex )
1148 static MEMORYSTATUSEX cached_memstatus;
1149 static int cache_lastchecked = 0;
1150 SYSTEM_INFO si;
1151 #ifdef linux
1152 FILE *f;
1153 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1154 DWORDLONG total;
1155 #ifdef __APPLE__
1156 unsigned int val;
1157 #else
1158 unsigned long val;
1159 #endif
1160 int mib[2];
1161 size_t size_sys;
1162 #ifdef HW_MEMSIZE
1163 uint64_t val64;
1164 #endif
1165 #ifdef VM_SWAPUSAGE
1166 struct xsw_usage swap;
1167 #endif
1168 #elif defined(sun)
1169 unsigned long pagesize,maxpages,freepages,swapspace,swapfree;
1170 struct anoninfo swapinf;
1171 int rval;
1172 #endif
1174 if (lpmemex->dwLength != sizeof(*lpmemex))
1176 SetLastError( ERROR_INVALID_PARAMETER );
1177 return FALSE;
1180 if (time(NULL)==cache_lastchecked) {
1181 *lpmemex = cached_memstatus;
1182 return TRUE;
1184 cache_lastchecked = time(NULL);
1186 lpmemex->dwMemoryLoad = 0;
1187 lpmemex->ullTotalPhys = 16*1024*1024;
1188 lpmemex->ullAvailPhys = 16*1024*1024;
1189 lpmemex->ullTotalPageFile = 16*1024*1024;
1190 lpmemex->ullAvailPageFile = 16*1024*1024;
1192 #ifdef linux
1193 f = fopen( "/proc/meminfo", "r" );
1194 if (f)
1196 char buffer[256];
1197 unsigned long total, used, free, shared, buffers, cached;
1199 lpmemex->ullTotalPhys = lpmemex->ullAvailPhys = 0;
1200 lpmemex->ullTotalPageFile = lpmemex->ullAvailPageFile = 0;
1201 while (fgets( buffer, sizeof(buffer), f ))
1203 /* old style /proc/meminfo ... */
1204 if (sscanf( buffer, "Mem: %lu %lu %lu %lu %lu %lu",
1205 &total, &used, &free, &shared, &buffers, &cached ))
1207 lpmemex->ullTotalPhys += total;
1208 lpmemex->ullAvailPhys += free + buffers + cached;
1210 if (sscanf( buffer, "Swap: %lu %lu %lu", &total, &used, &free ))
1212 lpmemex->ullTotalPageFile += total;
1213 lpmemex->ullAvailPageFile += free;
1216 /* new style /proc/meminfo ... */
1217 if (sscanf(buffer, "MemTotal: %lu", &total))
1218 lpmemex->ullTotalPhys = (ULONG64)total*1024;
1219 if (sscanf(buffer, "MemFree: %lu", &free))
1220 lpmemex->ullAvailPhys = (ULONG64)free*1024;
1221 if (sscanf(buffer, "SwapTotal: %lu", &total))
1222 lpmemex->ullTotalPageFile = (ULONG64)total*1024;
1223 if (sscanf(buffer, "SwapFree: %lu", &free))
1224 lpmemex->ullAvailPageFile = (ULONG64)free*1024;
1225 if (sscanf(buffer, "Buffers: %lu", &buffers))
1226 lpmemex->ullAvailPhys += (ULONG64)buffers*1024;
1227 if (sscanf(buffer, "Cached: %lu", &cached))
1228 lpmemex->ullAvailPhys += (ULONG64)cached*1024;
1230 fclose( f );
1232 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1233 total = 0;
1234 lpmemex->ullAvailPhys = 0;
1236 mib[0] = CTL_HW;
1237 #ifdef HW_MEMSIZE
1238 mib[1] = HW_MEMSIZE;
1239 size_sys = sizeof(val64);
1240 if (!sysctl(mib, 2, &val64, &size_sys, NULL, 0) && size_sys == sizeof(val64) && val64)
1241 total = val64;
1242 #endif
1244 #ifdef HAVE_MACH_MACH_H
1246 host_name_port_t host = mach_host_self();
1247 mach_msg_type_number_t count;
1249 #ifdef HOST_VM_INFO64_COUNT
1250 vm_size_t page_size;
1251 vm_statistics64_data_t vm_stat;
1253 count = HOST_VM_INFO64_COUNT;
1254 if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) == KERN_SUCCESS &&
1255 host_page_size(host, &page_size) == KERN_SUCCESS)
1256 lpmemex->ullAvailPhys = (vm_stat.free_count + vm_stat.inactive_count) * (DWORDLONG)page_size;
1257 #endif
1258 if (!total)
1260 host_basic_info_data_t info;
1261 count = HOST_BASIC_INFO_COUNT;
1262 if (host_info(host, HOST_BASIC_INFO, (host_info_t)&info, &count) == KERN_SUCCESS)
1263 total = info.max_mem;
1266 mach_port_deallocate(mach_task_self(), host);
1268 #endif
1270 if (!total)
1272 mib[1] = HW_PHYSMEM;
1273 size_sys = sizeof(val);
1274 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val) && val)
1275 total = val;
1278 if (total)
1279 lpmemex->ullTotalPhys = total;
1281 if (!lpmemex->ullAvailPhys)
1283 mib[1] = HW_USERMEM;
1284 size_sys = sizeof(val);
1285 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val) && val)
1286 lpmemex->ullAvailPhys = val;
1289 if (!lpmemex->ullAvailPhys)
1290 lpmemex->ullAvailPhys = lpmemex->ullTotalPhys;
1292 lpmemex->ullTotalPageFile = lpmemex->ullAvailPhys;
1293 lpmemex->ullAvailPageFile = lpmemex->ullAvailPhys;
1295 #ifdef VM_SWAPUSAGE
1296 mib[0] = CTL_VM;
1297 mib[1] = VM_SWAPUSAGE;
1298 size_sys = sizeof(swap);
1299 if (!sysctl(mib, 2, &swap, &size_sys, NULL, 0) && size_sys == sizeof(swap))
1301 lpmemex->ullTotalPageFile = swap.xsu_total;
1302 lpmemex->ullAvailPageFile = swap.xsu_avail;
1304 #endif
1305 #elif defined ( sun )
1306 pagesize=sysconf(_SC_PAGESIZE);
1307 maxpages=sysconf(_SC_PHYS_PAGES);
1308 freepages=sysconf(_SC_AVPHYS_PAGES);
1309 rval=swapctl(SC_AINFO, &swapinf);
1310 if(rval >-1)
1312 swapspace=swapinf.ani_max*pagesize;
1313 swapfree=swapinf.ani_free*pagesize;
1314 }else
1317 WARN("Swap size cannot be determined , assuming equal to physical memory\n");
1318 swapspace=maxpages*pagesize;
1319 swapfree=maxpages*pagesize;
1321 lpmemex->ullTotalPhys=pagesize*maxpages;
1322 lpmemex->ullAvailPhys = pagesize*freepages;
1323 lpmemex->ullTotalPageFile = swapspace;
1324 lpmemex->ullAvailPageFile = swapfree;
1325 #endif
1327 if (lpmemex->ullTotalPhys)
1329 lpmemex->dwMemoryLoad = (lpmemex->ullTotalPhys-lpmemex->ullAvailPhys)
1330 / (lpmemex->ullTotalPhys / 100);
1333 /* Win98 returns only the swapsize in ullTotalPageFile/ullAvailPageFile,
1334 WinXP returns the size of physical memory + swapsize;
1335 mimic the behavior of XP.
1336 Note: Project2k refuses to start if it sees less than 1Mb of free swap.
1338 lpmemex->ullTotalPageFile += lpmemex->ullTotalPhys;
1339 lpmemex->ullAvailPageFile += lpmemex->ullAvailPhys;
1341 /* Titan Quest refuses to run if TotalPageFile <= ullTotalPhys */
1342 if(lpmemex->ullTotalPageFile == lpmemex->ullTotalPhys)
1344 lpmemex->ullTotalPhys -= 1;
1345 lpmemex->ullAvailPhys -= 1;
1348 /* FIXME: should do something for other systems */
1349 GetSystemInfo(&si);
1350 lpmemex->ullTotalVirtual = (ULONG_PTR)si.lpMaximumApplicationAddress-(ULONG_PTR)si.lpMinimumApplicationAddress;
1351 /* FIXME: we should track down all the already allocated VM pages and subtract them, for now arbitrarily remove 64KB so that it matches NT */
1352 lpmemex->ullAvailVirtual = lpmemex->ullTotalVirtual-64*1024;
1354 /* MSDN says about AvailExtendedVirtual: Size of unreserved and uncommitted
1355 memory in the extended portion of the virtual address space of the calling
1356 process, in bytes.
1357 However, I don't know what this means, so set it to zero :(
1359 lpmemex->ullAvailExtendedVirtual = 0;
1361 cached_memstatus = *lpmemex;
1363 TRACE_(globalmem)("<-- LPMEMORYSTATUSEX: dwLength %d, dwMemoryLoad %d, ullTotalPhys %s, ullAvailPhys %s,"
1364 " ullTotalPageFile %s, ullAvailPageFile %s, ullTotalVirtual %s, ullAvailVirtual %s\n",
1365 lpmemex->dwLength, lpmemex->dwMemoryLoad, wine_dbgstr_longlong(lpmemex->ullTotalPhys),
1366 wine_dbgstr_longlong(lpmemex->ullAvailPhys), wine_dbgstr_longlong(lpmemex->ullTotalPageFile),
1367 wine_dbgstr_longlong(lpmemex->ullAvailPageFile), wine_dbgstr_longlong(lpmemex->ullTotalVirtual),
1368 wine_dbgstr_longlong(lpmemex->ullAvailVirtual) );
1370 return TRUE;
1373 /***********************************************************************
1374 * GlobalMemoryStatus (KERNEL32.@)
1375 * Provides information about the status of the memory, so apps can tell
1376 * roughly how much they are able to allocate
1378 * RETURNS
1379 * None
1381 VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
1383 MEMORYSTATUSEX memstatus;
1384 OSVERSIONINFOW osver;
1385 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( GetModuleHandleW(0) );
1387 /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
1388 for one extra field in the struct, and the lack of a bug, we simply
1389 call GlobalMemoryStatusEx and copy the values across. */
1390 memstatus.dwLength = sizeof(memstatus);
1391 GlobalMemoryStatusEx(&memstatus);
1393 lpBuffer->dwLength = sizeof(*lpBuffer);
1394 lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;
1396 /* Windows 2000 and later report -1 when values are greater than 4 Gb.
1397 * NT reports values modulo 4 Gb.
1400 osver.dwOSVersionInfoSize = sizeof(osver);
1401 GetVersionExW(&osver);
1403 if ( osver.dwMajorVersion >= 5 || osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
1405 lpBuffer->dwTotalPhys = min( memstatus.ullTotalPhys, MAXDWORD );
1406 lpBuffer->dwAvailPhys = min( memstatus.ullAvailPhys, MAXDWORD );
1407 /* Limit value for apps that do not expect so much memory. Remove last 512 kb to make Sacrifice demo happy. */
1408 lpBuffer->dwTotalPageFile = min( memstatus.ullTotalPageFile, 0xfff7ffff );
1409 lpBuffer->dwAvailPageFile = min( memstatus.ullAvailPageFile, MAXDWORD );
1410 lpBuffer->dwTotalVirtual = min( memstatus.ullTotalVirtual, MAXDWORD );
1411 lpBuffer->dwAvailVirtual = min( memstatus.ullAvailVirtual, MAXDWORD );
1414 else /* duplicate NT bug */
1416 lpBuffer->dwTotalPhys = memstatus.ullTotalPhys;
1417 lpBuffer->dwAvailPhys = memstatus.ullAvailPhys;
1418 lpBuffer->dwTotalPageFile = memstatus.ullTotalPageFile;
1419 lpBuffer->dwAvailPageFile = memstatus.ullAvailPageFile;
1420 lpBuffer->dwTotalVirtual = memstatus.ullTotalVirtual;
1421 lpBuffer->dwAvailVirtual = memstatus.ullAvailVirtual;
1424 /* values are limited to 2Gb unless the app has the IMAGE_FILE_LARGE_ADDRESS_AWARE flag */
1425 /* page file sizes are not limited (Adobe Illustrator 8 depends on this) */
1426 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE))
1428 if (lpBuffer->dwTotalPhys > MAXLONG) lpBuffer->dwTotalPhys = MAXLONG;
1429 if (lpBuffer->dwAvailPhys > MAXLONG) lpBuffer->dwAvailPhys = MAXLONG;
1430 if (lpBuffer->dwTotalVirtual > MAXLONG) lpBuffer->dwTotalVirtual = MAXLONG;
1431 if (lpBuffer->dwAvailVirtual > MAXLONG) lpBuffer->dwAvailVirtual = MAXLONG;
1434 /* work around for broken photoshop 4 installer */
1435 if ( lpBuffer->dwAvailPhys + lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
1436 lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 - lpBuffer->dwAvailPhys - 1;
1438 /* limit page file size for really old binaries */
1439 if (nt->OptionalHeader.MajorSubsystemVersion < 4)
1441 if (lpBuffer->dwTotalPageFile > MAXLONG) lpBuffer->dwTotalPageFile = MAXLONG;
1442 if (lpBuffer->dwAvailPageFile > MAXLONG) lpBuffer->dwAvailPageFile = MAXLONG;
1445 TRACE_(globalmem)("Length %u, MemoryLoad %u, TotalPhys %lx, AvailPhys %lx,"
1446 " TotalPageFile %lx, AvailPageFile %lx, TotalVirtual %lx, AvailVirtual %lx\n",
1447 lpBuffer->dwLength, lpBuffer->dwMemoryLoad, lpBuffer->dwTotalPhys,
1448 lpBuffer->dwAvailPhys, lpBuffer->dwTotalPageFile, lpBuffer->dwAvailPageFile,
1449 lpBuffer->dwTotalVirtual, lpBuffer->dwAvailVirtual );
1452 BOOL WINAPI GetSystemFileCacheSize(PSIZE_T mincache, PSIZE_T maxcache, PDWORD flags)
1454 FIXME("stub: %p %p %p\n", mincache, maxcache, flags);
1455 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1456 return FALSE;
1459 BOOL WINAPI SetSystemFileCacheSize(SIZE_T mincache, SIZE_T maxcache, DWORD flags)
1461 FIXME("stub: %ld %ld %d\n", mincache, maxcache, flags);
1462 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1463 return FALSE;