gdi32: Add a helper function to initialize Bresenham parameters for line drawing.
[wine/multimedia.git] / dlls / kernel32 / heap.c
blobb74763f218136c96740585fc323dbb12adeb5455
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 RtlLockHeap(GetProcessHeap());
375 pintern = HeapAlloc(GetProcessHeap(), 0, sizeof(GLOBAL32_INTERN));
376 if (pintern)
378 /* Mask out obsolete flags */
379 flags &= ~(GMEM_LOWER | GMEM_NOCOMPACT | GMEM_NOT_BANKED | GMEM_NOTIFY);
381 pintern->Magic = MAGIC_GLOBAL_USED;
382 pintern->Flags = flags >> 8;
383 pintern->LockCount = 0;
385 if (size)
387 palloc = HeapAlloc(GetProcessHeap(), hpflags, size+HGLOBAL_STORAGE);
388 if (!palloc)
390 HeapFree(GetProcessHeap(), 0, pintern);
391 pintern = NULL;
393 else
395 *(HGLOBAL *)palloc = INTERN_TO_HANDLE(pintern);
396 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
399 else
400 pintern->Pointer = NULL;
403 RtlUnlockHeap(GetProcessHeap());
404 if (!pintern) return 0;
405 TRACE( "(flags=%04x) returning handle %p pointer %p\n",
406 flags, INTERN_TO_HANDLE(pintern), pintern->Pointer );
407 return INTERN_TO_HANDLE(pintern);
412 /***********************************************************************
413 * GlobalLock (KERNEL32.@)
415 * Lock a global memory object and return a pointer to first byte of the memory
417 * PARAMS
418 * hmem [I] Handle of the global memory object
420 * RETURNS
421 * Success: Pointer to first byte of the memory block
422 * Failure: NULL
424 * NOTES
425 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
428 LPVOID WINAPI GlobalLock(HGLOBAL hmem)
430 PGLOBAL32_INTERN pintern;
431 LPVOID palloc;
433 if (ISPOINTER(hmem))
434 return IsBadReadPtr(hmem, 1) ? NULL : hmem;
436 RtlLockHeap(GetProcessHeap());
437 __TRY
439 pintern = HANDLE_TO_INTERN(hmem);
440 if (pintern->Magic == MAGIC_GLOBAL_USED)
442 palloc = pintern->Pointer;
443 if (!pintern->Pointer)
444 SetLastError(ERROR_DISCARDED);
445 else if (pintern->LockCount < GMEM_LOCKCOUNT)
446 pintern->LockCount++;
448 else
450 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
451 palloc = NULL;
452 SetLastError(ERROR_INVALID_HANDLE);
455 __EXCEPT_PAGE_FAULT
457 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
458 palloc = NULL;
459 SetLastError(ERROR_INVALID_HANDLE);
461 __ENDTRY
462 RtlUnlockHeap(GetProcessHeap());
463 return palloc;
467 /***********************************************************************
468 * GlobalUnlock (KERNEL32.@)
470 * Unlock a global memory object.
472 * PARAMS
473 * hmem [I] Handle of the global memory object
475 * RETURNS
476 * Success: Object is still locked
477 * Failure: FALSE (The Object is unlocked)
479 * NOTES
480 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
483 BOOL WINAPI GlobalUnlock(HGLOBAL hmem)
485 PGLOBAL32_INTERN pintern;
486 BOOL locked;
488 if (ISPOINTER(hmem)) return TRUE;
490 RtlLockHeap(GetProcessHeap());
491 __TRY
493 pintern=HANDLE_TO_INTERN(hmem);
494 if(pintern->Magic==MAGIC_GLOBAL_USED)
496 if(pintern->LockCount)
498 pintern->LockCount--;
499 locked = (pintern->LockCount != 0);
500 if (!locked) SetLastError(NO_ERROR);
502 else
504 WARN("%p not locked\n", hmem);
505 SetLastError(ERROR_NOT_LOCKED);
506 locked = FALSE;
509 else
511 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
512 SetLastError(ERROR_INVALID_HANDLE);
513 locked=FALSE;
516 __EXCEPT_PAGE_FAULT
518 WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
519 SetLastError( ERROR_INVALID_PARAMETER );
520 locked=FALSE;
522 __ENDTRY
523 RtlUnlockHeap(GetProcessHeap());
524 return locked;
528 /***********************************************************************
529 * GlobalHandle (KERNEL32.@)
531 * Get the handle associated with the pointer to a global memory block.
533 * RETURNS
534 * Handle: Success
535 * NULL: Failure
537 HGLOBAL WINAPI GlobalHandle(
538 LPCVOID pmem /* [in] Pointer to global memory block */
540 HGLOBAL handle;
541 PGLOBAL32_INTERN maybe_intern;
542 LPCVOID test;
544 if (!pmem)
546 SetLastError( ERROR_INVALID_PARAMETER );
547 return 0;
550 RtlLockHeap(GetProcessHeap());
551 __TRY
553 handle = 0;
555 /* note that if pmem is a pointer to a block allocated by */
556 /* GlobalAlloc with GMEM_MOVEABLE then magic test in HeapValidate */
557 /* will fail. */
558 if (ISPOINTER(pmem)) {
559 if (HeapValidate( GetProcessHeap(), 0, pmem )) {
560 handle = (HGLOBAL)pmem; /* valid fixed block */
561 break;
563 handle = POINTER_TO_HANDLE(pmem);
564 } else
565 handle = (HGLOBAL)pmem;
567 /* Now test handle either passed in or retrieved from pointer */
568 maybe_intern = HANDLE_TO_INTERN( handle );
569 if (maybe_intern->Magic == MAGIC_GLOBAL_USED) {
570 test = maybe_intern->Pointer;
571 if (HeapValidate( GetProcessHeap(), 0, (const char *)test - HGLOBAL_STORAGE ) && /* obj(-handle) valid arena? */
572 HeapValidate( GetProcessHeap(), 0, maybe_intern )) /* intern valid arena? */
573 break; /* valid moveable block */
575 handle = 0;
576 SetLastError( ERROR_INVALID_HANDLE );
578 __EXCEPT_PAGE_FAULT
580 SetLastError( ERROR_INVALID_HANDLE );
581 handle = 0;
583 __ENDTRY
584 RtlUnlockHeap(GetProcessHeap());
586 return handle;
590 /***********************************************************************
591 * GlobalReAlloc (KERNEL32.@)
593 * Change the size or attributes of a global memory object.
595 * RETURNS
596 * Handle: Success
597 * NULL: Failure
599 HGLOBAL WINAPI GlobalReAlloc(
600 HGLOBAL hmem, /* [in] Handle of global memory object */
601 SIZE_T size, /* [in] New size of block */
602 UINT flags /* [in] How to reallocate object */
604 LPVOID palloc;
605 HGLOBAL hnew;
606 PGLOBAL32_INTERN pintern;
607 DWORD heap_flags = (flags & GMEM_ZEROINIT) ? HEAP_ZERO_MEMORY : 0;
609 hnew = 0;
610 RtlLockHeap(GetProcessHeap());
611 if(flags & GMEM_MODIFY) /* modify flags */
613 if( ISPOINTER(hmem) && (flags & GMEM_MOVEABLE))
615 /* make a fixed block moveable
616 * actually only NT is able to do this. But it's soo simple
618 if (hmem == 0)
620 WARN("GlobalReAlloc with null handle!\n");
621 SetLastError( ERROR_NOACCESS );
622 hnew = 0;
624 else
626 size = HeapSize(GetProcessHeap(), 0, hmem);
627 hnew = GlobalAlloc(flags, size);
628 palloc = GlobalLock(hnew);
629 memcpy(palloc, hmem, size);
630 GlobalUnlock(hnew);
631 GlobalFree(hmem);
634 else if( ISPOINTER(hmem) &&(flags & GMEM_DISCARDABLE))
636 /* change the flags to make our block "discardable" */
637 pintern=HANDLE_TO_INTERN(hmem);
638 pintern->Flags = pintern->Flags | (GMEM_DISCARDABLE >> 8);
639 hnew=hmem;
641 else
643 SetLastError(ERROR_INVALID_PARAMETER);
644 hnew = 0;
647 else
649 if(ISPOINTER(hmem))
651 /* reallocate fixed memory */
652 hnew=HeapReAlloc(GetProcessHeap(), heap_flags, hmem, size);
654 else
656 /* reallocate a moveable block */
657 pintern=HANDLE_TO_INTERN(hmem);
659 #if 0
660 /* Apparently Windows doesn't care whether the handle is locked at this point */
661 /* See also the same comment in GlobalFree() */
662 if(pintern->LockCount>1) {
663 ERR("handle 0x%08lx is still locked, cannot realloc!\n",(DWORD)hmem);
664 SetLastError(ERROR_INVALID_HANDLE);
665 } else
666 #endif
667 if(size!=0)
669 hnew=hmem;
670 if(pintern->Pointer)
672 if(size > INT_MAX-HGLOBAL_STORAGE)
674 SetLastError(ERROR_OUTOFMEMORY);
675 hnew = 0;
677 else if((palloc = HeapReAlloc(GetProcessHeap(), heap_flags,
678 (char *) pintern->Pointer-HGLOBAL_STORAGE,
679 size+HGLOBAL_STORAGE)) == NULL)
680 hnew = 0; /* Block still valid */
681 else
682 pintern->Pointer = (char *)palloc+HGLOBAL_STORAGE;
684 else
686 if(size > INT_MAX-HGLOBAL_STORAGE)
688 SetLastError(ERROR_OUTOFMEMORY);
689 hnew = 0;
691 else if((palloc=HeapAlloc(GetProcessHeap(), heap_flags, size+HGLOBAL_STORAGE))
692 == NULL)
693 hnew = 0;
694 else
696 *(HGLOBAL *)palloc = hmem;
697 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
701 else
703 if (pintern->LockCount == 0)
705 if(pintern->Pointer)
707 HeapFree(GetProcessHeap(), 0, (char *) pintern->Pointer-HGLOBAL_STORAGE);
708 pintern->Pointer = NULL;
710 hnew = hmem;
712 else
713 WARN("not freeing memory associated with locked handle\n");
717 RtlUnlockHeap(GetProcessHeap());
718 return hnew;
722 /***********************************************************************
723 * GlobalFree (KERNEL32.@)
725 * Free a global memory object.
727 * PARAMS
728 * hmem [I] Handle of the global memory object
730 * RETURNS
731 * Success: NULL
732 * Failure: The provided handle
734 * NOTES
735 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
738 HGLOBAL WINAPI GlobalFree(HGLOBAL hmem)
740 PGLOBAL32_INTERN pintern;
741 HGLOBAL hreturned;
743 RtlLockHeap(GetProcessHeap());
744 __TRY
746 hreturned = 0;
747 if(ISPOINTER(hmem)) /* POINTER */
749 if(!HeapFree(GetProcessHeap(), 0, hmem))
751 SetLastError(ERROR_INVALID_HANDLE);
752 hreturned = hmem;
755 else /* HANDLE */
757 pintern=HANDLE_TO_INTERN(hmem);
759 if(pintern->Magic==MAGIC_GLOBAL_USED)
761 pintern->Magic = 0xdead;
763 /* WIN98 does not make this test. That is you can free a */
764 /* block you have not unlocked. Go figure!! */
765 /* if(pintern->LockCount!=0) */
766 /* SetLastError(ERROR_INVALID_HANDLE); */
768 if(pintern->Pointer)
769 if(!HeapFree(GetProcessHeap(), 0, (char *)(pintern->Pointer)-HGLOBAL_STORAGE))
770 hreturned=hmem;
771 if(!HeapFree(GetProcessHeap(), 0, pintern))
772 hreturned=hmem;
774 else
776 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
777 SetLastError(ERROR_INVALID_HANDLE);
778 hreturned = hmem;
782 __EXCEPT_PAGE_FAULT
784 ERR("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
785 SetLastError( ERROR_INVALID_PARAMETER );
786 hreturned = hmem;
788 __ENDTRY
789 RtlUnlockHeap(GetProcessHeap());
790 return hreturned;
794 /***********************************************************************
795 * GlobalSize (KERNEL32.@)
797 * Get the size of a global memory object.
799 * PARAMS
800 * hmem [I] Handle of the global memory object
802 * RETURNS
803 * Failure: 0
804 * Success: Size in Bytes of the global memory object
806 * NOTES
807 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
810 SIZE_T WINAPI GlobalSize(HGLOBAL hmem)
812 SIZE_T retval;
813 PGLOBAL32_INTERN pintern;
815 if (!((ULONG_PTR)hmem >> 16))
817 SetLastError(ERROR_INVALID_HANDLE);
818 return 0;
821 if(ISPOINTER(hmem))
823 retval=HeapSize(GetProcessHeap(), 0, hmem);
825 if (retval == ~0ul) /* It might be a GMEM_MOVEABLE data pointer */
827 retval = HeapSize(GetProcessHeap(), 0, (char*)hmem - HGLOBAL_STORAGE);
828 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
831 else
833 RtlLockHeap(GetProcessHeap());
834 pintern=HANDLE_TO_INTERN(hmem);
836 if(pintern->Magic==MAGIC_GLOBAL_USED)
838 if (!pintern->Pointer) /* handle case of GlobalAlloc( ??,0) */
839 retval = 0;
840 else
842 retval = HeapSize(GetProcessHeap(), 0, (char *)pintern->Pointer - HGLOBAL_STORAGE );
843 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
846 else
848 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
849 SetLastError(ERROR_INVALID_HANDLE);
850 retval=0;
852 RtlUnlockHeap(GetProcessHeap());
854 if (retval == ~0ul) retval = 0;
855 return retval;
859 /***********************************************************************
860 * GlobalWire (KERNEL32.@)
862 LPVOID WINAPI GlobalWire(HGLOBAL hmem)
864 return GlobalLock( hmem );
868 /***********************************************************************
869 * GlobalUnWire (KERNEL32.@)
871 BOOL WINAPI GlobalUnWire(HGLOBAL hmem)
873 return GlobalUnlock( hmem);
877 /***********************************************************************
878 * GlobalFix (KERNEL32.@)
880 VOID WINAPI GlobalFix(HGLOBAL hmem)
882 GlobalLock( hmem );
886 /***********************************************************************
887 * GlobalUnfix (KERNEL32.@)
889 VOID WINAPI GlobalUnfix(HGLOBAL hmem)
891 GlobalUnlock( hmem);
895 /***********************************************************************
896 * GlobalFlags (KERNEL32.@)
898 * Get information about a global memory object.
900 * PARAMS
901 * hmem [I] Handle of the global memory object
903 * RETURNS
904 * Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid
905 * Success: Value specifying allocation flags and lock count
908 UINT WINAPI GlobalFlags(HGLOBAL hmem)
910 DWORD retval;
911 PGLOBAL32_INTERN pintern;
913 if(ISPOINTER(hmem))
915 retval=0;
917 else
919 RtlLockHeap(GetProcessHeap());
920 pintern=HANDLE_TO_INTERN(hmem);
921 if(pintern->Magic==MAGIC_GLOBAL_USED)
923 retval=pintern->LockCount + (pintern->Flags<<8);
924 if(pintern->Pointer==0)
925 retval|= GMEM_DISCARDED;
927 else
929 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
930 SetLastError(ERROR_INVALID_HANDLE);
931 retval = GMEM_INVALID_HANDLE;
933 RtlUnlockHeap(GetProcessHeap());
935 return retval;
939 /***********************************************************************
940 * GlobalCompact (KERNEL32.@)
942 SIZE_T WINAPI GlobalCompact( DWORD minfree )
944 return 0; /* GlobalCompact does nothing in Win32 */
948 /***********************************************************************
949 * LocalAlloc (KERNEL32.@)
951 * Allocate a local memory object.
953 * RETURNS
954 * Handle: Success
955 * NULL: Failure
957 * NOTES
958 * Windows memory management does not provide a separate local heap
959 * and global heap.
961 HLOCAL WINAPI LocalAlloc(
962 UINT flags, /* [in] Allocation attributes */
963 SIZE_T size /* [in] Number of bytes to allocate */
965 return GlobalAlloc( flags, size );
969 /***********************************************************************
970 * LocalCompact (KERNEL32.@)
972 SIZE_T WINAPI LocalCompact( UINT minfree )
974 return 0; /* LocalCompact does nothing in Win32 */
978 /***********************************************************************
979 * LocalFlags (KERNEL32.@)
981 * Get information about a local memory object.
983 * RETURNS
984 * Value specifying allocation flags and lock count.
985 * LMEM_INVALID_HANDLE: Failure
987 * NOTES
988 * Windows memory management does not provide a separate local heap
989 * and global heap.
991 UINT WINAPI LocalFlags(
992 HLOCAL handle /* [in] Handle of memory object */
994 return GlobalFlags( handle );
998 /***********************************************************************
999 * LocalFree (KERNEL32.@)
1001 * Free a local memory object.
1003 * RETURNS
1004 * NULL: Success
1005 * Handle: Failure
1007 * NOTES
1008 * Windows memory management does not provide a separate local heap
1009 * and global heap.
1011 HLOCAL WINAPI LocalFree(
1012 HLOCAL handle /* [in] Handle of memory object */
1014 return GlobalFree( handle );
1018 /***********************************************************************
1019 * LocalHandle (KERNEL32.@)
1021 * Get the handle associated with the pointer to a local memory block.
1023 * RETURNS
1024 * Handle: Success
1025 * NULL: Failure
1027 * NOTES
1028 * Windows memory management does not provide a separate local heap
1029 * and global heap.
1031 HLOCAL WINAPI LocalHandle(
1032 LPCVOID ptr /* [in] Address of local memory block */
1034 return GlobalHandle( ptr );
1038 /***********************************************************************
1039 * LocalLock (KERNEL32.@)
1040 * Locks a local memory object and returns pointer to the first byte
1041 * of the memory block.
1043 * RETURNS
1044 * Pointer: Success
1045 * NULL: Failure
1047 * NOTES
1048 * Windows memory management does not provide a separate local heap
1049 * and global heap.
1051 LPVOID WINAPI LocalLock(
1052 HLOCAL handle /* [in] Address of local memory object */
1054 return GlobalLock( handle );
1058 /***********************************************************************
1059 * LocalReAlloc (KERNEL32.@)
1061 * Change the size or attributes of a local memory object.
1063 * RETURNS
1064 * Handle: Success
1065 * NULL: Failure
1067 * NOTES
1068 * Windows memory management does not provide a separate local heap
1069 * and global heap.
1071 HLOCAL WINAPI LocalReAlloc(
1072 HLOCAL handle, /* [in] Handle of memory object */
1073 SIZE_T size, /* [in] New size of block */
1074 UINT flags /* [in] How to reallocate object */
1076 return GlobalReAlloc( handle, size, flags );
1080 /***********************************************************************
1081 * LocalShrink (KERNEL32.@)
1083 SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
1085 return 0; /* LocalShrink does nothing in Win32 */
1089 /***********************************************************************
1090 * LocalSize (KERNEL32.@)
1092 * Get the size of a local memory object.
1094 * RETURNS
1095 * Size: Success
1096 * 0: Failure
1098 * NOTES
1099 * Windows memory management does not provide a separate local heap
1100 * and global heap.
1102 SIZE_T WINAPI LocalSize(
1103 HLOCAL handle /* [in] Handle of memory object */
1105 return GlobalSize( handle );
1109 /***********************************************************************
1110 * LocalUnlock (KERNEL32.@)
1112 * Unlock a local memory object.
1114 * RETURNS
1115 * TRUE: Object is still locked
1116 * FALSE: Object is unlocked
1118 * NOTES
1119 * Windows memory management does not provide a separate local heap
1120 * and global heap.
1122 BOOL WINAPI LocalUnlock(
1123 HLOCAL handle /* [in] Handle of memory object */
1126 if (ISPOINTER( handle ))
1128 SetLastError( ERROR_NOT_LOCKED );
1129 return FALSE;
1132 return GlobalUnlock( handle );
1136 /***********************************************************************
1137 * GlobalMemoryStatusEx (KERNEL32.@)
1138 * A version of GlobalMemoryStatus that can deal with memory over 4GB
1140 * RETURNS
1141 * TRUE
1143 BOOL WINAPI GlobalMemoryStatusEx( LPMEMORYSTATUSEX lpmemex )
1145 static MEMORYSTATUSEX cached_memstatus;
1146 static int cache_lastchecked = 0;
1147 SYSTEM_INFO si;
1148 #ifdef linux
1149 FILE *f;
1150 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
1151 unsigned long val;
1152 int mib[2];
1153 size_t size_sys;
1154 #elif defined(__APPLE__)
1155 unsigned int val;
1156 int mib[2];
1157 size_t size_sys;
1158 #elif defined(sun)
1159 unsigned long pagesize,maxpages,freepages,swapspace,swapfree;
1160 struct anoninfo swapinf;
1161 int rval;
1162 #endif
1164 if (lpmemex->dwLength != sizeof(*lpmemex))
1166 SetLastError( ERROR_INVALID_PARAMETER );
1167 return FALSE;
1170 if (time(NULL)==cache_lastchecked) {
1171 *lpmemex = cached_memstatus;
1172 return TRUE;
1174 cache_lastchecked = time(NULL);
1176 lpmemex->dwMemoryLoad = 0;
1177 lpmemex->ullTotalPhys = 16*1024*1024;
1178 lpmemex->ullAvailPhys = 16*1024*1024;
1179 lpmemex->ullTotalPageFile = 16*1024*1024;
1180 lpmemex->ullAvailPageFile = 16*1024*1024;
1182 #ifdef linux
1183 f = fopen( "/proc/meminfo", "r" );
1184 if (f)
1186 char buffer[256];
1187 unsigned long total, used, free, shared, buffers, cached;
1189 lpmemex->ullTotalPhys = lpmemex->ullAvailPhys = 0;
1190 lpmemex->ullTotalPageFile = lpmemex->ullAvailPageFile = 0;
1191 while (fgets( buffer, sizeof(buffer), f ))
1193 /* old style /proc/meminfo ... */
1194 if (sscanf( buffer, "Mem: %lu %lu %lu %lu %lu %lu",
1195 &total, &used, &free, &shared, &buffers, &cached ))
1197 lpmemex->ullTotalPhys += total;
1198 lpmemex->ullAvailPhys += free + buffers + cached;
1200 if (sscanf( buffer, "Swap: %lu %lu %lu", &total, &used, &free ))
1202 lpmemex->ullTotalPageFile += total;
1203 lpmemex->ullAvailPageFile += free;
1206 /* new style /proc/meminfo ... */
1207 if (sscanf(buffer, "MemTotal: %lu", &total))
1208 lpmemex->ullTotalPhys = (ULONG64)total*1024;
1209 if (sscanf(buffer, "MemFree: %lu", &free))
1210 lpmemex->ullAvailPhys = (ULONG64)free*1024;
1211 if (sscanf(buffer, "SwapTotal: %lu", &total))
1212 lpmemex->ullTotalPageFile = (ULONG64)total*1024;
1213 if (sscanf(buffer, "SwapFree: %lu", &free))
1214 lpmemex->ullAvailPageFile = (ULONG64)free*1024;
1215 if (sscanf(buffer, "Buffers: %lu", &buffers))
1216 lpmemex->ullAvailPhys += (ULONG64)buffers*1024;
1217 if (sscanf(buffer, "Cached: %lu", &cached))
1218 lpmemex->ullAvailPhys += (ULONG64)cached*1024;
1220 fclose( f );
1222 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1223 mib[0] = CTL_HW;
1224 mib[1] = HW_PHYSMEM;
1225 size_sys = sizeof(val);
1226 sysctl(mib, 2, &val, &size_sys, NULL, 0);
1227 if (val) lpmemex->ullTotalPhys = val;
1228 mib[1] = HW_USERMEM;
1229 size_sys = sizeof(val);
1230 sysctl(mib, 2, &val, &size_sys, NULL, 0);
1231 if (!val) val = lpmemex->ullTotalPhys;
1232 lpmemex->ullAvailPhys = val;
1233 lpmemex->ullTotalPageFile = val;
1234 lpmemex->ullAvailPageFile = val;
1235 #elif defined ( sun )
1236 pagesize=sysconf(_SC_PAGESIZE);
1237 maxpages=sysconf(_SC_PHYS_PAGES);
1238 freepages=sysconf(_SC_AVPHYS_PAGES);
1239 rval=swapctl(SC_AINFO, &swapinf);
1240 if(rval >-1)
1242 swapspace=swapinf.ani_max*pagesize;
1243 swapfree=swapinf.ani_free*pagesize;
1244 }else
1247 WARN("Swap size cannot be determined , assuming equal to physical memory\n");
1248 swapspace=maxpages*pagesize;
1249 swapfree=maxpages*pagesize;
1251 lpmemex->ullTotalPhys=pagesize*maxpages;
1252 lpmemex->ullAvailPhys = pagesize*freepages;
1253 lpmemex->ullTotalPageFile = swapspace;
1254 lpmemex->ullAvailPageFile = swapfree;
1255 #endif
1257 if (lpmemex->ullTotalPhys)
1259 lpmemex->dwMemoryLoad = (lpmemex->ullTotalPhys-lpmemex->ullAvailPhys)
1260 / (lpmemex->ullTotalPhys / 100);
1263 /* Win98 returns only the swapsize in ullTotalPageFile/ullAvailPageFile,
1264 WinXP returns the size of physical memory + swapsize;
1265 mimic the behavior of XP.
1266 Note: Project2k refuses to start if it sees less than 1Mb of free swap.
1268 lpmemex->ullTotalPageFile += lpmemex->ullTotalPhys;
1269 lpmemex->ullAvailPageFile += lpmemex->ullAvailPhys;
1271 /* Titan Quest refuses to run if TotalPageFile <= ullTotalPhys */
1272 if(lpmemex->ullTotalPageFile == lpmemex->ullTotalPhys)
1274 lpmemex->ullTotalPhys -= 1;
1275 lpmemex->ullAvailPhys -= 1;
1278 /* FIXME: should do something for other systems */
1279 GetSystemInfo(&si);
1280 lpmemex->ullTotalVirtual = (ULONG_PTR)si.lpMaximumApplicationAddress-(ULONG_PTR)si.lpMinimumApplicationAddress;
1281 /* FIXME: we should track down all the already allocated VM pages and subtract them, for now arbitrarily remove 64KB so that it matches NT */
1282 lpmemex->ullAvailVirtual = lpmemex->ullTotalVirtual-64*1024;
1284 /* MSDN says about AvailExtendedVirtual: Size of unreserved and uncommitted
1285 memory in the extended portion of the virtual address space of the calling
1286 process, in bytes.
1287 However, I don't know what this means, so set it to zero :(
1289 lpmemex->ullAvailExtendedVirtual = 0;
1291 cached_memstatus = *lpmemex;
1293 TRACE_(globalmem)("<-- LPMEMORYSTATUSEX: dwLength %d, dwMemoryLoad %d, ullTotalPhys %s, ullAvailPhys %s,"
1294 " ullTotalPageFile %s, ullAvailPageFile %s, ullTotalVirtual %s, ullAvailVirtual %s\n",
1295 lpmemex->dwLength, lpmemex->dwMemoryLoad, wine_dbgstr_longlong(lpmemex->ullTotalPhys),
1296 wine_dbgstr_longlong(lpmemex->ullAvailPhys), wine_dbgstr_longlong(lpmemex->ullTotalPageFile),
1297 wine_dbgstr_longlong(lpmemex->ullAvailPageFile), wine_dbgstr_longlong(lpmemex->ullTotalVirtual),
1298 wine_dbgstr_longlong(lpmemex->ullAvailVirtual) );
1300 return TRUE;
1303 /***********************************************************************
1304 * GlobalMemoryStatus (KERNEL32.@)
1305 * Provides information about the status of the memory, so apps can tell
1306 * roughly how much they are able to allocate
1308 * RETURNS
1309 * None
1311 VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
1313 MEMORYSTATUSEX memstatus;
1314 OSVERSIONINFOW osver;
1315 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( GetModuleHandleW(0) );
1317 /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
1318 for one extra field in the struct, and the lack of a bug, we simply
1319 call GlobalMemoryStatusEx and copy the values across. */
1320 memstatus.dwLength = sizeof(memstatus);
1321 GlobalMemoryStatusEx(&memstatus);
1323 lpBuffer->dwLength = sizeof(*lpBuffer);
1324 lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;
1326 /* Windows 2000 and later report -1 when values are greater than 4 Gb.
1327 * NT reports values modulo 4 Gb.
1330 osver.dwOSVersionInfoSize = sizeof(osver);
1331 GetVersionExW(&osver);
1333 if ( osver.dwMajorVersion >= 5 || osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
1335 lpBuffer->dwTotalPhys = min( memstatus.ullTotalPhys, MAXDWORD );
1336 lpBuffer->dwAvailPhys = min( memstatus.ullAvailPhys, MAXDWORD );
1337 /* Limit value for apps that do not expect so much memory. Remove last 512 kb to make Sacrifice demo happy. */
1338 lpBuffer->dwTotalPageFile = min( memstatus.ullTotalPageFile, 0xfff7ffff );
1339 lpBuffer->dwAvailPageFile = min( memstatus.ullAvailPageFile, MAXDWORD );
1340 lpBuffer->dwTotalVirtual = min( memstatus.ullTotalVirtual, MAXDWORD );
1341 lpBuffer->dwAvailVirtual = min( memstatus.ullAvailVirtual, MAXDWORD );
1344 else /* duplicate NT bug */
1346 lpBuffer->dwTotalPhys = memstatus.ullTotalPhys;
1347 lpBuffer->dwAvailPhys = memstatus.ullAvailPhys;
1348 lpBuffer->dwTotalPageFile = memstatus.ullTotalPageFile;
1349 lpBuffer->dwAvailPageFile = memstatus.ullAvailPageFile;
1350 lpBuffer->dwTotalVirtual = memstatus.ullTotalVirtual;
1351 lpBuffer->dwAvailVirtual = memstatus.ullAvailVirtual;
1354 /* values are limited to 2Gb unless the app has the IMAGE_FILE_LARGE_ADDRESS_AWARE flag */
1355 /* page file sizes are not limited (Adobe Illustrator 8 depends on this) */
1356 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE))
1358 if (lpBuffer->dwTotalPhys > MAXLONG) lpBuffer->dwTotalPhys = MAXLONG;
1359 if (lpBuffer->dwAvailPhys > MAXLONG) lpBuffer->dwAvailPhys = MAXLONG;
1360 if (lpBuffer->dwTotalVirtual > MAXLONG) lpBuffer->dwTotalVirtual = MAXLONG;
1361 if (lpBuffer->dwAvailVirtual > MAXLONG) lpBuffer->dwAvailVirtual = MAXLONG;
1364 /* work around for broken photoshop 4 installer */
1365 if ( lpBuffer->dwAvailPhys + lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
1366 lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 - lpBuffer->dwAvailPhys - 1;
1368 /* limit page file size for really old binaries */
1369 if (nt->OptionalHeader.MajorSubsystemVersion < 4)
1371 if (lpBuffer->dwTotalPageFile > MAXLONG) lpBuffer->dwTotalPageFile = MAXLONG;
1372 if (lpBuffer->dwAvailPageFile > MAXLONG) lpBuffer->dwAvailPageFile = MAXLONG;
1375 TRACE_(globalmem)("Length %u, MemoryLoad %u, TotalPhys %lx, AvailPhys %lx,"
1376 " TotalPageFile %lx, AvailPageFile %lx, TotalVirtual %lx, AvailVirtual %lx\n",
1377 lpBuffer->dwLength, lpBuffer->dwMemoryLoad, lpBuffer->dwTotalPhys,
1378 lpBuffer->dwAvailPhys, lpBuffer->dwTotalPageFile, lpBuffer->dwAvailPageFile,
1379 lpBuffer->dwTotalVirtual, lpBuffer->dwAvailVirtual );