dbgeng: Update to IDebugControl4 stub.
[wine.git] / dlls / kernel32 / heap.c
blobdf094c942570a42ec6ae926b783d99f71a27a9ab
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 <assert.h>
24 #include <limits.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <sys/types.h>
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winerror.h"
34 #include "winnt.h"
35 #include "winternl.h"
37 #include "kernel_private.h"
39 #include "wine/exception.h"
40 #include "wine/debug.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(globalmem);
44 /* address where we try to map the system heap */
45 #define SYSTEM_HEAP_BASE ((void*)0x80000000)
46 #define SYSTEM_HEAP_SIZE 0x1000000 /* Default heap size = 16Mb */
48 static HANDLE systemHeap; /* globally shared heap */
51 /***********************************************************************
52 * HEAP_CreateSystemHeap
54 * Create the system heap.
56 static inline HANDLE HEAP_CreateSystemHeap(void)
58 int created;
59 void *base;
60 HANDLE map, event;
62 /* create the system heap event first */
63 event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );
65 if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
66 0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
67 created = (GetLastError() != ERROR_ALREADY_EXISTS);
69 if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
71 /* pre-defined address not available */
72 ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
73 return 0;
76 if (created) /* newly created heap */
78 systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
79 SYSTEM_HEAP_SIZE, NULL, NULL );
80 SetEvent( event );
82 else
84 /* wait for the heap to be initialized */
85 WaitForSingleObject( event, INFINITE );
86 systemHeap = base;
88 CloseHandle( map );
89 return systemHeap;
93 /***********************************************************************
94 * HeapCreate (KERNEL32.@)
96 * Create a heap object.
98 * RETURNS
99 * Handle of heap: Success
100 * NULL: Failure
102 HANDLE WINAPI HeapCreate(
103 DWORD flags, /* [in] Heap allocation flag */
104 SIZE_T initialSize, /* [in] Initial heap size */
105 SIZE_T maxSize /* [in] Maximum heap size */
107 HANDLE ret;
109 if ( flags & HEAP_SHARED )
111 if (!systemHeap) HEAP_CreateSystemHeap();
112 else WARN( "Shared Heap requested, returning system heap.\n" );
113 ret = systemHeap;
115 else
117 ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
118 if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
120 return ret;
124 /***********************************************************************
125 * HeapDestroy (KERNEL32.@)
127 * Destroy a heap object.
129 * RETURNS
130 * TRUE: Success
131 * FALSE: Failure
133 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
135 if (heap == systemHeap)
137 WARN( "attempt to destroy system heap, returning TRUE!\n" );
138 return TRUE;
140 if (!RtlDestroyHeap( heap )) return TRUE;
141 SetLastError( ERROR_INVALID_HANDLE );
142 return FALSE;
146 /***********************************************************************
147 * Global/local heap functions, keep in sync with kernelbase/memory.c
148 ***********************************************************************/
150 #define MEM_FLAG_USED 1
151 #define MEM_FLAG_MOVEABLE 2
152 #define MEM_FLAG_DISCARDABLE 4
153 #define MEM_FLAG_DISCARDED 8
154 #define MEM_FLAG_DDESHARE 0x8000
156 struct mem_entry
158 union
160 struct
162 WORD flags;
163 BYTE lock;
165 void *next_free;
167 void *ptr;
170 C_ASSERT(sizeof(struct mem_entry) == 2 * sizeof(void *));
172 struct kernelbase_global_data *kernelbase_global_data;
174 #define POINTER_TO_HANDLE( p ) (*(((const HGLOBAL *)( p )) - 2))
175 /* align the storage needed for the HLOCAL on an 8-byte boundary thus
176 * LocalAlloc/LocalReAlloc'ing with LMEM_MOVEABLE of memory with
177 * size = 8*k, where k=1,2,3,... allocs exactly the given size.
178 * The Minolta DiMAGE Image Viewer heavily relies on this, corrupting
179 * the output jpeg's > 1 MB if not */
180 #define HLOCAL_STORAGE (sizeof(HLOCAL) * 2)
182 static inline struct mem_entry *unsafe_mem_from_HLOCAL( HLOCAL handle )
184 struct mem_entry *mem = CONTAINING_RECORD( handle, struct mem_entry, ptr );
185 struct kernelbase_global_data *data = kernelbase_global_data;
186 if (((UINT_PTR)handle & ((sizeof(void *) << 1) - 1)) != sizeof(void *)) return NULL;
187 if (mem < data->mem_entries || mem >= data->mem_entries_end) return NULL;
188 if (!(mem->flags & MEM_FLAG_USED)) return NULL;
189 return mem;
192 static inline void *unsafe_ptr_from_HLOCAL( HLOCAL handle )
194 if (((UINT_PTR)handle & ((sizeof(void *) << 1) - 1))) return NULL;
195 return handle;
199 /***********************************************************************
200 * GlobalLock (KERNEL32.@)
202 * Lock a global memory object and return a pointer to first byte of the memory
204 * PARAMS
205 * handle [I] Handle of the global memory object
207 * RETURNS
208 * Success: Pointer to first byte of the memory block
209 * Failure: NULL
211 * NOTES
212 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
215 void *WINAPI GlobalLock( HGLOBAL handle )
217 return LocalLock( handle );
221 /***********************************************************************
222 * GlobalUnlock (KERNEL32.@)
224 * Unlock a global memory object.
226 * PARAMS
227 * handle [I] Handle of the global memory object
229 * RETURNS
230 * Success: Object is still locked
231 * Failure: FALSE (The Object is unlocked)
233 * NOTES
234 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
237 BOOL WINAPI GlobalUnlock( HGLOBAL handle )
239 if (unsafe_ptr_from_HLOCAL( handle )) return TRUE;
240 return LocalUnlock( handle );
244 /***********************************************************************
245 * GlobalHandle (KERNEL32.@)
247 * Get the handle associated with the pointer to a global memory block.
249 * RETURNS
250 * Handle: Success
251 * NULL: Failure
253 HGLOBAL WINAPI GlobalHandle( const void *ptr )
255 struct mem_entry *mem;
256 HGLOBAL handle;
257 LPCVOID test;
259 TRACE_(globalmem)( "ptr %p\n", ptr );
261 if (!ptr)
263 SetLastError( ERROR_INVALID_PARAMETER );
264 return 0;
267 RtlLockHeap( GetProcessHeap() );
268 __TRY
270 handle = 0;
272 /* note that if ptr is a pointer to a block allocated by */
273 /* GlobalAlloc with GMEM_MOVEABLE then magic test in HeapValidate */
274 /* will fail. */
275 if ((ptr = unsafe_ptr_from_HLOCAL( (HLOCAL)ptr )))
277 if (HeapValidate( GetProcessHeap(), HEAP_NO_SERIALIZE, ptr ))
279 handle = (HGLOBAL)ptr; /* valid fixed block */
280 break;
282 handle = POINTER_TO_HANDLE( ptr );
284 else handle = (HGLOBAL)ptr;
286 /* Now test handle either passed in or retrieved from pointer */
287 if ((mem = unsafe_mem_from_HLOCAL( handle )))
289 test = mem->ptr;
290 if (HeapValidate( GetProcessHeap(), HEAP_NO_SERIALIZE, (const char *)test - HLOCAL_STORAGE )) /* obj(-handle) valid arena? */
291 break; /* valid moveable block */
293 handle = 0;
294 SetLastError( ERROR_INVALID_HANDLE );
296 __EXCEPT_PAGE_FAULT
298 SetLastError( ERROR_INVALID_HANDLE );
299 handle = 0;
301 __ENDTRY
302 RtlUnlockHeap( GetProcessHeap() );
304 return handle;
307 /***********************************************************************
308 * GlobalReAlloc (KERNEL32.@)
310 * Change the size or attributes of a global memory object.
312 * RETURNS
313 * Handle: Success
314 * NULL: Failure
316 HGLOBAL WINAPI GlobalReAlloc( HGLOBAL handle, SIZE_T size, UINT flags )
318 return LocalReAlloc( handle, size, flags );
322 /***********************************************************************
323 * GlobalSize (KERNEL32.@)
325 * Get the size of a global memory object.
327 * PARAMS
328 * handle [I] Handle of the global memory object
330 * RETURNS
331 * Failure: 0
332 * Success: Size in Bytes of the global memory object
334 * NOTES
335 * When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
338 SIZE_T WINAPI GlobalSize( HGLOBAL handle )
340 struct mem_entry *mem;
341 SIZE_T retval;
342 void *ptr;
344 TRACE_(globalmem)( "handle %p\n", handle );
346 if (!((ULONG_PTR)handle >> 16))
348 SetLastError( ERROR_INVALID_HANDLE );
349 return 0;
352 if ((ptr = unsafe_ptr_from_HLOCAL( handle )))
354 retval = HeapSize( GetProcessHeap(), 0, ptr );
355 if (retval == ~(SIZE_T)0) /* It might be a GMEM_MOVEABLE data pointer */
357 retval = HeapSize( GetProcessHeap(), 0, (char *)ptr - HLOCAL_STORAGE );
358 if (retval != ~(SIZE_T)0) retval -= HLOCAL_STORAGE;
361 else
363 RtlLockHeap( GetProcessHeap() );
364 if ((mem = unsafe_mem_from_HLOCAL( handle )))
366 if (!mem->ptr) /* handle case of GlobalAlloc( ??,0) */
367 retval = 0;
368 else
370 retval = HeapSize( GetProcessHeap(), 0, (char *)mem->ptr - HLOCAL_STORAGE );
371 if (retval != ~(SIZE_T)0) retval -= HLOCAL_STORAGE;
374 else
376 WARN_(globalmem)( "invalid handle %p\n", handle );
377 SetLastError( ERROR_INVALID_HANDLE );
378 retval = 0;
380 RtlUnlockHeap( GetProcessHeap() );
382 if (retval == ~(SIZE_T)0) retval = 0;
383 return retval;
387 /***********************************************************************
388 * GlobalWire (KERNEL32.@)
390 void *WINAPI GlobalWire( HGLOBAL handle )
392 return GlobalLock( handle );
396 /***********************************************************************
397 * GlobalUnWire (KERNEL32.@)
399 BOOL WINAPI GlobalUnWire( HGLOBAL handle )
401 return GlobalUnlock( handle );
405 /***********************************************************************
406 * GlobalFix (KERNEL32.@)
408 VOID WINAPI GlobalFix( HGLOBAL handle )
410 GlobalLock( handle );
414 /***********************************************************************
415 * GlobalUnfix (KERNEL32.@)
417 VOID WINAPI GlobalUnfix( HGLOBAL handle )
419 GlobalUnlock( handle );
423 /***********************************************************************
424 * GlobalFlags (KERNEL32.@)
426 * Get information about a global memory object.
428 * PARAMS
429 * handle [I] Handle of the global memory object
431 * RETURNS
432 * Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid
433 * Success: Value specifying allocation flags and lock count
436 UINT WINAPI GlobalFlags( HGLOBAL handle )
438 HANDLE heap = GetProcessHeap();
439 struct mem_entry *mem;
440 UINT flags;
442 if (unsafe_ptr_from_HLOCAL( handle )) return 0;
444 RtlLockHeap( heap );
445 if ((mem = unsafe_mem_from_HLOCAL( handle )))
447 flags = mem->lock;
448 if (mem->flags & MEM_FLAG_DISCARDABLE) flags |= GMEM_DISCARDABLE;
449 if (mem->flags & MEM_FLAG_DISCARDED) flags |= GMEM_DISCARDED;
450 if (mem->flags & MEM_FLAG_DDESHARE) flags |= GMEM_DDESHARE;
452 else
454 WARN_(globalmem)( "invalid handle %p\n", handle );
455 SetLastError( ERROR_INVALID_HANDLE );
456 flags = GMEM_INVALID_HANDLE;
458 RtlUnlockHeap( heap );
460 return flags;
464 /***********************************************************************
465 * GlobalCompact (KERNEL32.@)
467 SIZE_T WINAPI GlobalCompact( DWORD minfree )
469 return 0; /* GlobalCompact does nothing in Win32 */
473 /***********************************************************************
474 * LocalCompact (KERNEL32.@)
476 SIZE_T WINAPI LocalCompact( UINT minfree )
478 return 0; /* LocalCompact does nothing in Win32 */
482 /***********************************************************************
483 * LocalFlags (KERNEL32.@)
485 * Get information about a local memory object.
487 * RETURNS
488 * Value specifying allocation flags and lock count.
489 * LMEM_INVALID_HANDLE: Failure
491 * NOTES
492 * Windows memory management does not provide a separate local heap
493 * and global heap.
495 UINT WINAPI LocalFlags( HLOCAL handle )
497 UINT flags = GlobalFlags( handle );
498 if (flags & GMEM_DISCARDABLE) flags |= LMEM_DISCARDABLE;
499 return flags;
503 /***********************************************************************
504 * LocalHandle (KERNEL32.@)
506 * Get the handle associated with the pointer to a local memory block.
508 * RETURNS
509 * Handle: Success
510 * NULL: Failure
512 * NOTES
513 * Windows memory management does not provide a separate local heap
514 * and global heap.
516 HLOCAL WINAPI LocalHandle(
517 LPCVOID ptr /* [in] Address of local memory block */
519 return GlobalHandle( ptr );
523 /***********************************************************************
524 * LocalShrink (KERNEL32.@)
526 SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
528 return 0; /* LocalShrink does nothing in Win32 */
532 /***********************************************************************
533 * LocalSize (KERNEL32.@)
535 * Get the size of a local memory object.
537 * RETURNS
538 * Size: Success
539 * 0: Failure
541 * NOTES
542 * Windows memory management does not provide a separate local heap
543 * and global heap.
545 SIZE_T WINAPI LocalSize(
546 HLOCAL handle /* [in] Handle of memory object */
548 return GlobalSize( handle );
552 /***********************************************************************
553 * GlobalMemoryStatus (KERNEL32.@)
554 * Provides information about the status of the memory, so apps can tell
555 * roughly how much they are able to allocate
557 * RETURNS
558 * None
560 VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
562 MEMORYSTATUSEX memstatus;
563 OSVERSIONINFOW osver;
564 #ifndef _WIN64
565 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( GetModuleHandleW(0) );
566 #endif
568 /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
569 for one extra field in the struct, and the lack of a bug, we simply
570 call GlobalMemoryStatusEx and copy the values across. */
571 memstatus.dwLength = sizeof(memstatus);
572 GlobalMemoryStatusEx(&memstatus);
574 lpBuffer->dwLength = sizeof(*lpBuffer);
575 lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;
577 /* Windows 2000 and later report -1 when values are greater than 4 Gb.
578 * NT reports values modulo 4 Gb.
581 osver.dwOSVersionInfoSize = sizeof(osver);
582 GetVersionExW(&osver);
584 lpBuffer->dwTotalPhys = memstatus.ullTotalPhys;
585 lpBuffer->dwAvailPhys = memstatus.ullAvailPhys;
586 lpBuffer->dwTotalPageFile = memstatus.ullTotalPageFile;
587 lpBuffer->dwAvailPageFile = memstatus.ullAvailPageFile;
588 lpBuffer->dwTotalVirtual = memstatus.ullTotalVirtual;
589 lpBuffer->dwAvailVirtual = memstatus.ullAvailVirtual;
591 #ifndef _WIN64
592 if ( osver.dwMajorVersion >= 5 || osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
594 lpBuffer->dwTotalPhys = min( memstatus.ullTotalPhys, MAXDWORD );
595 lpBuffer->dwAvailPhys = min( memstatus.ullAvailPhys, MAXDWORD );
596 /* Limit value for apps that do not expect so much memory. Remove last 512 kb to make Sacrifice demo happy. */
597 lpBuffer->dwTotalPageFile = min( memstatus.ullTotalPageFile, 0xfff7ffff );
598 lpBuffer->dwAvailPageFile = min( memstatus.ullAvailPageFile, MAXDWORD );
599 lpBuffer->dwTotalVirtual = min( memstatus.ullTotalVirtual, MAXDWORD );
600 lpBuffer->dwAvailVirtual = min( memstatus.ullAvailVirtual, MAXDWORD );
603 /* values are limited to 2Gb unless the app has the IMAGE_FILE_LARGE_ADDRESS_AWARE flag */
604 /* page file sizes are not limited (Adobe Illustrator 8 depends on this) */
605 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE))
607 if (lpBuffer->dwTotalPhys > MAXLONG) lpBuffer->dwTotalPhys = MAXLONG;
608 if (lpBuffer->dwAvailPhys > MAXLONG) lpBuffer->dwAvailPhys = MAXLONG;
609 if (lpBuffer->dwTotalVirtual > MAXLONG) lpBuffer->dwTotalVirtual = MAXLONG;
610 if (lpBuffer->dwAvailVirtual > MAXLONG) lpBuffer->dwAvailVirtual = MAXLONG;
613 /* work around for broken photoshop 4 installer */
614 if ( lpBuffer->dwAvailPhys + lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
615 lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 - lpBuffer->dwAvailPhys - 1;
617 /* limit page file size for really old binaries */
618 if (nt->OptionalHeader.MajorSubsystemVersion < 4 ||
619 nt->OptionalHeader.MajorOperatingSystemVersion < 4)
621 if (lpBuffer->dwTotalPageFile > MAXLONG) lpBuffer->dwTotalPageFile = MAXLONG;
622 if (lpBuffer->dwAvailPageFile > MAXLONG) lpBuffer->dwAvailPageFile = MAXLONG;
624 #endif
626 TRACE("Length %lu, MemoryLoad %lu, TotalPhys %Ix, AvailPhys %Ix,"
627 " TotalPageFile %Ix, AvailPageFile %Ix, TotalVirtual %Ix, AvailVirtual %Ix\n",
628 lpBuffer->dwLength, lpBuffer->dwMemoryLoad, lpBuffer->dwTotalPhys,
629 lpBuffer->dwAvailPhys, lpBuffer->dwTotalPageFile, lpBuffer->dwAvailPageFile,
630 lpBuffer->dwTotalVirtual, lpBuffer->dwAvailVirtual );