wined3d: Ignore set_priority calls on non-managed resources.
[wine.git] / dlls / kernel32 / heap.c
blobdb1b4017c9b61c40ea99a1e21d724736aa632d65
1 /*
2 * Win32 heap functions
4 * Copyright 1995, 1996 Alexandre Julliard
5 * Copyright 1996 Huw Davies
6 * Copyright 1998 Ulrich Weigand
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <limits.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <time.h>
34 #ifdef HAVE_SYS_PARAM_H
35 #include <sys/param.h>
36 #endif
37 #ifdef HAVE_SYS_SYSCTL_H
38 #include <sys/sysctl.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43 #ifdef HAVE_MACH_MACH_H
44 #include <mach/mach.h>
45 #endif
47 #ifdef sun
48 /* FIXME: Unfortunately swapctl can't be used with largefile.... */
49 # undef _FILE_OFFSET_BITS
50 # define _FILE_OFFSET_BITS 32
51 # ifdef HAVE_SYS_RESOURCE_H
52 # include <sys/resource.h>
53 # endif
54 # ifdef HAVE_SYS_STAT_H
55 # include <sys/stat.h>
56 # endif
57 # include <sys/swap.h>
58 #endif
61 #include "windef.h"
62 #include "winbase.h"
63 #include "winerror.h"
64 #include "winnt.h"
65 #include "winternl.h"
66 #include "wine/exception.h"
67 #include "wine/debug.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(heap);
70 WINE_DECLARE_DEBUG_CHANNEL(globalmem);
72 /* address where we try to map the system heap */
73 #define SYSTEM_HEAP_BASE ((void*)0x80000000)
74 #define SYSTEM_HEAP_SIZE 0x1000000 /* Default heap size = 16Mb */
76 static HANDLE systemHeap; /* globally shared heap */
79 /***********************************************************************
80 * HEAP_CreateSystemHeap
82 * Create the system heap.
84 static inline HANDLE HEAP_CreateSystemHeap(void)
86 int created;
87 void *base;
88 HANDLE map, event;
90 /* create the system heap event first */
91 event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );
93 if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
94 0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
95 created = (GetLastError() != ERROR_ALREADY_EXISTS);
97 if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
99 /* pre-defined address not available */
100 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
101 return 0;
104 if (created) /* newly created heap */
106 systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
107 SYSTEM_HEAP_SIZE, NULL, NULL );
108 SetEvent( event );
110 else
112 /* wait for the heap to be initialized */
113 WaitForSingleObject( event, INFINITE );
114 systemHeap = base;
116 CloseHandle( map );
117 return systemHeap;
121 /***********************************************************************
122 * HeapCreate (KERNEL32.@)
124 * Create a heap object.
126 * RETURNS
127 * Handle of heap: Success
128 * NULL: Failure
130 HANDLE WINAPI HeapCreate(
131 DWORD flags, /* [in] Heap allocation flag */
132 SIZE_T initialSize, /* [in] Initial heap size */
133 SIZE_T maxSize /* [in] Maximum heap size */
135 HANDLE ret;
137 if ( flags & HEAP_SHARED )
139 if (!systemHeap) HEAP_CreateSystemHeap();
140 else WARN( "Shared Heap requested, returning system heap.\n" );
141 ret = systemHeap;
143 else
145 ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
146 if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
148 return ret;
152 /***********************************************************************
153 * HeapDestroy (KERNEL32.@)
155 * Destroy a heap object.
157 * RETURNS
158 * TRUE: Success
159 * FALSE: Failure
161 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
163 if (heap == systemHeap)
165 WARN( "attempt to destroy system heap, returning TRUE!\n" );
166 return TRUE;
168 if (!RtlDestroyHeap( heap )) return TRUE;
169 SetLastError( ERROR_INVALID_HANDLE );
170 return FALSE;
174 /***********************************************************************
175 * HeapCompact (KERNEL32.@)
177 SIZE_T WINAPI HeapCompact( HANDLE heap, DWORD flags )
179 return RtlCompactHeap( heap, flags );
183 /***********************************************************************
184 * HeapValidate (KERNEL32.@)
185 * Validates a specified heap.
187 * NOTES
188 * Flags is ignored.
190 * RETURNS
191 * TRUE: Success
192 * FALSE: Failure
194 BOOL WINAPI HeapValidate(
195 HANDLE heap, /* [in] Handle to the heap */
196 DWORD flags, /* [in] Bit flags that control access during operation */
197 LPCVOID block /* [in] Optional pointer to memory block to validate */
199 return RtlValidateHeap( heap, flags, block );
203 /***********************************************************************
204 * HeapWalk (KERNEL32.@)
205 * Enumerates the memory blocks in a specified heap.
207 * TODO
208 * - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
209 * PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
211 * RETURNS
212 * TRUE: Success
213 * FALSE: Failure
215 BOOL WINAPI HeapWalk(
216 HANDLE heap, /* [in] Handle to heap to enumerate */
217 LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
219 NTSTATUS ret = RtlWalkHeap( heap, entry );
220 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
221 return !ret;
225 /***********************************************************************
226 * HeapLock (KERNEL32.@)
227 * Attempts to acquire the critical section object for a specified heap.
229 * RETURNS
230 * TRUE: Success
231 * FALSE: Failure
233 BOOL WINAPI HeapLock(
234 HANDLE heap /* [in] Handle of heap to lock for exclusive access */
236 return RtlLockHeap( heap );
240 /***********************************************************************
241 * HeapUnlock (KERNEL32.@)
242 * Releases ownership of the critical section object.
244 * RETURNS
245 * TRUE: Success
246 * FALSE: Failure
248 BOOL WINAPI HeapUnlock(
249 HANDLE heap /* [in] Handle to the heap to unlock */
251 return RtlUnlockHeap( heap );
255 /***********************************************************************
256 * GetProcessHeaps (KERNEL32.@)
258 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
260 return RtlGetProcessHeaps( count, heaps );
264 /* These are needed so that we can call the functions from inside kernel itself */
266 /***********************************************************************
267 * HeapAlloc (KERNEL32.@)
269 LPVOID WINAPI HeapAlloc( HANDLE heap, DWORD flags, SIZE_T size )
271 return RtlAllocateHeap( heap, flags, size );
274 BOOL WINAPI HeapFree( HANDLE heap, DWORD flags, LPVOID ptr )
276 return RtlFreeHeap( heap, flags, ptr );
279 LPVOID WINAPI HeapReAlloc( HANDLE heap, DWORD flags, LPVOID ptr, SIZE_T size )
281 return RtlReAllocateHeap( heap, flags, ptr, size );
284 SIZE_T WINAPI HeapSize( HANDLE heap, DWORD flags, LPCVOID ptr )
286 return RtlSizeHeap( heap, flags, ptr );
289 BOOL WINAPI HeapQueryInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
290 PVOID info, SIZE_T size_in, PSIZE_T size_out)
292 NTSTATUS ret = RtlQueryHeapInformation( heap, info_class, info, size_in, size_out );
293 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
294 return !ret;
297 BOOL WINAPI HeapSetInformation( HANDLE heap, HEAP_INFORMATION_CLASS infoclass, PVOID info, SIZE_T size)
299 FIXME("%p %d %p %ld\n", heap, infoclass, info, size );
300 return TRUE;
304 * Win32 Global heap functions (GlobalXXX).
305 * These functions included in Win32 for compatibility with 16 bit Windows
306 * Especially the moveable blocks and handles are oldish.
307 * But the ability to directly allocate memory with GPTR and LPTR is widely
308 * used.
310 * The handle stuff looks horrible, but it's implemented almost like Win95
311 * does it.
315 #define MAGIC_GLOBAL_USED 0x5342
316 #define HANDLE_TO_INTERN(h) ((PGLOBAL32_INTERN)(((char *)(h))-2))
317 #define INTERN_TO_HANDLE(i) (&((i)->Pointer))
318 #define POINTER_TO_HANDLE(p) (*(((const HGLOBAL *)(p))-2))
319 #define ISHANDLE(h) (((ULONG_PTR)(h)&2)!=0)
320 #define ISPOINTER(h) (((ULONG_PTR)(h)&2)==0)
321 /* align the storage needed for the HGLOBAL on an 8byte boundary thus
322 * GlobalAlloc/GlobalReAlloc'ing with GMEM_MOVEABLE of memory with
323 * size = 8*k, where k=1,2,3,... alloc's exactly the given size.
324 * The Minolta DiMAGE Image Viewer heavily relies on this, corrupting
325 * the output jpeg's > 1 MB if not */
326 #define HGLOBAL_STORAGE (sizeof(HGLOBAL)*2)
328 #include "pshpack1.h"
330 typedef struct __GLOBAL32_INTERN
332 WORD Magic;
333 LPVOID Pointer;
334 BYTE Flags;
335 BYTE LockCount;
336 } GLOBAL32_INTERN, *PGLOBAL32_INTERN;
338 #include "poppack.h"
340 /***********************************************************************
341 * GlobalAlloc (KERNEL32.@)
343 * Allocate a global memory object.
345 * RETURNS
346 * Handle: Success
347 * NULL: Failure
349 HGLOBAL WINAPI GlobalAlloc(
350 UINT flags, /* [in] Object allocation attributes */
351 SIZE_T size /* [in] Number of bytes to allocate */
353 PGLOBAL32_INTERN pintern;
354 DWORD hpflags;
355 LPVOID palloc;
357 if(flags&GMEM_ZEROINIT)
358 hpflags=HEAP_ZERO_MEMORY;
359 else
360 hpflags=0;
362 if((flags & GMEM_MOVEABLE)==0) /* POINTER */
364 palloc=HeapAlloc(GetProcessHeap(), hpflags, size);
365 TRACE( "(flags=%04x) returning %p\n", flags, palloc );
366 return palloc;
368 else /* HANDLE */
370 if (size > INT_MAX-HGLOBAL_STORAGE)
372 SetLastError(ERROR_OUTOFMEMORY);
373 return 0;
376 pintern = HeapAlloc(GetProcessHeap(), 0, sizeof(GLOBAL32_INTERN));
377 if (pintern)
379 /* Mask out obsolete flags */
380 flags &= ~(GMEM_LOWER | GMEM_NOCOMPACT | GMEM_NOT_BANKED | GMEM_NOTIFY);
382 pintern->Magic = MAGIC_GLOBAL_USED;
383 pintern->Flags = flags >> 8;
384 pintern->LockCount = 0;
386 if (size)
388 palloc = HeapAlloc(GetProcessHeap(), hpflags, size+HGLOBAL_STORAGE);
389 if (!palloc)
391 HeapFree(GetProcessHeap(), 0, pintern);
392 pintern = NULL;
394 else
396 *(HGLOBAL *)palloc = INTERN_TO_HANDLE(pintern);
397 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
400 else
401 pintern->Pointer = NULL;
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 if (!(flags & GMEM_MOVEABLE))
653 heap_flags |= HEAP_REALLOC_IN_PLACE_ONLY;
654 hnew=HeapReAlloc(GetProcessHeap(), heap_flags, hmem, size);
656 else
658 /* reallocate a moveable block */
659 pintern=HANDLE_TO_INTERN(hmem);
661 #if 0
662 /* Apparently Windows doesn't care whether the handle is locked at this point */
663 /* See also the same comment in GlobalFree() */
664 if(pintern->LockCount>1) {
665 ERR("handle 0x%08lx is still locked, cannot realloc!\n",(DWORD)hmem);
666 SetLastError(ERROR_INVALID_HANDLE);
667 } else
668 #endif
669 if(size!=0)
671 hnew=hmem;
672 if(pintern->Pointer)
674 if(size > INT_MAX-HGLOBAL_STORAGE)
676 SetLastError(ERROR_OUTOFMEMORY);
677 hnew = 0;
679 else if((palloc = HeapReAlloc(GetProcessHeap(), heap_flags,
680 (char *) pintern->Pointer-HGLOBAL_STORAGE,
681 size+HGLOBAL_STORAGE)) == NULL)
682 hnew = 0; /* Block still valid */
683 else
684 pintern->Pointer = (char *)palloc+HGLOBAL_STORAGE;
686 else
688 if(size > INT_MAX-HGLOBAL_STORAGE)
690 SetLastError(ERROR_OUTOFMEMORY);
691 hnew = 0;
693 else if((palloc=HeapAlloc(GetProcessHeap(), heap_flags, size+HGLOBAL_STORAGE))
694 == NULL)
695 hnew = 0;
696 else
698 *(HGLOBAL *)palloc = hmem;
699 pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
703 else
705 if (pintern->LockCount == 0)
707 if(pintern->Pointer)
709 HeapFree(GetProcessHeap(), 0, (char *) pintern->Pointer-HGLOBAL_STORAGE);
710 pintern->Pointer = NULL;
712 hnew = hmem;
714 else
715 WARN("not freeing memory associated with locked handle\n");
719 RtlUnlockHeap(GetProcessHeap());
720 return hnew;
724 /***********************************************************************
725 * GlobalFree (KERNEL32.@)
727 * Free a global memory object.
729 * PARAMS
730 * hmem [I] Handle of the global memory object
732 * RETURNS
733 * Success: NULL
734 * Failure: The provided handle
736 * NOTES
737 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
740 HGLOBAL WINAPI GlobalFree(HGLOBAL hmem)
742 PGLOBAL32_INTERN pintern;
743 HGLOBAL hreturned;
745 RtlLockHeap(GetProcessHeap());
746 __TRY
748 hreturned = 0;
749 if(ISPOINTER(hmem)) /* POINTER */
751 if(!HeapFree(GetProcessHeap(), 0, hmem))
753 SetLastError(ERROR_INVALID_HANDLE);
754 hreturned = hmem;
757 else /* HANDLE */
759 pintern=HANDLE_TO_INTERN(hmem);
761 if(pintern->Magic==MAGIC_GLOBAL_USED)
763 pintern->Magic = 0xdead;
765 /* WIN98 does not make this test. That is you can free a */
766 /* block you have not unlocked. Go figure!! */
767 /* if(pintern->LockCount!=0) */
768 /* SetLastError(ERROR_INVALID_HANDLE); */
770 if(pintern->Pointer)
771 if(!HeapFree(GetProcessHeap(), 0, (char *)(pintern->Pointer)-HGLOBAL_STORAGE))
772 hreturned=hmem;
773 if(!HeapFree(GetProcessHeap(), 0, pintern))
774 hreturned=hmem;
776 else
778 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
779 SetLastError(ERROR_INVALID_HANDLE);
780 hreturned = hmem;
784 __EXCEPT_PAGE_FAULT
786 ERR("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
787 SetLastError( ERROR_INVALID_PARAMETER );
788 hreturned = hmem;
790 __ENDTRY
791 RtlUnlockHeap(GetProcessHeap());
792 return hreturned;
796 /***********************************************************************
797 * GlobalSize (KERNEL32.@)
799 * Get the size of a global memory object.
801 * PARAMS
802 * hmem [I] Handle of the global memory object
804 * RETURNS
805 * Failure: 0
806 * Success: Size in Bytes of the global memory object
808 * NOTES
809 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
812 SIZE_T WINAPI GlobalSize(HGLOBAL hmem)
814 SIZE_T retval;
815 PGLOBAL32_INTERN pintern;
817 if (!((ULONG_PTR)hmem >> 16))
819 SetLastError(ERROR_INVALID_HANDLE);
820 return 0;
823 if(ISPOINTER(hmem))
825 retval=HeapSize(GetProcessHeap(), 0, hmem);
827 if (retval == ~0ul) /* It might be a GMEM_MOVEABLE data pointer */
829 retval = HeapSize(GetProcessHeap(), 0, (char*)hmem - HGLOBAL_STORAGE);
830 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
833 else
835 RtlLockHeap(GetProcessHeap());
836 pintern=HANDLE_TO_INTERN(hmem);
838 if(pintern->Magic==MAGIC_GLOBAL_USED)
840 if (!pintern->Pointer) /* handle case of GlobalAlloc( ??,0) */
841 retval = 0;
842 else
844 retval = HeapSize(GetProcessHeap(), 0, (char *)pintern->Pointer - HGLOBAL_STORAGE );
845 if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
848 else
850 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
851 SetLastError(ERROR_INVALID_HANDLE);
852 retval=0;
854 RtlUnlockHeap(GetProcessHeap());
856 if (retval == ~0ul) retval = 0;
857 return retval;
861 /***********************************************************************
862 * GlobalWire (KERNEL32.@)
864 LPVOID WINAPI GlobalWire(HGLOBAL hmem)
866 return GlobalLock( hmem );
870 /***********************************************************************
871 * GlobalUnWire (KERNEL32.@)
873 BOOL WINAPI GlobalUnWire(HGLOBAL hmem)
875 return GlobalUnlock( hmem);
879 /***********************************************************************
880 * GlobalFix (KERNEL32.@)
882 VOID WINAPI GlobalFix(HGLOBAL hmem)
884 GlobalLock( hmem );
888 /***********************************************************************
889 * GlobalUnfix (KERNEL32.@)
891 VOID WINAPI GlobalUnfix(HGLOBAL hmem)
893 GlobalUnlock( hmem);
897 /***********************************************************************
898 * GlobalFlags (KERNEL32.@)
900 * Get information about a global memory object.
902 * PARAMS
903 * hmem [I] Handle of the global memory object
905 * RETURNS
906 * Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid
907 * Success: Value specifying allocation flags and lock count
910 UINT WINAPI GlobalFlags(HGLOBAL hmem)
912 DWORD retval;
913 PGLOBAL32_INTERN pintern;
915 if(ISPOINTER(hmem))
917 retval=0;
919 else
921 RtlLockHeap(GetProcessHeap());
922 pintern=HANDLE_TO_INTERN(hmem);
923 if(pintern->Magic==MAGIC_GLOBAL_USED)
925 retval=pintern->LockCount + (pintern->Flags<<8);
926 if(pintern->Pointer==0)
927 retval|= GMEM_DISCARDED;
929 else
931 WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
932 SetLastError(ERROR_INVALID_HANDLE);
933 retval = GMEM_INVALID_HANDLE;
935 RtlUnlockHeap(GetProcessHeap());
937 return retval;
941 /***********************************************************************
942 * GlobalCompact (KERNEL32.@)
944 SIZE_T WINAPI GlobalCompact( DWORD minfree )
946 return 0; /* GlobalCompact does nothing in Win32 */
950 /***********************************************************************
951 * LocalAlloc (KERNEL32.@)
953 * Allocate a local memory object.
955 * RETURNS
956 * Handle: Success
957 * NULL: Failure
959 * NOTES
960 * Windows memory management does not provide a separate local heap
961 * and global heap.
963 HLOCAL WINAPI LocalAlloc(
964 UINT flags, /* [in] Allocation attributes */
965 SIZE_T size /* [in] Number of bytes to allocate */
967 return GlobalAlloc( flags, size );
971 /***********************************************************************
972 * LocalCompact (KERNEL32.@)
974 SIZE_T WINAPI LocalCompact( UINT minfree )
976 return 0; /* LocalCompact does nothing in Win32 */
980 /***********************************************************************
981 * LocalFlags (KERNEL32.@)
983 * Get information about a local memory object.
985 * RETURNS
986 * Value specifying allocation flags and lock count.
987 * LMEM_INVALID_HANDLE: Failure
989 * NOTES
990 * Windows memory management does not provide a separate local heap
991 * and global heap.
993 UINT WINAPI LocalFlags(
994 HLOCAL handle /* [in] Handle of memory object */
996 return GlobalFlags( handle );
1000 /***********************************************************************
1001 * LocalFree (KERNEL32.@)
1003 * Free a local memory object.
1005 * RETURNS
1006 * NULL: Success
1007 * Handle: Failure
1009 * NOTES
1010 * Windows memory management does not provide a separate local heap
1011 * and global heap.
1013 HLOCAL WINAPI LocalFree(
1014 HLOCAL handle /* [in] Handle of memory object */
1016 return GlobalFree( handle );
1020 /***********************************************************************
1021 * LocalHandle (KERNEL32.@)
1023 * Get the handle associated with the pointer to a local memory block.
1025 * RETURNS
1026 * Handle: Success
1027 * NULL: Failure
1029 * NOTES
1030 * Windows memory management does not provide a separate local heap
1031 * and global heap.
1033 HLOCAL WINAPI LocalHandle(
1034 LPCVOID ptr /* [in] Address of local memory block */
1036 return GlobalHandle( ptr );
1040 /***********************************************************************
1041 * LocalLock (KERNEL32.@)
1042 * Locks a local memory object and returns pointer to the first byte
1043 * of the memory block.
1045 * RETURNS
1046 * Pointer: Success
1047 * NULL: Failure
1049 * NOTES
1050 * Windows memory management does not provide a separate local heap
1051 * and global heap.
1053 LPVOID WINAPI LocalLock(
1054 HLOCAL handle /* [in] Address of local memory object */
1056 return GlobalLock( handle );
1060 /***********************************************************************
1061 * LocalReAlloc (KERNEL32.@)
1063 * Change the size or attributes of a local memory object.
1065 * RETURNS
1066 * Handle: Success
1067 * NULL: Failure
1069 * NOTES
1070 * Windows memory management does not provide a separate local heap
1071 * and global heap.
1073 HLOCAL WINAPI LocalReAlloc(
1074 HLOCAL handle, /* [in] Handle of memory object */
1075 SIZE_T size, /* [in] New size of block */
1076 UINT flags /* [in] How to reallocate object */
1078 return GlobalReAlloc( handle, size, flags );
1082 /***********************************************************************
1083 * LocalShrink (KERNEL32.@)
1085 SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
1087 return 0; /* LocalShrink does nothing in Win32 */
1091 /***********************************************************************
1092 * LocalSize (KERNEL32.@)
1094 * Get the size of a local memory object.
1096 * RETURNS
1097 * Size: Success
1098 * 0: Failure
1100 * NOTES
1101 * Windows memory management does not provide a separate local heap
1102 * and global heap.
1104 SIZE_T WINAPI LocalSize(
1105 HLOCAL handle /* [in] Handle of memory object */
1107 return GlobalSize( handle );
1111 /***********************************************************************
1112 * LocalUnlock (KERNEL32.@)
1114 * Unlock a local memory object.
1116 * RETURNS
1117 * TRUE: Object is still locked
1118 * FALSE: Object is unlocked
1120 * NOTES
1121 * Windows memory management does not provide a separate local heap
1122 * and global heap.
1124 BOOL WINAPI LocalUnlock(
1125 HLOCAL handle /* [in] Handle of memory object */
1128 if (ISPOINTER( handle ))
1130 SetLastError( ERROR_NOT_LOCKED );
1131 return FALSE;
1134 return GlobalUnlock( handle );
1138 /***********************************************************************
1139 * GlobalMemoryStatusEx (KERNEL32.@)
1140 * A version of GlobalMemoryStatus that can deal with memory over 4GB
1142 * RETURNS
1143 * TRUE
1145 BOOL WINAPI GlobalMemoryStatusEx( LPMEMORYSTATUSEX lpmemex )
1147 static MEMORYSTATUSEX cached_memstatus;
1148 static int cache_lastchecked = 0;
1149 SYSTEM_INFO si;
1150 #ifdef linux
1151 FILE *f;
1152 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1153 DWORDLONG total;
1154 #ifdef __APPLE__
1155 unsigned int val;
1156 #else
1157 unsigned long val;
1158 #endif
1159 int mib[2];
1160 size_t size_sys;
1161 #ifdef HW_MEMSIZE
1162 uint64_t val64;
1163 #endif
1164 #ifdef VM_SWAPUSAGE
1165 struct xsw_usage swap;
1166 #endif
1167 #elif defined(sun)
1168 unsigned long pagesize,maxpages,freepages,swapspace,swapfree;
1169 struct anoninfo swapinf;
1170 int rval;
1171 #endif
1173 if (lpmemex->dwLength != sizeof(*lpmemex))
1175 SetLastError( ERROR_INVALID_PARAMETER );
1176 return FALSE;
1179 if (time(NULL)==cache_lastchecked) {
1180 *lpmemex = cached_memstatus;
1181 return TRUE;
1183 cache_lastchecked = time(NULL);
1185 lpmemex->dwMemoryLoad = 0;
1186 lpmemex->ullTotalPhys = 16*1024*1024;
1187 lpmemex->ullAvailPhys = 16*1024*1024;
1188 lpmemex->ullTotalPageFile = 16*1024*1024;
1189 lpmemex->ullAvailPageFile = 16*1024*1024;
1191 #ifdef linux
1192 f = fopen( "/proc/meminfo", "r" );
1193 if (f)
1195 char buffer[256];
1196 unsigned long total, used, free, shared, buffers, cached;
1198 lpmemex->ullTotalPhys = lpmemex->ullAvailPhys = 0;
1199 lpmemex->ullTotalPageFile = lpmemex->ullAvailPageFile = 0;
1200 while (fgets( buffer, sizeof(buffer), f ))
1202 /* old style /proc/meminfo ... */
1203 if (sscanf( buffer, "Mem: %lu %lu %lu %lu %lu %lu",
1204 &total, &used, &free, &shared, &buffers, &cached ))
1206 lpmemex->ullTotalPhys += total;
1207 lpmemex->ullAvailPhys += free + buffers + cached;
1209 if (sscanf( buffer, "Swap: %lu %lu %lu", &total, &used, &free ))
1211 lpmemex->ullTotalPageFile += total;
1212 lpmemex->ullAvailPageFile += free;
1215 /* new style /proc/meminfo ... */
1216 if (sscanf(buffer, "MemTotal: %lu", &total))
1217 lpmemex->ullTotalPhys = (ULONG64)total*1024;
1218 if (sscanf(buffer, "MemFree: %lu", &free))
1219 lpmemex->ullAvailPhys = (ULONG64)free*1024;
1220 if (sscanf(buffer, "SwapTotal: %lu", &total))
1221 lpmemex->ullTotalPageFile = (ULONG64)total*1024;
1222 if (sscanf(buffer, "SwapFree: %lu", &free))
1223 lpmemex->ullAvailPageFile = (ULONG64)free*1024;
1224 if (sscanf(buffer, "Buffers: %lu", &buffers))
1225 lpmemex->ullAvailPhys += (ULONG64)buffers*1024;
1226 if (sscanf(buffer, "Cached: %lu", &cached))
1227 lpmemex->ullAvailPhys += (ULONG64)cached*1024;
1229 fclose( f );
1231 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1232 total = 0;
1233 lpmemex->ullAvailPhys = 0;
1235 mib[0] = CTL_HW;
1236 #ifdef HW_MEMSIZE
1237 mib[1] = HW_MEMSIZE;
1238 size_sys = sizeof(val64);
1239 if (!sysctl(mib, 2, &val64, &size_sys, NULL, 0) && size_sys == sizeof(val64) && val64)
1240 total = val64;
1241 #endif
1243 #ifdef HAVE_MACH_MACH_H
1245 host_name_port_t host = mach_host_self();
1246 mach_msg_type_number_t count;
1248 #ifdef HOST_VM_INFO64_COUNT
1249 vm_size_t page_size;
1250 vm_statistics64_data_t vm_stat;
1252 count = HOST_VM_INFO64_COUNT;
1253 if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) == KERN_SUCCESS &&
1254 host_page_size(host, &page_size) == KERN_SUCCESS)
1255 lpmemex->ullAvailPhys = (vm_stat.free_count + vm_stat.inactive_count) * (DWORDLONG)page_size;
1256 #endif
1257 if (!total)
1259 host_basic_info_data_t info;
1260 count = HOST_BASIC_INFO_COUNT;
1261 if (host_info(host, HOST_BASIC_INFO, (host_info_t)&info, &count) == KERN_SUCCESS)
1262 total = info.max_mem;
1265 mach_port_deallocate(mach_task_self(), host);
1267 #endif
1269 if (!total)
1271 mib[1] = HW_PHYSMEM;
1272 size_sys = sizeof(val);
1273 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val) && val)
1274 total = val;
1277 if (total)
1278 lpmemex->ullTotalPhys = total;
1280 if (!lpmemex->ullAvailPhys)
1282 mib[1] = HW_USERMEM;
1283 size_sys = sizeof(val);
1284 if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val) && val)
1285 lpmemex->ullAvailPhys = val;
1288 if (!lpmemex->ullAvailPhys)
1289 lpmemex->ullAvailPhys = lpmemex->ullTotalPhys;
1291 lpmemex->ullTotalPageFile = lpmemex->ullAvailPhys;
1292 lpmemex->ullAvailPageFile = lpmemex->ullAvailPhys;
1294 #ifdef VM_SWAPUSAGE
1295 mib[0] = CTL_VM;
1296 mib[1] = VM_SWAPUSAGE;
1297 size_sys = sizeof(swap);
1298 if (!sysctl(mib, 2, &swap, &size_sys, NULL, 0) && size_sys == sizeof(swap))
1300 lpmemex->ullTotalPageFile = swap.xsu_total;
1301 lpmemex->ullAvailPageFile = swap.xsu_avail;
1303 #endif
1304 #elif defined ( sun )
1305 pagesize=sysconf(_SC_PAGESIZE);
1306 maxpages=sysconf(_SC_PHYS_PAGES);
1307 freepages=sysconf(_SC_AVPHYS_PAGES);
1308 rval=swapctl(SC_AINFO, &swapinf);
1309 if(rval >-1)
1311 swapspace=swapinf.ani_max*pagesize;
1312 swapfree=swapinf.ani_free*pagesize;
1313 }else
1316 WARN("Swap size cannot be determined , assuming equal to physical memory\n");
1317 swapspace=maxpages*pagesize;
1318 swapfree=maxpages*pagesize;
1320 lpmemex->ullTotalPhys=pagesize*maxpages;
1321 lpmemex->ullAvailPhys = pagesize*freepages;
1322 lpmemex->ullTotalPageFile = swapspace;
1323 lpmemex->ullAvailPageFile = swapfree;
1324 #endif
1326 if (lpmemex->ullTotalPhys)
1328 lpmemex->dwMemoryLoad = (lpmemex->ullTotalPhys-lpmemex->ullAvailPhys)
1329 / (lpmemex->ullTotalPhys / 100);
1332 /* Win98 returns only the swapsize in ullTotalPageFile/ullAvailPageFile,
1333 WinXP returns the size of physical memory + swapsize;
1334 mimic the behavior of XP.
1335 Note: Project2k refuses to start if it sees less than 1Mb of free swap.
1337 lpmemex->ullTotalPageFile += lpmemex->ullTotalPhys;
1338 lpmemex->ullAvailPageFile += lpmemex->ullAvailPhys;
1340 /* Titan Quest refuses to run if TotalPageFile <= ullTotalPhys */
1341 if(lpmemex->ullTotalPageFile == lpmemex->ullTotalPhys)
1343 lpmemex->ullTotalPhys -= 1;
1344 lpmemex->ullAvailPhys -= 1;
1347 /* FIXME: should do something for other systems */
1348 GetSystemInfo(&si);
1349 lpmemex->ullTotalVirtual = (ULONG_PTR)si.lpMaximumApplicationAddress-(ULONG_PTR)si.lpMinimumApplicationAddress;
1350 /* FIXME: we should track down all the already allocated VM pages and subtract them, for now arbitrarily remove 64KB so that it matches NT */
1351 lpmemex->ullAvailVirtual = lpmemex->ullTotalVirtual-64*1024;
1353 /* MSDN says about AvailExtendedVirtual: Size of unreserved and uncommitted
1354 memory in the extended portion of the virtual address space of the calling
1355 process, in bytes.
1356 However, I don't know what this means, so set it to zero :(
1358 lpmemex->ullAvailExtendedVirtual = 0;
1360 cached_memstatus = *lpmemex;
1362 TRACE_(globalmem)("<-- LPMEMORYSTATUSEX: dwLength %d, dwMemoryLoad %d, ullTotalPhys %s, ullAvailPhys %s,"
1363 " ullTotalPageFile %s, ullAvailPageFile %s, ullTotalVirtual %s, ullAvailVirtual %s\n",
1364 lpmemex->dwLength, lpmemex->dwMemoryLoad, wine_dbgstr_longlong(lpmemex->ullTotalPhys),
1365 wine_dbgstr_longlong(lpmemex->ullAvailPhys), wine_dbgstr_longlong(lpmemex->ullTotalPageFile),
1366 wine_dbgstr_longlong(lpmemex->ullAvailPageFile), wine_dbgstr_longlong(lpmemex->ullTotalVirtual),
1367 wine_dbgstr_longlong(lpmemex->ullAvailVirtual) );
1369 return TRUE;
1372 /***********************************************************************
1373 * GlobalMemoryStatus (KERNEL32.@)
1374 * Provides information about the status of the memory, so apps can tell
1375 * roughly how much they are able to allocate
1377 * RETURNS
1378 * None
1380 VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
1382 MEMORYSTATUSEX memstatus;
1383 OSVERSIONINFOW osver;
1384 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( GetModuleHandleW(0) );
1386 /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
1387 for one extra field in the struct, and the lack of a bug, we simply
1388 call GlobalMemoryStatusEx and copy the values across. */
1389 memstatus.dwLength = sizeof(memstatus);
1390 GlobalMemoryStatusEx(&memstatus);
1392 lpBuffer->dwLength = sizeof(*lpBuffer);
1393 lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;
1395 /* Windows 2000 and later report -1 when values are greater than 4 Gb.
1396 * NT reports values modulo 4 Gb.
1399 osver.dwOSVersionInfoSize = sizeof(osver);
1400 GetVersionExW(&osver);
1402 if ( osver.dwMajorVersion >= 5 || osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
1404 lpBuffer->dwTotalPhys = min( memstatus.ullTotalPhys, MAXDWORD );
1405 lpBuffer->dwAvailPhys = min( memstatus.ullAvailPhys, MAXDWORD );
1406 /* Limit value for apps that do not expect so much memory. Remove last 512 kb to make Sacrifice demo happy. */
1407 lpBuffer->dwTotalPageFile = min( memstatus.ullTotalPageFile, 0xfff7ffff );
1408 lpBuffer->dwAvailPageFile = min( memstatus.ullAvailPageFile, MAXDWORD );
1409 lpBuffer->dwTotalVirtual = min( memstatus.ullTotalVirtual, MAXDWORD );
1410 lpBuffer->dwAvailVirtual = min( memstatus.ullAvailVirtual, MAXDWORD );
1413 else /* duplicate NT bug */
1415 lpBuffer->dwTotalPhys = memstatus.ullTotalPhys;
1416 lpBuffer->dwAvailPhys = memstatus.ullAvailPhys;
1417 lpBuffer->dwTotalPageFile = memstatus.ullTotalPageFile;
1418 lpBuffer->dwAvailPageFile = memstatus.ullAvailPageFile;
1419 lpBuffer->dwTotalVirtual = memstatus.ullTotalVirtual;
1420 lpBuffer->dwAvailVirtual = memstatus.ullAvailVirtual;
1423 /* values are limited to 2Gb unless the app has the IMAGE_FILE_LARGE_ADDRESS_AWARE flag */
1424 /* page file sizes are not limited (Adobe Illustrator 8 depends on this) */
1425 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE))
1427 if (lpBuffer->dwTotalPhys > MAXLONG) lpBuffer->dwTotalPhys = MAXLONG;
1428 if (lpBuffer->dwAvailPhys > MAXLONG) lpBuffer->dwAvailPhys = MAXLONG;
1429 if (lpBuffer->dwTotalVirtual > MAXLONG) lpBuffer->dwTotalVirtual = MAXLONG;
1430 if (lpBuffer->dwAvailVirtual > MAXLONG) lpBuffer->dwAvailVirtual = MAXLONG;
1433 /* work around for broken photoshop 4 installer */
1434 if ( lpBuffer->dwAvailPhys + lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
1435 lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 - lpBuffer->dwAvailPhys - 1;
1437 /* limit page file size for really old binaries */
1438 if (nt->OptionalHeader.MajorSubsystemVersion < 4)
1440 if (lpBuffer->dwTotalPageFile > MAXLONG) lpBuffer->dwTotalPageFile = MAXLONG;
1441 if (lpBuffer->dwAvailPageFile > MAXLONG) lpBuffer->dwAvailPageFile = MAXLONG;
1444 TRACE_(globalmem)("Length %u, MemoryLoad %u, TotalPhys %lx, AvailPhys %lx,"
1445 " TotalPageFile %lx, AvailPageFile %lx, TotalVirtual %lx, AvailVirtual %lx\n",
1446 lpBuffer->dwLength, lpBuffer->dwMemoryLoad, lpBuffer->dwTotalPhys,
1447 lpBuffer->dwAvailPhys, lpBuffer->dwTotalPageFile, lpBuffer->dwAvailPageFile,
1448 lpBuffer->dwTotalVirtual, lpBuffer->dwAvailVirtual );