msvcrt: Don't forward wcsncpy to ntdll.
[wine.git] / dlls / kernel32 / heap.c
blobe0b86e57358b5dd993b5adb88e16f5b652350d12
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
44 #ifdef sun
45 /* FIXME: Unfortunately swapctl can't be used with largefile.... */
46 # undef _FILE_OFFSET_BITS
47 # define _FILE_OFFSET_BITS 32
48 # ifdef HAVE_SYS_RESOURCE_H
49 # include <sys/resource.h>
50 # endif
51 # ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
53 # endif
54 # include <sys/swap.h>
55 #endif
58 #include "windef.h"
59 #include "winbase.h"
60 #include "winerror.h"
61 #include "winnt.h"
62 #include "winternl.h"
63 #include "wine/exception.h"
64 #include "wine/debug.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(heap);
67 WINE_DECLARE_DEBUG_CHANNEL(globalmem);
69 /* address where we try to map the system heap */
70 #define SYSTEM_HEAP_BASE ((void*)0x80000000)
71 #define SYSTEM_HEAP_SIZE 0x1000000 /* Default heap size = 16Mb */
73 static HANDLE systemHeap; /* globally shared heap */
76 /***********************************************************************
77 * HEAP_CreateSystemHeap
79 * Create the system heap.
81 static inline HANDLE HEAP_CreateSystemHeap(void)
83 int created;
84 void *base;
85 HANDLE map, event;
87 /* create the system heap event first */
88 event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );
90 if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
91 0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
92 created = (GetLastError() != ERROR_ALREADY_EXISTS);
94 if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
96 /* pre-defined address not available */
97 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
98 return 0;
101 if (created) /* newly created heap */
103 systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
104 SYSTEM_HEAP_SIZE, NULL, NULL );
105 SetEvent( event );
107 else
109 /* wait for the heap to be initialized */
110 WaitForSingleObject( event, INFINITE );
111 systemHeap = base;
113 CloseHandle( map );
114 return systemHeap;
118 /***********************************************************************
119 * HeapCreate (KERNEL32.@)
121 * Create a heap object.
123 * RETURNS
124 * Handle of heap: Success
125 * NULL: Failure
127 HANDLE WINAPI HeapCreate(
128 DWORD flags, /* [in] Heap allocation flag */
129 SIZE_T initialSize, /* [in] Initial heap size */
130 SIZE_T maxSize /* [in] Maximum heap size */
132 HANDLE ret;
134 if ( flags & HEAP_SHARED )
136 if (!systemHeap) HEAP_CreateSystemHeap();
137 else WARN( "Shared Heap requested, returning system heap.\n" );
138 ret = systemHeap;
140 else
142 ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
143 if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
145 return ret;
149 /***********************************************************************
150 * HeapDestroy (KERNEL32.@)
152 * Destroy a heap object.
154 * RETURNS
155 * TRUE: Success
156 * FALSE: Failure
158 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
160 if (heap == systemHeap)
162 WARN( "attempt to destroy system heap, returning TRUE!\n" );
163 return TRUE;
165 if (!RtlDestroyHeap( heap )) return TRUE;
166 SetLastError( ERROR_INVALID_HANDLE );
167 return FALSE;
171 /***********************************************************************
172 * HeapCompact (KERNEL32.@)
174 SIZE_T WINAPI HeapCompact( HANDLE heap, DWORD flags )
176 return RtlCompactHeap( heap, flags );
180 /***********************************************************************
181 * HeapValidate (KERNEL32.@)
182 * Validates a specified heap.
184 * NOTES
185 * Flags is ignored.
187 * RETURNS
188 * TRUE: Success
189 * FALSE: Failure
191 BOOL WINAPI HeapValidate(
192 HANDLE heap, /* [in] Handle to the heap */
193 DWORD flags, /* [in] Bit flags that control access during operation */
194 LPCVOID block /* [in] Optional pointer to memory block to validate */
196 return RtlValidateHeap( heap, flags, block );
200 /***********************************************************************
201 * HeapWalk (KERNEL32.@)
202 * Enumerates the memory blocks in a specified heap.
204 * TODO
205 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
206 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
208 * RETURNS
209 * TRUE: Success
210 * FALSE: Failure
212 BOOL WINAPI HeapWalk(
213 HANDLE heap, /* [in] Handle to heap to enumerate */
214 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
216 NTSTATUS ret = RtlWalkHeap( heap, entry );
217 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
218 return !ret;
222 /***********************************************************************
223 * HeapLock (KERNEL32.@)
224 * Attempts to acquire the critical section object for a specified heap.
226 * RETURNS
227 * TRUE: Success
228 * FALSE: Failure
230 BOOL WINAPI HeapLock(
231 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
233 return RtlLockHeap( heap );
237 /***********************************************************************
238 * HeapUnlock (KERNEL32.@)
239 * Releases ownership of the critical section object.
241 * RETURNS
242 * TRUE: Success
243 * FALSE: Failure
245 BOOL WINAPI HeapUnlock(
246 HANDLE heap /* [in] Handle to the heap to unlock */
248 return RtlUnlockHeap( heap );
252 /***********************************************************************
253 * GetProcessHeaps (KERNEL32.@)
255 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
257 return RtlGetProcessHeaps( count, heaps );
261 /* These are needed so that we can call the functions from inside kernel itself */
263 /***********************************************************************
264 * HeapAlloc (KERNEL32.@)
266 LPVOID WINAPI HeapAlloc( HANDLE heap, DWORD flags, SIZE_T size )
268 return RtlAllocateHeap( heap, flags, size );
271 BOOL WINAPI HeapFree( HANDLE heap, DWORD flags, LPVOID ptr )
273 return RtlFreeHeap( heap, flags, ptr );
276 LPVOID WINAPI HeapReAlloc( HANDLE heap, DWORD flags, LPVOID ptr, SIZE_T size )
278 return RtlReAllocateHeap( heap, flags, ptr, size );
281 SIZE_T WINAPI HeapSize( HANDLE heap, DWORD flags, LPCVOID ptr )
283 return RtlSizeHeap( heap, flags, ptr );
286 BOOL WINAPI HeapQueryInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
287 PVOID info, SIZE_T size_in, PSIZE_T size_out)
289 NTSTATUS ret = RtlQueryHeapInformation( heap, info_class, info, size_in, size_out );
290 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
291 return !ret;
294 BOOL WINAPI HeapSetInformation( HANDLE heap, HEAP_INFORMATION_CLASS infoclass, PVOID info, SIZE_T size)
296 FIXME("%p %d %p %ld\n", heap, infoclass, info, size );
297 return TRUE;
301 * Win32 Global heap functions (GlobalXXX).
302 * These functions included in Win32 for compatibility with 16 bit Windows
303 * Especially the moveable blocks and handles are oldish.
304 * But the ability to directly allocate memory with GPTR and LPTR is widely
305 * used.
307 * The handle stuff looks horrible, but it's implemented almost like Win95
308 * does it.
312 #define MAGIC_GLOBAL_USED 0x5342
313 #define HANDLE_TO_INTERN(h) ((PGLOBAL32_INTERN)(((char *)(h))-2))
314 #define INTERN_TO_HANDLE(i) (&((i)->Pointer))
315 #define POINTER_TO_HANDLE(p) (*(((const HGLOBAL *)(p))-2))
316 #define ISHANDLE(h) (((ULONG_PTR)(h)&2)!=0)
317 #define ISPOINTER(h) (((ULONG_PTR)(h)&2)==0)
318 /* align the storage needed for the HGLOBAL on an 8byte boundary thus
319 * GlobalAlloc/GlobalReAlloc'ing with GMEM_MOVEABLE of memory with
320 * size = 8*k, where k=1,2,3,... alloc's exactly the given size.
321 * The Minolta DiMAGE Image Viewer heavily relies on this, corrupting
322 * the output jpeg's > 1 MB if not */
323 #define HGLOBAL_STORAGE (sizeof(HGLOBAL)*2)
325 #include "pshpack1.h"
327 typedef struct __GLOBAL32_INTERN
329 WORD Magic;
330 LPVOID Pointer;
331 BYTE Flags;
332 BYTE LockCount;
333 } GLOBAL32_INTERN, *PGLOBAL32_INTERN;
335 #include "poppack.h"
337 /***********************************************************************
338 * GlobalAlloc (KERNEL32.@)
340 * Allocate a global memory object.
342 * RETURNS
343 * Handle: Success
344 * NULL: Failure
346 HGLOBAL WINAPI GlobalAlloc(
347 UINT flags, /* [in] Object allocation attributes */
348 SIZE_T size /* [in] Number of bytes to allocate */
350 PGLOBAL32_INTERN pintern;
351 DWORD hpflags;
352 LPVOID palloc;
354 if(flags&GMEM_ZEROINIT)
355 hpflags=HEAP_ZERO_MEMORY;
356 else
357 hpflags=0;
359 if((flags & GMEM_MOVEABLE)==0) /* POINTER */
361 palloc=HeapAlloc(GetProcessHeap(), hpflags, size);
362 TRACE( "(flags=%04x) returning %p\n", flags, palloc );
363 return palloc;
365 else /* HANDLE */
367 if (size > INT_MAX-HGLOBAL_STORAGE)
369 SetLastError(ERROR_OUTOFMEMORY);
370 return 0;
373 pintern = HeapAlloc(GetProcessHeap(), 0, sizeof(GLOBAL32_INTERN));
374 if (pintern)
376 /* Mask out obsolete flags */
377 flags &= ~(GMEM_LOWER | GMEM_NOCOMPACT | GMEM_NOT_BANKED | GMEM_NOTIFY);
379 pintern->Magic = MAGIC_GLOBAL_USED;
380 pintern->Flags = flags >> 8;
381 pintern->LockCount = 0;
383 if (size)
385 palloc = HeapAlloc(GetProcessHeap(), hpflags, size+HGLOBAL_STORAGE);
386 if (!palloc)
388 HeapFree(GetProcessHeap(), 0, pintern);
389 pintern = NULL;
391 else
393 *(HGLOBAL *)palloc = INTERN_TO_HANDLE(pintern);
394 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
397 else
398 pintern->Pointer = NULL;
401 if (!pintern) return 0;
402 TRACE( "(flags=%04x) returning handle %p pointer %p\n",
403 flags, INTERN_TO_HANDLE(pintern), pintern->Pointer );
404 return INTERN_TO_HANDLE(pintern);
409 /***********************************************************************
410 * GlobalLock (KERNEL32.@)
412 * Lock a global memory object and return a pointer to first byte of the memory
414 * PARAMS
415 * hmem [I] Handle of the global memory object
417 * RETURNS
418 * Success: Pointer to first byte of the memory block
419 * Failure: NULL
421 * NOTES
422 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
425 LPVOID WINAPI GlobalLock(HGLOBAL hmem)
427 PGLOBAL32_INTERN pintern;
428 LPVOID palloc;
430 if (ISPOINTER(hmem))
431 return IsBadReadPtr(hmem, 1) ? NULL : hmem;
433 RtlLockHeap(GetProcessHeap());
434 __TRY
436 pintern = HANDLE_TO_INTERN(hmem);
437 if (pintern->Magic == MAGIC_GLOBAL_USED)
439 palloc = pintern->Pointer;
440 if (!pintern->Pointer)
441 SetLastError(ERROR_DISCARDED);
442 else if (pintern->LockCount < GMEM_LOCKCOUNT)
443 pintern->LockCount++;
445 else
447 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
448 palloc = NULL;
449 SetLastError(ERROR_INVALID_HANDLE);
452 __EXCEPT_PAGE_FAULT
454 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
455 palloc = NULL;
456 SetLastError(ERROR_INVALID_HANDLE);
458 __ENDTRY
459 RtlUnlockHeap(GetProcessHeap());
460 return palloc;
464 /***********************************************************************
465 * GlobalUnlock (KERNEL32.@)
467 * Unlock a global memory object.
469 * PARAMS
470 * hmem [I] Handle of the global memory object
472 * RETURNS
473 * Success: Object is still locked
474 * Failure: FALSE (The Object is unlocked)
476 * NOTES
477 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
480 BOOL WINAPI GlobalUnlock(HGLOBAL hmem)
482 PGLOBAL32_INTERN pintern;
483 BOOL locked;
485 if (ISPOINTER(hmem)) return TRUE;
487 RtlLockHeap(GetProcessHeap());
488 __TRY
490 pintern=HANDLE_TO_INTERN(hmem);
491 if(pintern->Magic==MAGIC_GLOBAL_USED)
493 if(pintern->LockCount)
495 pintern->LockCount--;
496 locked = (pintern->LockCount != 0);
497 if (!locked) SetLastError(NO_ERROR);
499 else
501 WARN("%p not locked\n", hmem);
502 SetLastError(ERROR_NOT_LOCKED);
503 locked = FALSE;
506 else
508 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
509 SetLastError(ERROR_INVALID_HANDLE);
510 locked=FALSE;
513 __EXCEPT_PAGE_FAULT
515 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
516 SetLastError( ERROR_INVALID_PARAMETER );
517 locked=FALSE;
519 __ENDTRY
520 RtlUnlockHeap(GetProcessHeap());
521 return locked;
525 /***********************************************************************
526 * GlobalHandle (KERNEL32.@)
528 * Get the handle associated with the pointer to a global memory block.
530 * RETURNS
531 * Handle: Success
532 * NULL: Failure
534 HGLOBAL WINAPI GlobalHandle(
535 LPCVOID pmem /* [in] Pointer to global memory block */
537 HGLOBAL handle;
538 PGLOBAL32_INTERN maybe_intern;
539 LPCVOID test;
541 if (!pmem)
543 SetLastError( ERROR_INVALID_PARAMETER );
544 return 0;
547 RtlLockHeap(GetProcessHeap());
548 __TRY
550 handle = 0;
552 /* note that if pmem is a pointer to a block allocated by */
553 /* GlobalAlloc with GMEM_MOVEABLE then magic test in HeapValidate */
554 /* will fail. */
555 if (ISPOINTER(pmem)) {
556 if (HeapValidate( GetProcessHeap(), 0, pmem )) {
557 handle = (HGLOBAL)pmem; /* valid fixed block */
558 break;
560 handle = POINTER_TO_HANDLE(pmem);
561 } else
562 handle = (HGLOBAL)pmem;
564 /* Now test handle either passed in or retrieved from pointer */
565 maybe_intern = HANDLE_TO_INTERN( handle );
566 if (maybe_intern->Magic == MAGIC_GLOBAL_USED) {
567 test = maybe_intern->Pointer;
568 if (HeapValidate( GetProcessHeap(), 0, (const char *)test - HGLOBAL_STORAGE ) && /* obj(-handle) valid arena? */
569 HeapValidate( GetProcessHeap(), 0, maybe_intern )) /* intern valid arena? */
570 break; /* valid moveable block */
572 handle = 0;
573 SetLastError( ERROR_INVALID_HANDLE );
575 __EXCEPT_PAGE_FAULT
577 SetLastError( ERROR_INVALID_HANDLE );
578 handle = 0;
580 __ENDTRY
581 RtlUnlockHeap(GetProcessHeap());
583 return handle;
587 /***********************************************************************
588 * GlobalReAlloc (KERNEL32.@)
590 * Change the size or attributes of a global memory object.
592 * RETURNS
593 * Handle: Success
594 * NULL: Failure
596 HGLOBAL WINAPI GlobalReAlloc(
597 HGLOBAL hmem, /* [in] Handle of global memory object */
598 SIZE_T size, /* [in] New size of block */
599 UINT flags /* [in] How to reallocate object */
601 LPVOID palloc;
602 HGLOBAL hnew;
603 PGLOBAL32_INTERN pintern;
604 DWORD heap_flags = (flags & GMEM_ZEROINIT) ? HEAP_ZERO_MEMORY : 0;
606 hnew = 0;
607 RtlLockHeap(GetProcessHeap());
608 if(flags & GMEM_MODIFY) /* modify flags */
610 if( ISPOINTER(hmem) && (flags & GMEM_MOVEABLE))
612 /* make a fixed block moveable
613 * actually only NT is able to do this. But it's soo simple
615 if (hmem == 0)
617 WARN("GlobalReAlloc with null handle!\n");
618 SetLastError( ERROR_NOACCESS );
619 hnew = 0;
621 else
623 size = HeapSize(GetProcessHeap(), 0, hmem);
624 hnew = GlobalAlloc(flags, size);
625 palloc = GlobalLock(hnew);
626 memcpy(palloc, hmem, size);
627 GlobalUnlock(hnew);
628 GlobalFree(hmem);
631 else if( ISPOINTER(hmem) &&(flags & GMEM_DISCARDABLE))
633 /* change the flags to make our block "discardable" */
634 pintern=HANDLE_TO_INTERN(hmem);
635 pintern->Flags = pintern->Flags | (GMEM_DISCARDABLE >> 8);
636 hnew=hmem;
638 else
640 SetLastError(ERROR_INVALID_PARAMETER);
641 hnew = 0;
644 else
646 if(ISPOINTER(hmem))
648 /* reallocate fixed memory */
649 hnew=HeapReAlloc(GetProcessHeap(), heap_flags, hmem, size);
651 else
653 /* reallocate a moveable block */
654 pintern=HANDLE_TO_INTERN(hmem);
656 #if 0
657 /* Apparently Windows doesn't care whether the handle is locked at this point */
658 /* See also the same comment in GlobalFree() */
659 if(pintern->LockCount>1) {
660 ERR("handle 0x%08lx is still locked, cannot realloc!\n",(DWORD)hmem);
661 SetLastError(ERROR_INVALID_HANDLE);
662 } else
663 #endif
664 if(size!=0)
666 hnew=hmem;
667 if(pintern->Pointer)
669 if(size > INT_MAX-HGLOBAL_STORAGE)
671 SetLastError(ERROR_OUTOFMEMORY);
672 hnew = 0;
674 else if((palloc = HeapReAlloc(GetProcessHeap(), heap_flags,
675 (char *) pintern->Pointer-HGLOBAL_STORAGE,
676 size+HGLOBAL_STORAGE)) == NULL)
677 hnew = 0; /* Block still valid */
678 else
679 pintern->Pointer = (char *)palloc+HGLOBAL_STORAGE;
681 else
683 if(size > INT_MAX-HGLOBAL_STORAGE)
685 SetLastError(ERROR_OUTOFMEMORY);
686 hnew = 0;
688 else if((palloc=HeapAlloc(GetProcessHeap(), heap_flags, size+HGLOBAL_STORAGE))
689 == NULL)
690 hnew = 0;
691 else
693 *(HGLOBAL *)palloc = hmem;
694 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
698 else
700 if (pintern->LockCount == 0)
702 if(pintern->Pointer)
704 HeapFree(GetProcessHeap(), 0, (char *) pintern->Pointer-HGLOBAL_STORAGE);
705 pintern->Pointer = NULL;
707 hnew = hmem;
709 else
710 WARN("not freeing memory associated with locked handle\n");
714 RtlUnlockHeap(GetProcessHeap());
715 return hnew;
719 /***********************************************************************
720 * GlobalFree (KERNEL32.@)
722 * Free a global memory object.
724 * PARAMS
725 * hmem [I] Handle of the global memory object
727 * RETURNS
728 * Success: NULL
729 * Failure: The provided handle
731 * NOTES
732 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
735 HGLOBAL WINAPI GlobalFree(HGLOBAL hmem)
737 PGLOBAL32_INTERN pintern;
738 HGLOBAL hreturned;
740 RtlLockHeap(GetProcessHeap());
741 __TRY
743 hreturned = 0;
744 if(ISPOINTER(hmem)) /* POINTER */
746 if(!HeapFree(GetProcessHeap(), 0, hmem))
748 SetLastError(ERROR_INVALID_HANDLE);
749 hreturned = hmem;
752 else /* HANDLE */
754 pintern=HANDLE_TO_INTERN(hmem);
756 if(pintern->Magic==MAGIC_GLOBAL_USED)
758 pintern->Magic = 0xdead;
760 /* WIN98 does not make this test. That is you can free a */
761 /* block you have not unlocked. Go figure!! */
762 /* if(pintern->LockCount!=0) */
763 /* SetLastError(ERROR_INVALID_HANDLE); */
765 if(pintern->Pointer)
766 if(!HeapFree(GetProcessHeap(), 0, (char *)(pintern->Pointer)-HGLOBAL_STORAGE))
767 hreturned=hmem;
768 if(!HeapFree(GetProcessHeap(), 0, pintern))
769 hreturned=hmem;
771 else
773 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
774 SetLastError(ERROR_INVALID_HANDLE);
775 hreturned = hmem;
779 __EXCEPT_PAGE_FAULT
781 ERR("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
782 SetLastError( ERROR_INVALID_PARAMETER );
783 hreturned = hmem;
785 __ENDTRY
786 RtlUnlockHeap(GetProcessHeap());
787 return hreturned;
791 /***********************************************************************
792 * GlobalSize (KERNEL32.@)
794 * Get the size of a global memory object.
796 * PARAMS
797 * hmem [I] Handle of the global memory object
799 * RETURNS
800 * Failure: 0
801 * Success: Size in Bytes of the global memory object
803 * NOTES
804 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
807 SIZE_T WINAPI GlobalSize(HGLOBAL hmem)
809 SIZE_T retval;
810 PGLOBAL32_INTERN pintern;
812 if (!((ULONG_PTR)hmem >> 16))
814 SetLastError(ERROR_INVALID_HANDLE);
815 return 0;
818 if(ISPOINTER(hmem))
820 retval=HeapSize(GetProcessHeap(), 0, hmem);
822 if (retval == ~0ul) /* It might be a GMEM_MOVEABLE data pointer */
824 retval = HeapSize(GetProcessHeap(), 0, (char*)hmem - HGLOBAL_STORAGE);
825 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
828 else
830 RtlLockHeap(GetProcessHeap());
831 pintern=HANDLE_TO_INTERN(hmem);
833 if(pintern->Magic==MAGIC_GLOBAL_USED)
835 if (!pintern->Pointer) /* handle case of GlobalAlloc( ??,0) */
836 retval = 0;
837 else
839 retval = HeapSize(GetProcessHeap(), 0, (char *)pintern->Pointer - HGLOBAL_STORAGE );
840 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
843 else
845 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
846 SetLastError(ERROR_INVALID_HANDLE);
847 retval=0;
849 RtlUnlockHeap(GetProcessHeap());
851 if (retval == ~0ul) retval = 0;
852 return retval;
856 /***********************************************************************
857 * GlobalWire (KERNEL32.@)
859 LPVOID WINAPI GlobalWire(HGLOBAL hmem)
861 return GlobalLock( hmem );
865 /***********************************************************************
866 * GlobalUnWire (KERNEL32.@)
868 BOOL WINAPI GlobalUnWire(HGLOBAL hmem)
870 return GlobalUnlock( hmem);
874 /***********************************************************************
875 * GlobalFix (KERNEL32.@)
877 VOID WINAPI GlobalFix(HGLOBAL hmem)
879 GlobalLock( hmem );
883 /***********************************************************************
884 * GlobalUnfix (KERNEL32.@)
886 VOID WINAPI GlobalUnfix(HGLOBAL hmem)
888 GlobalUnlock( hmem);
892 /***********************************************************************
893 * GlobalFlags (KERNEL32.@)
895 * Get information about a global memory object.
897 * PARAMS
898 * hmem [I] Handle of the global memory object
900 * RETURNS
901 * Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid
902 * Success: Value specifying allocation flags and lock count
905 UINT WINAPI GlobalFlags(HGLOBAL hmem)
907 DWORD retval;
908 PGLOBAL32_INTERN pintern;
910 if(ISPOINTER(hmem))
912 retval=0;
914 else
916 RtlLockHeap(GetProcessHeap());
917 pintern=HANDLE_TO_INTERN(hmem);
918 if(pintern->Magic==MAGIC_GLOBAL_USED)
920 retval=pintern->LockCount + (pintern->Flags<<8);
921 if(pintern->Pointer==0)
922 retval|= GMEM_DISCARDED;
924 else
926 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
927 SetLastError(ERROR_INVALID_HANDLE);
928 retval = GMEM_INVALID_HANDLE;
930 RtlUnlockHeap(GetProcessHeap());
932 return retval;
936 /***********************************************************************
937 * GlobalCompact (KERNEL32.@)
939 SIZE_T WINAPI GlobalCompact( DWORD minfree )
941 return 0; /* GlobalCompact does nothing in Win32 */
945 /***********************************************************************
946 * LocalAlloc (KERNEL32.@)
948 * Allocate a local memory object.
950 * RETURNS
951 * Handle: Success
952 * NULL: Failure
954 * NOTES
955 * Windows memory management does not provide a separate local heap
956 * and global heap.
958 HLOCAL WINAPI LocalAlloc(
959 UINT flags, /* [in] Allocation attributes */
960 SIZE_T size /* [in] Number of bytes to allocate */
962 return GlobalAlloc( flags, size );
966 /***********************************************************************
967 * LocalCompact (KERNEL32.@)
969 SIZE_T WINAPI LocalCompact( UINT minfree )
971 return 0; /* LocalCompact does nothing in Win32 */
975 /***********************************************************************
976 * LocalFlags (KERNEL32.@)
978 * Get information about a local memory object.
980 * RETURNS
981 * Value specifying allocation flags and lock count.
982 * LMEM_INVALID_HANDLE: Failure
984 * NOTES
985 * Windows memory management does not provide a separate local heap
986 * and global heap.
988 UINT WINAPI LocalFlags(
989 HLOCAL handle /* [in] Handle of memory object */
991 return GlobalFlags( handle );
995 /***********************************************************************
996 * LocalFree (KERNEL32.@)
998 * Free a local memory object.
1000 * RETURNS
1001 * NULL: Success
1002 * Handle: Failure
1004 * NOTES
1005 * Windows memory management does not provide a separate local heap
1006 * and global heap.
1008 HLOCAL WINAPI LocalFree(
1009 HLOCAL handle /* [in] Handle of memory object */
1011 return GlobalFree( handle );
1015 /***********************************************************************
1016 * LocalHandle (KERNEL32.@)
1018 * Get the handle associated with the pointer to a local memory block.
1020 * RETURNS
1021 * Handle: Success
1022 * NULL: Failure
1024 * NOTES
1025 * Windows memory management does not provide a separate local heap
1026 * and global heap.
1028 HLOCAL WINAPI LocalHandle(
1029 LPCVOID ptr /* [in] Address of local memory block */
1031 return GlobalHandle( ptr );
1035 /***********************************************************************
1036 * LocalLock (KERNEL32.@)
1037 * Locks a local memory object and returns pointer to the first byte
1038 * of the memory block.
1040 * RETURNS
1041 * Pointer: Success
1042 * NULL: Failure
1044 * NOTES
1045 * Windows memory management does not provide a separate local heap
1046 * and global heap.
1048 LPVOID WINAPI LocalLock(
1049 HLOCAL handle /* [in] Address of local memory object */
1051 return GlobalLock( handle );
1055 /***********************************************************************
1056 * LocalReAlloc (KERNEL32.@)
1058 * Change the size or attributes of a local memory object.
1060 * RETURNS
1061 * Handle: Success
1062 * NULL: Failure
1064 * NOTES
1065 * Windows memory management does not provide a separate local heap
1066 * and global heap.
1068 HLOCAL WINAPI LocalReAlloc(
1069 HLOCAL handle, /* [in] Handle of memory object */
1070 SIZE_T size, /* [in] New size of block */
1071 UINT flags /* [in] How to reallocate object */
1073 return GlobalReAlloc( handle, size, flags );
1077 /***********************************************************************
1078 * LocalShrink (KERNEL32.@)
1080 SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
1082 return 0; /* LocalShrink does nothing in Win32 */
1086 /***********************************************************************
1087 * LocalSize (KERNEL32.@)
1089 * Get the size of a local memory object.
1091 * RETURNS
1092 * Size: Success
1093 * 0: Failure
1095 * NOTES
1096 * Windows memory management does not provide a separate local heap
1097 * and global heap.
1099 SIZE_T WINAPI LocalSize(
1100 HLOCAL handle /* [in] Handle of memory object */
1102 return GlobalSize( handle );
1106 /***********************************************************************
1107 * LocalUnlock (KERNEL32.@)
1109 * Unlock a local memory object.
1111 * RETURNS
1112 * TRUE: Object is still locked
1113 * FALSE: Object is unlocked
1115 * NOTES
1116 * Windows memory management does not provide a separate local heap
1117 * and global heap.
1119 BOOL WINAPI LocalUnlock(
1120 HLOCAL handle /* [in] Handle of memory object */
1123 if (ISPOINTER( handle ))
1125 SetLastError( ERROR_NOT_LOCKED );
1126 return FALSE;
1129 return GlobalUnlock( handle );
1133 /***********************************************************************
1134 * GlobalMemoryStatusEx (KERNEL32.@)
1135 * A version of GlobalMemoryStatus that can deal with memory over 4GB
1137 * RETURNS
1138 * TRUE
1140 BOOL WINAPI GlobalMemoryStatusEx( LPMEMORYSTATUSEX lpmemex )
1142 static MEMORYSTATUSEX cached_memstatus;
1143 static int cache_lastchecked = 0;
1144 SYSTEM_INFO si;
1145 #ifdef linux
1146 FILE *f;
1147 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
1148 unsigned long val;
1149 int mib[2];
1150 size_t size_sys;
1151 #elif defined(__APPLE__)
1152 unsigned int val;
1153 int mib[2];
1154 size_t size_sys;
1155 #elif defined(sun)
1156 unsigned long pagesize,maxpages,freepages,swapspace,swapfree;
1157 struct anoninfo swapinf;
1158 int rval;
1159 #endif
1161 if (lpmemex->dwLength != sizeof(*lpmemex))
1163 SetLastError( ERROR_INVALID_PARAMETER );
1164 return FALSE;
1167 if (time(NULL)==cache_lastchecked) {
1168 *lpmemex = cached_memstatus;
1169 return TRUE;
1171 cache_lastchecked = time(NULL);
1173 lpmemex->dwMemoryLoad = 0;
1174 lpmemex->ullTotalPhys = 16*1024*1024;
1175 lpmemex->ullAvailPhys = 16*1024*1024;
1176 lpmemex->ullTotalPageFile = 16*1024*1024;
1177 lpmemex->ullAvailPageFile = 16*1024*1024;
1179 #ifdef linux
1180 f = fopen( "/proc/meminfo", "r" );
1181 if (f)
1183 char buffer[256];
1184 unsigned long total, used, free, shared, buffers, cached;
1186 lpmemex->ullTotalPhys = lpmemex->ullAvailPhys = 0;
1187 lpmemex->ullTotalPageFile = lpmemex->ullAvailPageFile = 0;
1188 while (fgets( buffer, sizeof(buffer), f ))
1190 /* old style /proc/meminfo ... */
1191 if (sscanf( buffer, "Mem: %lu %lu %lu %lu %lu %lu",
1192 &total, &used, &free, &shared, &buffers, &cached ))
1194 lpmemex->ullTotalPhys += total;
1195 lpmemex->ullAvailPhys += free + buffers + cached;
1197 if (sscanf( buffer, "Swap: %lu %lu %lu", &total, &used, &free ))
1199 lpmemex->ullTotalPageFile += total;
1200 lpmemex->ullAvailPageFile += free;
1203 /* new style /proc/meminfo ... */
1204 if (sscanf(buffer, "MemTotal: %lu", &total))
1205 lpmemex->ullTotalPhys = (ULONG64)total*1024;
1206 if (sscanf(buffer, "MemFree: %lu", &free))
1207 lpmemex->ullAvailPhys = (ULONG64)free*1024;
1208 if (sscanf(buffer, "SwapTotal: %lu", &total))
1209 lpmemex->ullTotalPageFile = (ULONG64)total*1024;
1210 if (sscanf(buffer, "SwapFree: %lu", &free))
1211 lpmemex->ullAvailPageFile = (ULONG64)free*1024;
1212 if (sscanf(buffer, "Buffers: %lu", &buffers))
1213 lpmemex->ullAvailPhys += (ULONG64)buffers*1024;
1214 if (sscanf(buffer, "Cached: %lu", &cached))
1215 lpmemex->ullAvailPhys += (ULONG64)cached*1024;
1217 fclose( f );
1219 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1220 mib[0] = CTL_HW;
1221 mib[1] = HW_PHYSMEM;
1222 size_sys = sizeof(val);
1223 sysctl(mib, 2, &val, &size_sys, NULL, 0);
1224 if (val) lpmemex->ullTotalPhys = val;
1225 mib[1] = HW_USERMEM;
1226 size_sys = sizeof(val);
1227 sysctl(mib, 2, &val, &size_sys, NULL, 0);
1228 if (!val) val = lpmemex->ullTotalPhys;
1229 lpmemex->ullAvailPhys = val;
1230 lpmemex->ullTotalPageFile = val;
1231 lpmemex->ullAvailPageFile = val;
1232 #elif defined ( sun )
1233 pagesize=sysconf(_SC_PAGESIZE);
1234 maxpages=sysconf(_SC_PHYS_PAGES);
1235 freepages=sysconf(_SC_AVPHYS_PAGES);
1236 rval=swapctl(SC_AINFO, &swapinf);
1237 if(rval >-1)
1239 swapspace=swapinf.ani_max*pagesize;
1240 swapfree=swapinf.ani_free*pagesize;
1241 }else
1244 WARN("Swap size cannot be determined , assuming equal to physical memory\n");
1245 swapspace=maxpages*pagesize;
1246 swapfree=maxpages*pagesize;
1248 lpmemex->ullTotalPhys=pagesize*maxpages;
1249 lpmemex->ullAvailPhys = pagesize*freepages;
1250 lpmemex->ullTotalPageFile = swapspace;
1251 lpmemex->ullAvailPageFile = swapfree;
1252 #endif
1254 if (lpmemex->ullTotalPhys)
1256 lpmemex->dwMemoryLoad = (lpmemex->ullTotalPhys-lpmemex->ullAvailPhys)
1257 / (lpmemex->ullTotalPhys / 100);
1260 /* Win98 returns only the swapsize in ullTotalPageFile/ullAvailPageFile,
1261 WinXP returns the size of physical memory + swapsize;
1262 mimic the behavior of XP.
1263 Note: Project2k refuses to start if it sees less than 1Mb of free swap.
1265 lpmemex->ullTotalPageFile += lpmemex->ullTotalPhys;
1266 lpmemex->ullAvailPageFile += lpmemex->ullAvailPhys;
1268 /* Titan Quest refuses to run if TotalPageFile <= ullTotalPhys */
1269 if(lpmemex->ullTotalPageFile == lpmemex->ullTotalPhys)
1271 lpmemex->ullTotalPhys -= 1;
1272 lpmemex->ullAvailPhys -= 1;
1275 /* FIXME: should do something for other systems */
1276 GetSystemInfo(&si);
1277 lpmemex->ullTotalVirtual = (ULONG_PTR)si.lpMaximumApplicationAddress-(ULONG_PTR)si.lpMinimumApplicationAddress;
1278 /* FIXME: we should track down all the already allocated VM pages and subtract them, for now arbitrarily remove 64KB so that it matches NT */
1279 lpmemex->ullAvailVirtual = lpmemex->ullTotalVirtual-64*1024;
1281 /* MSDN says about AvailExtendedVirtual: Size of unreserved and uncommitted
1282 memory in the extended portion of the virtual address space of the calling
1283 process, in bytes.
1284 However, I don't know what this means, so set it to zero :(
1286 lpmemex->ullAvailExtendedVirtual = 0;
1288 cached_memstatus = *lpmemex;
1290 TRACE_(globalmem)("<-- LPMEMORYSTATUSEX: dwLength %d, dwMemoryLoad %d, ullTotalPhys %s, ullAvailPhys %s,"
1291 " ullTotalPageFile %s, ullAvailPageFile %s, ullTotalVirtual %s, ullAvailVirtual %s\n",
1292 lpmemex->dwLength, lpmemex->dwMemoryLoad, wine_dbgstr_longlong(lpmemex->ullTotalPhys),
1293 wine_dbgstr_longlong(lpmemex->ullAvailPhys), wine_dbgstr_longlong(lpmemex->ullTotalPageFile),
1294 wine_dbgstr_longlong(lpmemex->ullAvailPageFile), wine_dbgstr_longlong(lpmemex->ullTotalVirtual),
1295 wine_dbgstr_longlong(lpmemex->ullAvailVirtual) );
1297 return TRUE;
1300 /***********************************************************************
1301 * GlobalMemoryStatus (KERNEL32.@)
1302 * Provides information about the status of the memory, so apps can tell
1303 * roughly how much they are able to allocate
1305 * RETURNS
1306 * None
1308 VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
1310 MEMORYSTATUSEX memstatus;
1311 OSVERSIONINFOW osver;
1312 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( GetModuleHandleW(0) );
1314 /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
1315 for one extra field in the struct, and the lack of a bug, we simply
1316 call GlobalMemoryStatusEx and copy the values across. */
1317 memstatus.dwLength = sizeof(memstatus);
1318 GlobalMemoryStatusEx(&memstatus);
1320 lpBuffer->dwLength = sizeof(*lpBuffer);
1321 lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;
1323 /* Windows 2000 and later report -1 when values are greater than 4 Gb.
1324 * NT reports values modulo 4 Gb.
1327 osver.dwOSVersionInfoSize = sizeof(osver);
1328 GetVersionExW(&osver);
1330 if ( osver.dwMajorVersion >= 5 || osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
1332 lpBuffer->dwTotalPhys = min( memstatus.ullTotalPhys, MAXDWORD );
1333 lpBuffer->dwAvailPhys = min( memstatus.ullAvailPhys, MAXDWORD );
1334 /* Limit value for apps that do not expect so much memory. Remove last 512 kb to make Sacrifice demo happy. */
1335 lpBuffer->dwTotalPageFile = min( memstatus.ullTotalPageFile, 0xfff7ffff );
1336 lpBuffer->dwAvailPageFile = min( memstatus.ullAvailPageFile, MAXDWORD );
1337 lpBuffer->dwTotalVirtual = min( memstatus.ullTotalVirtual, MAXDWORD );
1338 lpBuffer->dwAvailVirtual = min( memstatus.ullAvailVirtual, MAXDWORD );
1341 else /* duplicate NT bug */
1343 lpBuffer->dwTotalPhys = memstatus.ullTotalPhys;
1344 lpBuffer->dwAvailPhys = memstatus.ullAvailPhys;
1345 lpBuffer->dwTotalPageFile = memstatus.ullTotalPageFile;
1346 lpBuffer->dwAvailPageFile = memstatus.ullAvailPageFile;
1347 lpBuffer->dwTotalVirtual = memstatus.ullTotalVirtual;
1348 lpBuffer->dwAvailVirtual = memstatus.ullAvailVirtual;
1351 /* values are limited to 2Gb unless the app has the IMAGE_FILE_LARGE_ADDRESS_AWARE flag */
1352 /* page file sizes are not limited (Adobe Illustrator 8 depends on this) */
1353 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE))
1355 if (lpBuffer->dwTotalPhys > MAXLONG) lpBuffer->dwTotalPhys = MAXLONG;
1356 if (lpBuffer->dwAvailPhys > MAXLONG) lpBuffer->dwAvailPhys = MAXLONG;
1357 if (lpBuffer->dwTotalVirtual > MAXLONG) lpBuffer->dwTotalVirtual = MAXLONG;
1358 if (lpBuffer->dwAvailVirtual > MAXLONG) lpBuffer->dwAvailVirtual = MAXLONG;
1361 /* work around for broken photoshop 4 installer */
1362 if ( lpBuffer->dwAvailPhys + lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
1363 lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 - lpBuffer->dwAvailPhys - 1;
1365 /* limit page file size for really old binaries */
1366 if (nt->OptionalHeader.MajorSubsystemVersion < 4)
1368 if (lpBuffer->dwTotalPageFile > MAXLONG) lpBuffer->dwTotalPageFile = MAXLONG;
1369 if (lpBuffer->dwAvailPageFile > MAXLONG) lpBuffer->dwAvailPageFile = MAXLONG;
1372 TRACE_(globalmem)("Length %u, MemoryLoad %u, TotalPhys %lx, AvailPhys %lx,"
1373 " TotalPageFile %lx, AvailPageFile %lx, TotalVirtual %lx, AvailVirtual %lx\n",
1374 lpBuffer->dwLength, lpBuffer->dwMemoryLoad, lpBuffer->dwTotalPhys,
1375 lpBuffer->dwAvailPhys, lpBuffer->dwTotalPageFile, lpBuffer->dwAvailPageFile,
1376 lpBuffer->dwTotalVirtual, lpBuffer->dwAvailVirtual );