widl: Fix alignment check for struct members format string.
[wine/multimedia.git] / dlls / kernel32 / heap.c
blob44545cd8fa076cde1ac5b847f46dad0c0786a2d8
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 <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <time.h>
33 #ifdef HAVE_SYS_PARAM_H
34 #include <sys/param.h>
35 #endif
36 #ifdef HAVE_SYS_SYSCTL_H
37 #include <sys/sysctl.h>
38 #endif
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
43 #ifdef sun
44 /* FIXME: Unfortunately swapctl can't be used with largefile.... */
45 # undef _FILE_OFFSET_BITS
46 # define _FILE_OFFSET_BITS 32
47 # ifdef HAVE_SYS_RESOURCE_H
48 # include <sys/resource.h>
49 # endif
50 # ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
52 # endif
53 # include <sys/swap.h>
54 #endif
57 #include "windef.h"
58 #include "winbase.h"
59 #include "winerror.h"
60 #include "winnt.h"
61 #include "winternl.h"
62 #include "excpt.h"
63 #include "wine/exception.h"
64 #include "wine/debug.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(heap);
68 /* address where we try to map the system heap */
69 #define SYSTEM_HEAP_BASE ((void*)0x80000000)
70 #define SYSTEM_HEAP_SIZE 0x1000000 /* Default heap size = 16Mb */
72 static HANDLE systemHeap; /* globally shared heap */
75 /***********************************************************************
76 * HEAP_CreateSystemHeap
78 * Create the system heap.
80 inline static HANDLE HEAP_CreateSystemHeap(void)
82 int created;
83 void *base;
84 HANDLE map, event;
86 /* create the system heap event first */
87 event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );
89 if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
90 0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
91 created = (GetLastError() != ERROR_ALREADY_EXISTS);
93 if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
95 /* pre-defined address not available */
96 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
97 return 0;
100 if (created) /* newly created heap */
102 systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
103 SYSTEM_HEAP_SIZE, NULL, NULL );
104 SetEvent( event );
106 else
108 /* wait for the heap to be initialized */
109 WaitForSingleObject( event, INFINITE );
110 systemHeap = (HANDLE)base;
112 CloseHandle( map );
113 return systemHeap;
117 /***********************************************************************
118 * HeapCreate (KERNEL32.@)
120 * Create a heap object.
122 * RETURNS
123 * Handle of heap: Success
124 * NULL: Failure
126 HANDLE WINAPI HeapCreate(
127 DWORD flags, /* [in] Heap allocation flag */
128 SIZE_T initialSize, /* [in] Initial heap size */
129 SIZE_T maxSize /* [in] Maximum heap size */
131 HANDLE ret;
133 if ( flags & HEAP_SHARED )
135 if (!systemHeap) HEAP_CreateSystemHeap();
136 else WARN( "Shared Heap requested, returning system heap.\n" );
137 ret = systemHeap;
139 else
141 ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
142 if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
144 return ret;
148 /***********************************************************************
149 * HeapDestroy (KERNEL32.@)
151 * Destroy a heap object.
153 * RETURNS
154 * TRUE: Success
155 * FALSE: Failure
157 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
159 if (heap == systemHeap)
161 WARN( "attempt to destroy system heap, returning TRUE!\n" );
162 return TRUE;
164 if (!RtlDestroyHeap( heap )) return TRUE;
165 SetLastError( ERROR_INVALID_HANDLE );
166 return FALSE;
170 /***********************************************************************
171 * HeapCompact (KERNEL32.@)
173 SIZE_T WINAPI HeapCompact( HANDLE heap, DWORD flags )
175 return RtlCompactHeap( heap, flags );
179 /***********************************************************************
180 * HeapValidate (KERNEL32.@)
181 * Validates a specified heap.
183 * NOTES
184 * Flags is ignored.
186 * RETURNS
187 * TRUE: Success
188 * FALSE: Failure
190 BOOL WINAPI HeapValidate(
191 HANDLE heap, /* [in] Handle to the heap */
192 DWORD flags, /* [in] Bit flags that control access during operation */
193 LPCVOID block /* [in] Optional pointer to memory block to validate */
195 return RtlValidateHeap( heap, flags, block );
199 /***********************************************************************
200 * HeapWalk (KERNEL32.@)
201 * Enumerates the memory blocks in a specified heap.
203 * TODO
204 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
205 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
207 * RETURNS
208 * TRUE: Success
209 * FALSE: Failure
211 BOOL WINAPI HeapWalk(
212 HANDLE heap, /* [in] Handle to heap to enumerate */
213 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
215 NTSTATUS ret = RtlWalkHeap( heap, entry );
216 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
217 return !ret;
221 /***********************************************************************
222 * HeapLock (KERNEL32.@)
223 * Attempts to acquire the critical section object for a specified heap.
225 * RETURNS
226 * TRUE: Success
227 * FALSE: Failure
229 BOOL WINAPI HeapLock(
230 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
232 return RtlLockHeap( heap );
236 /***********************************************************************
237 * HeapUnlock (KERNEL32.@)
238 * Releases ownership of the critical section object.
240 * RETURNS
241 * TRUE: Success
242 * FALSE: Failure
244 BOOL WINAPI HeapUnlock(
245 HANDLE heap /* [in] Handle to the heap to unlock */
247 return RtlUnlockHeap( heap );
251 /***********************************************************************
252 * GetProcessHeap (KERNEL32.@)
254 HANDLE WINAPI GetProcessHeap(void)
256 return NtCurrentTeb()->Peb->ProcessHeap;
260 /***********************************************************************
261 * GetProcessHeaps (KERNEL32.@)
263 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
265 return RtlGetProcessHeaps( count, heaps );
269 /* These are needed so that we can call the functions from inside kernel itself */
271 /***********************************************************************
272 * HeapAlloc (KERNEL32.@)
274 LPVOID WINAPI HeapAlloc( HANDLE heap, DWORD flags, SIZE_T size )
276 return RtlAllocateHeap( heap, flags, size );
279 BOOL WINAPI HeapFree( HANDLE heap, DWORD flags, LPVOID ptr )
281 return RtlFreeHeap( heap, flags, ptr );
284 LPVOID WINAPI HeapReAlloc( HANDLE heap, DWORD flags, LPVOID ptr, SIZE_T size )
286 return RtlReAllocateHeap( heap, flags, ptr, size );
289 SIZE_T WINAPI HeapSize( HANDLE heap, DWORD flags, LPVOID ptr )
291 return RtlSizeHeap( heap, flags, ptr );
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) ((HGLOBAL) &((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 8 /* 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 TRACE("() flags=%04x\n", flags );
361 if((flags & GMEM_MOVEABLE)==0) /* POINTER */
363 palloc=HeapAlloc(GetProcessHeap(), hpflags, size);
364 return (HGLOBAL) palloc;
366 else /* HANDLE */
368 if (size > INT_MAX-HGLOBAL_STORAGE)
370 SetLastError(ERROR_OUTOFMEMORY);
371 return 0;
374 RtlLockHeap(GetProcessHeap());
376 pintern = HeapAlloc(GetProcessHeap(), 0, sizeof(GLOBAL32_INTERN));
377 if (pintern)
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 RtlUnlockHeap(GetProcessHeap());
402 return pintern ? INTERN_TO_HANDLE(pintern) : 0;
407 /***********************************************************************
408 * GlobalLock (KERNEL32.@)
410 * Lock a global memory object and return a pointer to first byte of the memory
412 * PARAMS
413 * hmem [I] Handle of the global memory object
415 * RETURNS
416 * Success: Pointer to first byte of the memory block
417 * Failure: NULL
419 * NOTES
420 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
423 LPVOID WINAPI GlobalLock(HGLOBAL hmem)
425 PGLOBAL32_INTERN pintern;
426 LPVOID palloc;
428 if (ISPOINTER(hmem))
429 return IsBadReadPtr(hmem, 1) ? NULL : hmem;
431 RtlLockHeap(GetProcessHeap());
432 __TRY
434 pintern = HANDLE_TO_INTERN(hmem);
435 if (pintern->Magic == MAGIC_GLOBAL_USED)
437 palloc = pintern->Pointer;
438 if (!pintern->Pointer)
439 SetLastError(ERROR_DISCARDED);
440 else if (pintern->LockCount < GMEM_LOCKCOUNT)
441 pintern->LockCount++;
443 else
445 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
446 palloc = NULL;
447 SetLastError(ERROR_INVALID_HANDLE);
450 __EXCEPT_PAGE_FAULT
452 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
453 palloc = NULL;
454 SetLastError(ERROR_INVALID_HANDLE);
456 __ENDTRY
457 RtlUnlockHeap(GetProcessHeap());
458 return palloc;
462 /***********************************************************************
463 * GlobalUnlock (KERNEL32.@)
465 * Unlock a global memory object.
467 * PARAMS
468 * hmem [I] Handle of the global memory object
470 * RETURNS
471 * Success: Object is still locked
472 * Failure: FALSE (The Object is unlocked)
474 * NOTES
475 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
478 BOOL WINAPI GlobalUnlock(HGLOBAL hmem)
480 PGLOBAL32_INTERN pintern;
481 BOOL locked;
483 if (ISPOINTER(hmem)) return FALSE;
485 RtlLockHeap(GetProcessHeap());
486 __TRY
488 pintern=HANDLE_TO_INTERN(hmem);
489 if(pintern->Magic==MAGIC_GLOBAL_USED)
491 if(pintern->LockCount)
493 pintern->LockCount--;
494 locked = (pintern->LockCount != 0);
495 if (!locked) SetLastError(NO_ERROR);
497 else
499 WARN("%p not locked\n", hmem);
500 SetLastError(ERROR_NOT_LOCKED);
501 locked = FALSE;
504 else
506 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
507 SetLastError(ERROR_INVALID_HANDLE);
508 locked=FALSE;
511 __EXCEPT_PAGE_FAULT
513 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
514 SetLastError( ERROR_INVALID_PARAMETER );
515 locked=FALSE;
517 __ENDTRY
518 RtlUnlockHeap(GetProcessHeap());
519 return locked;
523 /***********************************************************************
524 * GlobalHandle (KERNEL32.@)
526 * Get the handle associated with the pointer to a global memory block.
528 * RETURNS
529 * Handle: Success
530 * NULL: Failure
532 HGLOBAL WINAPI GlobalHandle(
533 LPCVOID pmem /* [in] Pointer to global memory block */
535 HGLOBAL handle;
536 PGLOBAL32_INTERN maybe_intern;
537 LPCVOID test;
539 if (!pmem)
541 SetLastError( ERROR_INVALID_PARAMETER );
542 return 0;
545 RtlLockHeap(GetProcessHeap());
546 __TRY
548 handle = 0;
550 /* note that if pmem is a pointer to a block allocated by */
551 /* GlobalAlloc with GMEM_MOVEABLE then magic test in HeapValidate */
552 /* will fail. */
553 if (ISPOINTER(pmem)) {
554 if (HeapValidate( GetProcessHeap(), 0, pmem )) {
555 handle = (HGLOBAL)pmem; /* valid fixed block */
556 break;
558 handle = POINTER_TO_HANDLE(pmem);
559 } else
560 handle = (HGLOBAL)pmem;
562 /* Now test handle either passed in or retrieved from pointer */
563 maybe_intern = HANDLE_TO_INTERN( handle );
564 if (maybe_intern->Magic == MAGIC_GLOBAL_USED) {
565 test = maybe_intern->Pointer;
566 if (HeapValidate( GetProcessHeap(), 0, (const char *)test - HGLOBAL_STORAGE ) && /* obj(-handle) valid arena? */
567 HeapValidate( GetProcessHeap(), 0, maybe_intern )) /* intern valid arena? */
568 break; /* valid moveable block */
570 handle = 0;
571 SetLastError( ERROR_INVALID_HANDLE );
573 __EXCEPT_PAGE_FAULT
575 SetLastError( ERROR_INVALID_HANDLE );
576 handle = 0;
578 __ENDTRY
579 RtlUnlockHeap(GetProcessHeap());
581 return handle;
585 /***********************************************************************
586 * GlobalReAlloc (KERNEL32.@)
588 * Change the size or attributes of a global memory object.
590 * RETURNS
591 * Handle: Success
592 * NULL: Failure
594 HGLOBAL WINAPI GlobalReAlloc(
595 HGLOBAL hmem, /* [in] Handle of global memory object */
596 SIZE_T size, /* [in] New size of block */
597 UINT flags /* [in] How to reallocate object */
599 LPVOID palloc;
600 HGLOBAL hnew;
601 PGLOBAL32_INTERN pintern;
602 DWORD heap_flags = (flags & GMEM_ZEROINIT) ? HEAP_ZERO_MEMORY : 0;
604 hnew = 0;
605 RtlLockHeap(GetProcessHeap());
606 if(flags & GMEM_MODIFY) /* modify flags */
608 if( ISPOINTER(hmem) && (flags & GMEM_MOVEABLE))
610 /* make a fixed block moveable
611 * actually only NT is able to do this. But it's soo simple
613 if (hmem == 0)
615 WARN("GlobalReAlloc with null handle!\n");
616 SetLastError( ERROR_NOACCESS );
617 hnew = 0;
619 else
621 size = HeapSize(GetProcessHeap(), 0, (LPVOID)hmem);
622 hnew = GlobalAlloc(flags, size);
623 palloc = GlobalLock(hnew);
624 memcpy(palloc, (LPVOID)hmem, size);
625 GlobalUnlock(hnew);
626 GlobalFree(hmem);
629 else if( ISPOINTER(hmem) &&(flags & GMEM_DISCARDABLE))
631 /* change the flags to make our block "discardable" */
632 pintern=HANDLE_TO_INTERN(hmem);
633 pintern->Flags = pintern->Flags | (GMEM_DISCARDABLE >> 8);
634 hnew=hmem;
636 else
638 SetLastError(ERROR_INVALID_PARAMETER);
639 hnew = 0;
642 else
644 if(ISPOINTER(hmem))
646 /* reallocate fixed memory */
647 hnew=HeapReAlloc(GetProcessHeap(), heap_flags, hmem, size);
649 else
651 /* reallocate a moveable block */
652 pintern=HANDLE_TO_INTERN(hmem);
654 #if 0
655 /* Apparently Windows doesn't care whether the handle is locked at this point */
656 /* See also the same comment in GlobalFree() */
657 if(pintern->LockCount>1) {
658 ERR("handle 0x%08lx is still locked, cannot realloc!\n",(DWORD)hmem);
659 SetLastError(ERROR_INVALID_HANDLE);
660 } else
661 #endif
662 if(size!=0)
664 hnew=hmem;
665 if(pintern->Pointer)
667 if(size > INT_MAX-HGLOBAL_STORAGE)
669 SetLastError(ERROR_OUTOFMEMORY);
670 hnew = 0;
672 else if((palloc = HeapReAlloc(GetProcessHeap(), heap_flags,
673 (char *) pintern->Pointer-HGLOBAL_STORAGE,
674 size+HGLOBAL_STORAGE)) == NULL)
675 hnew = 0; /* Block still valid */
676 else
677 pintern->Pointer = (char *)palloc+HGLOBAL_STORAGE;
679 else
681 if(size > INT_MAX-HGLOBAL_STORAGE)
683 SetLastError(ERROR_OUTOFMEMORY);
684 hnew = 0;
686 else if((palloc=HeapAlloc(GetProcessHeap(), heap_flags, size+HGLOBAL_STORAGE))
687 == NULL)
688 hnew = 0;
689 else
691 *(HGLOBAL *)palloc = hmem;
692 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
696 else
698 if (pintern->LockCount == 0)
700 if(pintern->Pointer)
702 HeapFree(GetProcessHeap(), 0, (char *) pintern->Pointer-HGLOBAL_STORAGE);
703 pintern->Pointer = NULL;
705 hnew = hmem;
707 else
708 WARN("not freeing memory associated with locked handle\n");
712 RtlUnlockHeap(GetProcessHeap());
713 return hnew;
717 /***********************************************************************
718 * GlobalFree (KERNEL32.@)
720 * Free a global memory object.
722 * PARAMS
723 * hmem [I] Handle of the global memory object
725 * RETURNS
726 * Success: NULL
727 * Failure: The provided handle
729 * NOTES
730 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
733 HGLOBAL WINAPI GlobalFree(HGLOBAL hmem)
735 PGLOBAL32_INTERN pintern;
736 HGLOBAL hreturned;
738 RtlLockHeap(GetProcessHeap());
739 __TRY
741 hreturned = 0;
742 if(ISPOINTER(hmem)) /* POINTER */
744 if(!HeapFree(GetProcessHeap(), 0, (LPVOID) hmem)) hmem = 0;
746 else /* HANDLE */
748 pintern=HANDLE_TO_INTERN(hmem);
750 if(pintern->Magic==MAGIC_GLOBAL_USED)
752 pintern->Magic = 0xdead;
754 /* WIN98 does not make this test. That is you can free a */
755 /* block you have not unlocked. Go figure!! */
756 /* if(pintern->LockCount!=0) */
757 /* SetLastError(ERROR_INVALID_HANDLE); */
759 if(pintern->Pointer)
760 if(!HeapFree(GetProcessHeap(), 0, (char *)(pintern->Pointer)-HGLOBAL_STORAGE))
761 hreturned=hmem;
762 if(!HeapFree(GetProcessHeap(), 0, pintern))
763 hreturned=hmem;
765 else
767 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
768 SetLastError(ERROR_INVALID_HANDLE);
769 hreturned = hmem;
773 __EXCEPT_PAGE_FAULT
775 ERR("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
776 SetLastError( ERROR_INVALID_PARAMETER );
777 hreturned = hmem;
779 __ENDTRY
780 RtlUnlockHeap(GetProcessHeap());
781 return hreturned;
785 /***********************************************************************
786 * GlobalSize (KERNEL32.@)
788 * Get the size of a global memory object.
790 * PARAMS
791 * hmem [I] Handle of the global memory object
793 * RETURNS
794 * Failure: 0
795 * Success: Size in Bytes of the global memory object
797 * NOTES
798 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
801 SIZE_T WINAPI GlobalSize(HGLOBAL hmem)
803 DWORD retval;
804 PGLOBAL32_INTERN pintern;
806 if (!hmem) return 0;
808 if(ISPOINTER(hmem))
810 retval=HeapSize(GetProcessHeap(), 0, (LPVOID) hmem);
812 else
814 RtlLockHeap(GetProcessHeap());
815 pintern=HANDLE_TO_INTERN(hmem);
817 if(pintern->Magic==MAGIC_GLOBAL_USED)
819 if (!pintern->Pointer) /* handle case of GlobalAlloc( ??,0) */
820 retval = 0;
821 else
823 retval = HeapSize(GetProcessHeap(), 0,
824 (char *)(pintern->Pointer) - HGLOBAL_STORAGE );
825 if (retval != (DWORD)-1) retval -= HGLOBAL_STORAGE;
828 else
830 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
831 SetLastError(ERROR_INVALID_HANDLE);
832 retval=0;
834 RtlUnlockHeap(GetProcessHeap());
836 /* HeapSize returns 0xffffffff on failure */
837 if (retval == 0xffffffff) retval = 0;
838 return retval;
842 /***********************************************************************
843 * GlobalWire (KERNEL32.@)
845 LPVOID WINAPI GlobalWire(HGLOBAL hmem)
847 return GlobalLock( hmem );
851 /***********************************************************************
852 * GlobalUnWire (KERNEL32.@)
854 BOOL WINAPI GlobalUnWire(HGLOBAL hmem)
856 return GlobalUnlock( hmem);
860 /***********************************************************************
861 * GlobalFix (KERNEL32.@)
863 VOID WINAPI GlobalFix(HGLOBAL hmem)
865 GlobalLock( hmem );
869 /***********************************************************************
870 * GlobalUnfix (KERNEL32.@)
872 VOID WINAPI GlobalUnfix(HGLOBAL hmem)
874 GlobalUnlock( hmem);
878 /***********************************************************************
879 * GlobalFlags (KERNEL32.@)
881 * Get information about a global memory object.
883 * PARAMS
884 * hmem [I] Handle of the global memory object
886 * RETURNS
887 * Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid
888 * Success: Value specifying allocation flags and lock count
891 UINT WINAPI GlobalFlags(HGLOBAL hmem)
893 DWORD retval;
894 PGLOBAL32_INTERN pintern;
896 if(ISPOINTER(hmem))
898 retval=0;
900 else
902 RtlLockHeap(GetProcessHeap());
903 pintern=HANDLE_TO_INTERN(hmem);
904 if(pintern->Magic==MAGIC_GLOBAL_USED)
906 retval=pintern->LockCount + (pintern->Flags<<8);
907 if(pintern->Pointer==0)
908 retval|= GMEM_DISCARDED;
910 else
912 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
913 SetLastError(ERROR_INVALID_HANDLE);
914 retval = GMEM_INVALID_HANDLE;
916 RtlUnlockHeap(GetProcessHeap());
918 return retval;
922 /***********************************************************************
923 * GlobalCompact (KERNEL32.@)
925 SIZE_T WINAPI GlobalCompact( DWORD minfree )
927 return 0; /* GlobalCompact does nothing in Win32 */
931 /***********************************************************************
932 * LocalAlloc (KERNEL32.@)
934 * Allocate a local memory object.
936 * RETURNS
937 * Handle: Success
938 * NULL: Failure
940 * NOTES
941 * Windows memory management does not provide a separate local heap
942 * and global heap.
944 HLOCAL WINAPI LocalAlloc(
945 UINT flags, /* [in] Allocation attributes */
946 SIZE_T size /* [in] Number of bytes to allocate */
948 return (HLOCAL)GlobalAlloc( flags, size );
952 /***********************************************************************
953 * LocalCompact (KERNEL32.@)
955 SIZE_T WINAPI LocalCompact( UINT minfree )
957 return 0; /* LocalCompact does nothing in Win32 */
961 /***********************************************************************
962 * LocalFlags (KERNEL32.@)
964 * Get information about a local memory object.
966 * RETURNS
967 * Value specifying allocation flags and lock count.
968 * LMEM_INVALID_HANDLE: Failure
970 * NOTES
971 * Windows memory management does not provide a separate local heap
972 * and global heap.
974 UINT WINAPI LocalFlags(
975 HLOCAL handle /* [in] Handle of memory object */
977 return GlobalFlags( (HGLOBAL)handle );
981 /***********************************************************************
982 * LocalFree (KERNEL32.@)
984 * Free a local memory object.
986 * RETURNS
987 * NULL: Success
988 * Handle: Failure
990 * NOTES
991 * Windows memory management does not provide a separate local heap
992 * and global heap.
994 HLOCAL WINAPI LocalFree(
995 HLOCAL handle /* [in] Handle of memory object */
997 return (HLOCAL)GlobalFree( (HGLOBAL)handle );
1001 /***********************************************************************
1002 * LocalHandle (KERNEL32.@)
1004 * Get the handle associated with the pointer to a local memory block.
1006 * RETURNS
1007 * Handle: Success
1008 * NULL: Failure
1010 * NOTES
1011 * Windows memory management does not provide a separate local heap
1012 * and global heap.
1014 HLOCAL WINAPI LocalHandle(
1015 LPCVOID ptr /* [in] Address of local memory block */
1017 return (HLOCAL)GlobalHandle( ptr );
1021 /***********************************************************************
1022 * LocalLock (KERNEL32.@)
1023 * Locks a local memory object and returns pointer to the first byte
1024 * of the memory block.
1026 * RETURNS
1027 * Pointer: Success
1028 * NULL: Failure
1030 * NOTES
1031 * Windows memory management does not provide a separate local heap
1032 * and global heap.
1034 LPVOID WINAPI LocalLock(
1035 HLOCAL handle /* [in] Address of local memory object */
1037 return GlobalLock( (HGLOBAL)handle );
1041 /***********************************************************************
1042 * LocalReAlloc (KERNEL32.@)
1044 * Change the size or attributes of a local memory object.
1046 * RETURNS
1047 * Handle: Success
1048 * NULL: Failure
1050 * NOTES
1051 * Windows memory management does not provide a separate local heap
1052 * and global heap.
1054 HLOCAL WINAPI LocalReAlloc(
1055 HLOCAL handle, /* [in] Handle of memory object */
1056 SIZE_T size, /* [in] New size of block */
1057 UINT flags /* [in] How to reallocate object */
1059 return (HLOCAL)GlobalReAlloc( (HGLOBAL)handle, size, flags );
1063 /***********************************************************************
1064 * LocalShrink (KERNEL32.@)
1066 SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
1068 return 0; /* LocalShrink does nothing in Win32 */
1072 /***********************************************************************
1073 * LocalSize (KERNEL32.@)
1075 * Get the size of a local memory object.
1077 * RETURNS
1078 * Size: Success
1079 * 0: Failure
1081 * NOTES
1082 * Windows memory management does not provide a separate local heap
1083 * and global heap.
1085 SIZE_T WINAPI LocalSize(
1086 HLOCAL handle /* [in] Handle of memory object */
1088 return GlobalSize( (HGLOBAL)handle );
1092 /***********************************************************************
1093 * LocalUnlock (KERNEL32.@)
1095 * Unlock a local memory object.
1097 * RETURNS
1098 * TRUE: Object is still locked
1099 * FALSE: Object is unlocked
1101 * NOTES
1102 * Windows memory management does not provide a separate local heap
1103 * and global heap.
1105 BOOL WINAPI LocalUnlock(
1106 HLOCAL handle /* [in] Handle of memory object */
1108 return GlobalUnlock( (HGLOBAL)handle );
1112 /**********************************************************************
1113 * AllocMappedBuffer (KERNEL32.38)
1115 * This is an undocumented KERNEL32 function that
1116 * SMapLS's a GlobalAlloc'ed buffer.
1118 * RETURNS
1119 * EDI register: pointer to buffer
1121 * NOTES
1122 * The buffer is preceded by 8 bytes:
1123 * ...
1124 * edi+0 buffer
1125 * edi-4 SEGPTR to buffer
1126 * edi-8 some magic Win95 needs for SUnMapLS
1127 * (we use it for the memory handle)
1129 * The SEGPTR is used by the caller!
1131 void WINAPI __regs_AllocMappedBuffer(
1132 CONTEXT86 *context /* [in] EDI register: size of buffer to allocate */
1134 HGLOBAL handle = GlobalAlloc(0, context->Edi + 8);
1135 DWORD *buffer = (DWORD *)GlobalLock(handle);
1136 DWORD ptr = 0;
1138 if (buffer)
1139 if (!(ptr = MapLS(buffer + 2)))
1141 GlobalUnlock(handle);
1142 GlobalFree(handle);
1145 if (!ptr)
1146 context->Eax = context->Edi = 0;
1147 else
1149 buffer[0] = (DWORD)handle;
1150 buffer[1] = ptr;
1152 context->Eax = (DWORD) ptr;
1153 context->Edi = (DWORD)(buffer + 2);
1156 #ifdef DEFINE_REGS_ENTRYPOINT
1157 DEFINE_REGS_ENTRYPOINT( AllocMappedBuffer, 0, 0 );
1158 #endif
1160 /**********************************************************************
1161 * FreeMappedBuffer (KERNEL32.39)
1163 * Free a buffer allocated by AllocMappedBuffer
1165 * RETURNS
1166 * Nothing.
1168 void WINAPI __regs_FreeMappedBuffer(
1169 CONTEXT86 *context /* [in] EDI register: pointer to buffer */
1171 if (context->Edi)
1173 DWORD *buffer = (DWORD *)context->Edi - 2;
1175 UnMapLS(buffer[1]);
1177 GlobalUnlock((HGLOBAL)buffer[0]);
1178 GlobalFree((HGLOBAL)buffer[0]);
1181 #ifdef DEFINE_REGS_ENTRYPOINT
1182 DEFINE_REGS_ENTRYPOINT( FreeMappedBuffer, 0, 0 );
1183 #endif
1185 /***********************************************************************
1186 * GlobalMemoryStatusEx (KERNEL32.@)
1187 * A version of GlobalMemoryStatus that can deal with memory over 4GB
1189 * RETURNS
1190 * TRUE
1192 BOOL WINAPI GlobalMemoryStatusEx( LPMEMORYSTATUSEX lpmemex )
1194 static MEMORYSTATUSEX cached_memstatus;
1195 static int cache_lastchecked = 0;
1196 SYSTEM_INFO si;
1197 #ifdef linux
1198 FILE *f;
1199 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
1200 unsigned long val;
1201 int size_sys, mib[2];
1202 #elif defined(__APPLE__)
1203 unsigned int val;
1204 int mib[2];
1205 size_t size_sys;
1206 #elif defined(sun)
1207 unsigned long pagesize,maxpages,freepages,swapspace,swapfree;
1208 struct anoninfo swapinf;
1209 int rval;
1210 #endif
1212 if (time(NULL)==cache_lastchecked) {
1213 memcpy(lpmemex,&cached_memstatus,sizeof(*lpmemex));
1214 return TRUE;
1216 cache_lastchecked = time(NULL);
1218 lpmemex->dwLength = sizeof(*lpmemex);
1219 lpmemex->dwMemoryLoad = 0;
1220 lpmemex->ullTotalPhys = 16*1024*1024;
1221 lpmemex->ullAvailPhys = 16*1024*1024;
1222 lpmemex->ullTotalPageFile = 16*1024*1024;
1223 lpmemex->ullAvailPageFile = 16*1024*1024;
1225 #ifdef linux
1226 f = fopen( "/proc/meminfo", "r" );
1227 if (f)
1229 char buffer[256];
1230 unsigned long total, used, free, shared, buffers, cached;
1232 lpmemex->ullTotalPhys = lpmemex->ullAvailPhys = 0;
1233 lpmemex->ullTotalPageFile = lpmemex->ullAvailPageFile = 0;
1234 while (fgets( buffer, sizeof(buffer), f ))
1236 /* old style /proc/meminfo ... */
1237 if (sscanf( buffer, "Mem: %lu %lu %lu %lu %lu %lu",
1238 &total, &used, &free, &shared, &buffers, &cached ))
1240 lpmemex->ullTotalPhys += total;
1241 lpmemex->ullAvailPhys += free + buffers + cached;
1243 if (sscanf( buffer, "Swap: %lu %lu %lu", &total, &used, &free ))
1245 lpmemex->ullTotalPageFile += total;
1246 lpmemex->ullAvailPageFile += free;
1249 /* new style /proc/meminfo ... */
1250 if (sscanf(buffer, "MemTotal: %lu", &total))
1251 lpmemex->ullTotalPhys = total*1024;
1252 if (sscanf(buffer, "MemFree: %lu", &free))
1253 lpmemex->ullAvailPhys = free*1024;
1254 if (sscanf(buffer, "SwapTotal: %lu", &total))
1255 lpmemex->ullTotalPageFile = total*1024;
1256 if (sscanf(buffer, "SwapFree: %lu", &free))
1257 lpmemex->ullAvailPageFile = free*1024;
1258 if (sscanf(buffer, "Buffers: %lu", &buffers))
1259 lpmemex->ullAvailPhys += buffers*1024;
1260 if (sscanf(buffer, "Cached: %lu", &cached))
1261 lpmemex->ullAvailPhys += cached*1024;
1263 fclose( f );
1265 if (lpmemex->ullTotalPhys)
1267 DWORDLONG TotalPhysical = lpmemex->ullTotalPhys+lpmemex->ullTotalPageFile;
1268 DWORDLONG AvailPhysical = lpmemex->ullAvailPhys+lpmemex->ullAvailPageFile;
1269 lpmemex->dwMemoryLoad = (TotalPhysical-AvailPhysical)
1270 / (TotalPhysical / 100);
1273 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
1274 mib[0] = CTL_HW;
1275 mib[1] = HW_PHYSMEM;
1276 size_sys = sizeof(val);
1277 sysctl(mib, 2, &val, &size_sys, NULL, 0);
1278 if (val) lpmemex->ullTotalPhys = val;
1279 mib[1] = HW_USERMEM;
1280 size_sys = sizeof(val);
1281 sysctl(mib, 2, &val, &size_sys, NULL, 0);
1282 if (!val) val = lpmemex->ullTotalPhys;
1283 lpmemex->ullAvailPhys = val;
1284 lpmemex->ullTotalPageFile = val;
1285 lpmemex->ullAvailPageFile = val;
1286 lpmemex->dwMemoryLoad = lpmemex->ullTotalPhys - lpmemex->ullAvailPhys;
1287 #elif defined ( sun )
1288 pagesize=sysconf(_SC_PAGESIZE);
1289 maxpages=sysconf(_SC_PHYS_PAGES);
1290 freepages=sysconf(_SC_AVPHYS_PAGES);
1291 rval=swapctl(SC_AINFO, &swapinf);
1292 if(rval >-1)
1294 swapspace=swapinf.ani_max*pagesize;
1295 swapfree=swapinf.ani_free*pagesize;
1296 }else
1299 WARN("Swap size cannot be determined , assuming equal to physical memory\n");
1300 swapspace=maxpages*pagesize;
1301 swapfree=maxpages*pagesize;
1303 lpmemex->ullTotalPhys=pagesize*maxpages;
1304 lpmemex->ullAvailPhys = pagesize*freepages;
1305 lpmemex->ullTotalPageFile = swapspace;
1306 lpmemex->ullAvailPageFile = swapfree;
1307 lpmemex->dwMemoryLoad = lpmemex->ullTotalPhys - lpmemex->ullAvailPhys;
1308 #endif
1310 /* Project2k refuses to start if it sees less than 1Mb of free swap */
1311 if (lpmemex->ullTotalPageFile < lpmemex->ullTotalPhys)
1312 lpmemex->ullTotalPageFile = lpmemex->ullTotalPhys;
1313 if (lpmemex->ullAvailPageFile < lpmemex->ullAvailPhys)
1314 lpmemex->ullAvailPageFile = lpmemex->ullAvailPhys;
1316 /* FIXME: should do something for other systems */
1317 GetSystemInfo(&si);
1318 lpmemex->ullTotalVirtual = (char*)si.lpMaximumApplicationAddress-(char*)si.lpMinimumApplicationAddress;
1319 /* FIXME: we should track down all the already allocated VM pages and substract them, for now arbitrarily remove 64KB so that it matches NT */
1320 lpmemex->ullAvailVirtual = lpmemex->ullTotalVirtual-64*1024;
1322 /* MSDN says about AvailExtendedVirtual: Size of unreserved and uncommitted
1323 memory in the extended portion of the virtual address space of the calling
1324 process, in bytes.
1325 However, I don't know what this means, so set it to zero :(
1327 lpmemex->ullAvailExtendedVirtual = 0;
1329 memcpy(&cached_memstatus,lpmemex,sizeof(*lpmemex));
1331 TRACE("<-- LPMEMORYSTATUSEX: dwLength %d, dwMemoryLoad %d, ullTotalPhys %s, ullAvailPhys %s,"
1332 " ullTotalPageFile %s, ullAvailPageFile %s, ullTotalVirtual %s, ullAvailVirtual %s\n",
1333 lpmemex->dwLength, lpmemex->dwMemoryLoad, wine_dbgstr_longlong(lpmemex->ullTotalPhys),
1334 wine_dbgstr_longlong(lpmemex->ullAvailPhys), wine_dbgstr_longlong(lpmemex->ullTotalPageFile),
1335 wine_dbgstr_longlong(lpmemex->ullAvailPageFile), wine_dbgstr_longlong(lpmemex->ullTotalVirtual),
1336 wine_dbgstr_longlong(lpmemex->ullAvailVirtual) );
1338 return TRUE;
1341 /***********************************************************************
1342 * GlobalMemoryStatus (KERNEL32.@)
1343 * Provides information about the status of the memory, so apps can tell
1344 * roughly how much they are able to allocate
1346 * RETURNS
1347 * None
1349 VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
1351 MEMORYSTATUSEX memstatus;
1352 OSVERSIONINFOW osver;
1354 /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
1355 for one extra field in the struct, and the lack of a bug, we simply
1356 call GlobalMemoryStatusEx and copy the values across. */
1357 GlobalMemoryStatusEx(&memstatus);
1359 lpBuffer->dwLength = sizeof(*lpBuffer);
1360 lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;
1362 /* Windows 2000 and later report -1 when values are greater than 4 Gb.
1363 * NT reports values modulo 4 Gb.
1364 * Values between 2 Gb and 4 Gb are rounded down to 2 Gb.
1367 osver.dwOSVersionInfoSize = sizeof(osver);
1368 GetVersionExW(&osver);
1370 if ( osver.dwMajorVersion >= 5 )
1372 lpBuffer->dwTotalPhys = (memstatus.ullTotalPhys > MAXDWORD) ? MAXDWORD :
1373 (memstatus.ullTotalPhys > MAXLONG) ? MAXLONG : memstatus.ullTotalPhys;
1374 lpBuffer->dwAvailPhys = (memstatus.ullAvailPhys > MAXDWORD) ? MAXDWORD :
1375 (memstatus.ullAvailPhys > MAXLONG) ? MAXLONG : memstatus.ullAvailPhys;
1376 lpBuffer->dwTotalPageFile = (memstatus.ullTotalPageFile > MAXDWORD) ? MAXDWORD :
1377 (memstatus.ullTotalPageFile > MAXLONG) ? MAXLONG : memstatus.ullTotalPageFile;
1378 lpBuffer->dwAvailPageFile = (memstatus.ullAvailPageFile > MAXDWORD) ? MAXDWORD :
1379 (memstatus.ullAvailPageFile > MAXLONG) ? MAXLONG : memstatus.ullAvailPageFile;
1380 lpBuffer->dwTotalVirtual = (memstatus.ullTotalVirtual > MAXDWORD) ? MAXDWORD :
1381 (memstatus.ullTotalVirtual > MAXLONG) ? MAXLONG : memstatus.ullTotalVirtual;
1382 lpBuffer->dwAvailVirtual = (memstatus.ullAvailVirtual > MAXDWORD) ? MAXDWORD :
1383 (memstatus.ullAvailVirtual > MAXLONG) ? MAXLONG : memstatus.ullAvailVirtual;
1385 else /* duplicate NT bug */
1387 lpBuffer->dwTotalPhys = (memstatus.ullTotalPhys > MAXDWORD) ? memstatus.ullTotalPhys :
1388 (memstatus.ullTotalPhys > MAXLONG) ? MAXLONG : memstatus.ullTotalPhys;
1389 lpBuffer->dwAvailPhys = (memstatus.ullAvailPhys > MAXDWORD) ? memstatus.ullAvailPhys :
1390 (memstatus.ullAvailPhys > MAXLONG) ? MAXLONG : memstatus.ullAvailPhys;
1391 lpBuffer->dwTotalPageFile = (memstatus.ullTotalPageFile > MAXDWORD) ? memstatus.ullTotalPageFile :
1392 (memstatus.ullTotalPageFile > MAXLONG) ? MAXLONG : memstatus.ullTotalPageFile;
1393 lpBuffer->dwAvailPageFile = (memstatus.ullAvailPageFile > MAXDWORD) ? memstatus.ullAvailPageFile :
1394 (memstatus.ullAvailPageFile > MAXLONG) ? MAXLONG : memstatus.ullAvailPageFile;
1395 lpBuffer->dwTotalVirtual = (memstatus.ullTotalVirtual > MAXDWORD) ? memstatus.ullTotalVirtual :
1396 (memstatus.ullTotalVirtual > MAXLONG) ? MAXLONG : memstatus.ullTotalVirtual;
1397 lpBuffer->dwAvailVirtual = (memstatus.ullAvailVirtual > MAXDWORD) ? memstatus.ullAvailVirtual :
1398 (memstatus.ullAvailVirtual > MAXLONG) ? MAXLONG : memstatus.ullAvailVirtual;
1401 /* work around for broken photoshop 4 installer */
1402 if ( lpBuffer->dwAvailPhys + lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
1403 lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 - lpBuffer->dwAvailPhys - 1;