heap.c 42.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Win32 heap functions
 *
 * Copyright 1995, 1996 Alexandre Julliard
 * Copyright 1996 Huw Davies
 * Copyright 1998 Ulrich Weigand
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
21 22 23
 */

#include "config.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
24
#include "wine/port.h"
25 26

#include <assert.h>
27
#include <limits.h>
28 29 30 31
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
32 33 34 35 36 37 38 39 40 41 42
#include <sys/types.h>
#include <time.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
43 44 45
#ifdef HAVE_MACH_MACH_H
#include <mach/mach.h>
#endif
46

47 48 49 50
#ifdef sun
/* FIXME:  Unfortunately swapctl can't be used with largefile.... */
# undef _FILE_OFFSET_BITS
# define _FILE_OFFSET_BITS 32
51 52 53
# ifdef HAVE_SYS_RESOURCE_H
#  include <sys/resource.h>
# endif
54 55 56
# ifdef HAVE_SYS_STAT_H
#  include <sys/stat.h>
# endif
57 58 59 60
# include <sys/swap.h>
#endif


61 62 63 64 65 66 67 68 69
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "winnt.h"
#include "winternl.h"
#include "wine/exception.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(heap);
70
WINE_DECLARE_DEBUG_CHANNEL(globalmem);
71 72

/* address where we try to map the system heap */
73 74
#define SYSTEM_HEAP_BASE  ((void*)0x80000000)
#define SYSTEM_HEAP_SIZE  0x1000000   /* Default heap size = 16Mb */
75 76 77 78 79 80 81 82 83

static HANDLE systemHeap;   /* globally shared heap */


/***********************************************************************
 *           HEAP_CreateSystemHeap
 *
 * Create the system heap.
 */
84
static inline HANDLE HEAP_CreateSystemHeap(void)
85 86 87 88
{
    int created;
    void *base;
    HANDLE map, event;
89 90

    /* create the system heap event first */
91
    event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );
92 93

    if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
94
                                    0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
95 96 97 98 99 100 101 102 103 104 105 106 107
    created = (GetLastError() != ERROR_ALREADY_EXISTS);

    if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
    {
        /* pre-defined address not available */
        ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
        return 0;
    }

    if (created)  /* newly created heap */
    {
        systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
                                    SYSTEM_HEAP_SIZE, NULL, NULL );
108
        SetEvent( event );
109 110 111 112 113
    }
    else
    {
        /* wait for the heap to be initialized */
        WaitForSingleObject( event, INFINITE );
114
        systemHeap = base;
115 116 117 118 119 120 121 122
    }
    CloseHandle( map );
    return systemHeap;
}


/***********************************************************************
 *           HeapCreate   (KERNEL32.@)
123 124 125
 *
 * Create a heap object.
 *
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
 * RETURNS
 *	Handle of heap: Success
 *	NULL: Failure
 */
HANDLE WINAPI HeapCreate(
                DWORD flags,       /* [in] Heap allocation flag */
                SIZE_T initialSize, /* [in] Initial heap size */
                SIZE_T maxSize      /* [in] Maximum heap size */
) {
    HANDLE ret;

    if ( flags & HEAP_SHARED )
    {
        if (!systemHeap) HEAP_CreateSystemHeap();
        else WARN( "Shared Heap requested, returning system heap.\n" );
        ret = systemHeap;
    }
    else
    {
        ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
        if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
    }
    return ret;
}


/***********************************************************************
 *           HeapDestroy   (KERNEL32.@)
154 155 156
 *
 * Destroy a heap object.
 *
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
{
    if (heap == systemHeap)
    {
        WARN( "attempt to destroy system heap, returning TRUE!\n" );
        return TRUE;
    }
    if (!RtlDestroyHeap( heap )) return TRUE;
    SetLastError( ERROR_INVALID_HANDLE );
    return FALSE;
}


/***********************************************************************
 *           HeapCompact   (KERNEL32.@)
 */
SIZE_T WINAPI HeapCompact( HANDLE heap, DWORD flags )
{
    return RtlCompactHeap( heap, flags );
}


/***********************************************************************
 *           HeapValidate   (KERNEL32.@)
 * Validates a specified heap.
 *
 * NOTES
 *	Flags is ignored.
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
BOOL WINAPI HeapValidate(
              HANDLE heap, /* [in] Handle to the heap */
              DWORD flags,   /* [in] Bit flags that control access during operation */
              LPCVOID block  /* [in] Optional pointer to memory block to validate */
) {
    return RtlValidateHeap( heap, flags, block );
}


/***********************************************************************
 *           HeapWalk   (KERNEL32.@)
 * Enumerates the memory blocks in a specified heap.
 *
 * TODO
 *   - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
 *     PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
BOOL WINAPI HeapWalk(
              HANDLE heap,               /* [in]  Handle to heap to enumerate */
              LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
) {
    NTSTATUS ret = RtlWalkHeap( heap, entry );
    if (ret) SetLastError( RtlNtStatusToDosError(ret) );
    return !ret;
}


225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
/***********************************************************************
 *           HeapLock   (KERNEL32.@)
 * Attempts to acquire the critical section object for a specified heap.
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
BOOL WINAPI HeapLock(
              HANDLE heap /* [in] Handle of heap to lock for exclusive access */
) {
    return RtlLockHeap( heap );
}


/***********************************************************************
 *           HeapUnlock   (KERNEL32.@)
 * Releases ownership of the critical section object.
 *
 * RETURNS
 *	TRUE: Success
 *	FALSE: Failure
 */
BOOL WINAPI HeapUnlock(
              HANDLE heap /* [in] Handle to the heap to unlock */
) {
    return RtlUnlockHeap( heap );
}


255 256 257 258 259 260 261 262 263
/***********************************************************************
 *           GetProcessHeaps    (KERNEL32.@)
 */
DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
{
    return RtlGetProcessHeaps( count, heaps );
}


264 265
/* These are needed so that we can call the functions from inside kernel itself */

266 267 268
/***********************************************************************
 *           HeapAlloc    (KERNEL32.@)
 */
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
LPVOID WINAPI HeapAlloc( HANDLE heap, DWORD flags, SIZE_T size )
{
    return RtlAllocateHeap( heap, flags, size );
}

BOOL WINAPI HeapFree( HANDLE heap, DWORD flags, LPVOID ptr )
{
    return RtlFreeHeap( heap, flags, ptr );
}

LPVOID WINAPI HeapReAlloc( HANDLE heap, DWORD flags, LPVOID ptr, SIZE_T size )
{
    return RtlReAllocateHeap( heap, flags, ptr, size );
}

284
SIZE_T WINAPI HeapSize( HANDLE heap, DWORD flags, LPCVOID ptr )
285 286 287 288
{
    return RtlSizeHeap( heap, flags, ptr );
}

289 290 291 292 293 294 295 296
BOOL WINAPI HeapQueryInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
                                  PVOID info, SIZE_T size_in, PSIZE_T size_out)
{
    NTSTATUS ret = RtlQueryHeapInformation( heap, info_class, info, size_in, size_out );
    if (ret) SetLastError( RtlNtStatusToDosError(ret) );
    return !ret;
}

297 298
BOOL WINAPI HeapSetInformation( HANDLE heap, HEAP_INFORMATION_CLASS infoclass, PVOID info, SIZE_T size)
{
299 300 301
    NTSTATUS ret = RtlSetHeapInformation( heap, infoclass, info, size );
    if (ret) SetLastError( RtlNtStatusToDosError(ret) );
    return !ret;
302 303
}

304 305 306 307 308 309 310 311 312 313 314 315 316 317
/*
 * Win32 Global heap functions (GlobalXXX).
 * These functions included in Win32 for compatibility with 16 bit Windows
 * Especially the moveable blocks and handles are oldish.
 * But the ability to directly allocate memory with GPTR and LPTR is widely
 * used.
 *
 * The handle stuff looks horrible, but it's implemented almost like Win95
 * does it.
 *
 */

#define MAGIC_GLOBAL_USED 0x5342
#define HANDLE_TO_INTERN(h)  ((PGLOBAL32_INTERN)(((char *)(h))-2))
318
#define INTERN_TO_HANDLE(i)  (&((i)->Pointer))
319
#define POINTER_TO_HANDLE(p) (*(((const HGLOBAL *)(p))-2))
320 321 322 323 324 325 326
#define ISHANDLE(h)          (((ULONG_PTR)(h)&2)!=0)
#define ISPOINTER(h)         (((ULONG_PTR)(h)&2)==0)
/* align the storage needed for the HGLOBAL on an 8byte boundary thus
 * GlobalAlloc/GlobalReAlloc'ing with GMEM_MOVEABLE of memory with
 * size = 8*k, where k=1,2,3,... alloc's exactly the given size.
 * The Minolta DiMAGE Image Viewer heavily relies on this, corrupting
 * the output jpeg's > 1 MB if not */
327
#define HGLOBAL_STORAGE      (sizeof(HGLOBAL)*2)
328

329 330
#include "pshpack1.h"

331 332 333
typedef struct __GLOBAL32_INTERN
{
   WORD         Magic;
334
   LPVOID       Pointer;
335 336 337 338
   BYTE         Flags;
   BYTE         LockCount;
} GLOBAL32_INTERN, *PGLOBAL32_INTERN;

339
#include "poppack.h"
340 341 342

/***********************************************************************
 *           GlobalAlloc   (KERNEL32.@)
343 344 345
 *
 * Allocate a global memory object.
 *
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
 * RETURNS
 *      Handle: Success
 *      NULL: Failure
 */
HGLOBAL WINAPI GlobalAlloc(
                 UINT flags, /* [in] Object allocation attributes */
                 SIZE_T size /* [in] Number of bytes to allocate */
) {
   PGLOBAL32_INTERN     pintern;
   DWORD                hpflags;
   LPVOID               palloc;

   if(flags&GMEM_ZEROINIT)
      hpflags=HEAP_ZERO_MEMORY;
   else
      hpflags=0;

   if((flags & GMEM_MOVEABLE)==0) /* POINTER */
   {
365
      palloc = HeapAlloc( GetProcessHeap(), hpflags, max( 1, size ));
366
      TRACE( "(flags=%04x) returning %p\n",  flags, palloc );
367
      return palloc;
368 369 370
   }
   else  /* HANDLE */
   {
371 372 373 374 375 376
      if (size > INT_MAX-HGLOBAL_STORAGE)
      {
          SetLastError(ERROR_OUTOFMEMORY);
          return 0;
      }

377 378 379
      pintern = HeapAlloc(GetProcessHeap(), 0, sizeof(GLOBAL32_INTERN));
      if (pintern)
      {
380 381 382
          /* Mask out obsolete flags */
          flags &= ~(GMEM_LOWER | GMEM_NOCOMPACT | GMEM_NOT_BANKED | GMEM_NOTIFY);

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
          pintern->Magic = MAGIC_GLOBAL_USED;
          pintern->Flags = flags >> 8;
          pintern->LockCount = 0;

          if (size)
          {
              palloc = HeapAlloc(GetProcessHeap(), hpflags, size+HGLOBAL_STORAGE);
              if (!palloc)
              {
                  HeapFree(GetProcessHeap(), 0, pintern);
                  pintern = NULL;
              }
              else
              {
                  *(HGLOBAL *)palloc = INTERN_TO_HANDLE(pintern);
                  pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
              }
          }
          else
              pintern->Pointer = NULL;
      }

405 406 407 408
      if (!pintern) return 0;
      TRACE( "(flags=%04x) returning handle %p pointer %p\n",
             flags, INTERN_TO_HANDLE(pintern), pintern->Pointer );
      return INTERN_TO_HANDLE(pintern);
409 410 411 412 413 414
   }
}


/***********************************************************************
 *           GlobalLock   (KERNEL32.@)
415
 *
416 417 418 419
 * Lock a global memory object and return a pointer to first byte of the memory
 *
 * PARAMS
 *  hmem [I] Handle of the global memory object
420
 *
421
 * RETURNS
422 423 424 425 426 427
 *  Success: Pointer to first byte of the memory block
 *  Failure: NULL
 *
 * NOTES
 *   When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
 *
428
 */
429
LPVOID WINAPI GlobalLock(HGLOBAL hmem)
430 431 432 433 434 435 436 437 438 439 440 441 442 443
{
    PGLOBAL32_INTERN pintern;
    LPVOID           palloc;

    if (ISPOINTER(hmem))
        return IsBadReadPtr(hmem, 1) ? NULL : hmem;

    RtlLockHeap(GetProcessHeap());
    __TRY
    {
        pintern = HANDLE_TO_INTERN(hmem);
        if (pintern->Magic == MAGIC_GLOBAL_USED)
        {
            palloc = pintern->Pointer;
444 445
            if (!pintern->Pointer)
                SetLastError(ERROR_DISCARDED);
446 447
            else if (pintern->LockCount < GMEM_LOCKCOUNT)
                pintern->LockCount++;
448 449 450
        }
        else
        {
451
            WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
452 453 454 455
            palloc = NULL;
            SetLastError(ERROR_INVALID_HANDLE);
        }
    }
456
    __EXCEPT_PAGE_FAULT
457
    {
458
        WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
459 460 461 462 463 464 465 466 467 468 469
        palloc = NULL;
        SetLastError(ERROR_INVALID_HANDLE);
    }
    __ENDTRY
    RtlUnlockHeap(GetProcessHeap());
    return palloc;
}


/***********************************************************************
 *           GlobalUnlock   (KERNEL32.@)
470 471 472
 *
 * Unlock a global memory object.
 *
473 474 475
 * PARAMS
 *  hmem [I] Handle of the global memory object
 *
476
 * RETURNS
477 478 479 480 481 482
 *  Success: Object is still locked
 *  Failure: FALSE (The Object is unlocked)
 *
 * NOTES
 *   When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
 *
483
 */
484 485
BOOL WINAPI GlobalUnlock(HGLOBAL hmem)
{
486 487 488
    PGLOBAL32_INTERN pintern;
    BOOL locked;

489
    if (ISPOINTER(hmem)) return TRUE;
490 491 492 493 494 495 496

    RtlLockHeap(GetProcessHeap());
    __TRY
    {
        pintern=HANDLE_TO_INTERN(hmem);
        if(pintern->Magic==MAGIC_GLOBAL_USED)
        {
497 498
            if(pintern->LockCount)
            {
499
                pintern->LockCount--;
500 501 502 503 504 505 506 507 508
                locked = (pintern->LockCount != 0);
                if (!locked) SetLastError(NO_ERROR);
            }
            else
            {
                WARN("%p not locked\n", hmem);
                SetLastError(ERROR_NOT_LOCKED);
                locked = FALSE;
            }
509 510 511
        }
        else
        {
512
            WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
513 514 515 516
            SetLastError(ERROR_INVALID_HANDLE);
            locked=FALSE;
        }
    }
517
    __EXCEPT_PAGE_FAULT
518
    {
519
        WARN("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
520 521 522 523 524 525 526 527 528 529 530
        SetLastError( ERROR_INVALID_PARAMETER );
        locked=FALSE;
    }
    __ENDTRY
    RtlUnlockHeap(GetProcessHeap());
    return locked;
}


/***********************************************************************
 *           GlobalHandle   (KERNEL32.@)
531 532
 *
 * Get the handle associated with the pointer to a global memory block.
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
 *
 * RETURNS
 *      Handle: Success
 *      NULL: Failure
 */
HGLOBAL WINAPI GlobalHandle(
                 LPCVOID pmem /* [in] Pointer to global memory block */
) {
    HGLOBAL handle;
    PGLOBAL32_INTERN  maybe_intern;
    LPCVOID test;

    if (!pmem)
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }

    RtlLockHeap(GetProcessHeap());
    __TRY
    {
        handle = 0;

556
        /* note that if pmem is a pointer to a block allocated by        */
557 558 559
        /* GlobalAlloc with GMEM_MOVEABLE then magic test in HeapValidate  */
        /* will fail.                                                      */
        if (ISPOINTER(pmem)) {
560
            if (HeapValidate( GetProcessHeap(), HEAP_NO_SERIALIZE, pmem )) {
561 562 563 564 565 566 567 568 569 570 571
                handle = (HGLOBAL)pmem;  /* valid fixed block */
                break;
            }
            handle = POINTER_TO_HANDLE(pmem);
        } else
            handle = (HGLOBAL)pmem;

        /* Now test handle either passed in or retrieved from pointer */
        maybe_intern = HANDLE_TO_INTERN( handle );
        if (maybe_intern->Magic == MAGIC_GLOBAL_USED) {
            test = maybe_intern->Pointer;
572 573
            if (HeapValidate( GetProcessHeap(), HEAP_NO_SERIALIZE, (const char *)test - HGLOBAL_STORAGE ) && /* obj(-handle) valid arena? */
                HeapValidate( GetProcessHeap(), HEAP_NO_SERIALIZE, maybe_intern ))  /* intern valid arena? */
574 575 576 577 578
                break;  /* valid moveable block */
        }
        handle = 0;
        SetLastError( ERROR_INVALID_HANDLE );
    }
579
    __EXCEPT_PAGE_FAULT
580 581 582 583 584 585 586 587 588 589 590 591 592
    {
        SetLastError( ERROR_INVALID_HANDLE );
        handle = 0;
    }
    __ENDTRY
    RtlUnlockHeap(GetProcessHeap());

    return handle;
}


/***********************************************************************
 *           GlobalReAlloc   (KERNEL32.@)
593 594 595
 *
 * Change the size or attributes of a global memory object.
 *
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
 * RETURNS
 *      Handle: Success
 *      NULL: Failure
 */
HGLOBAL WINAPI GlobalReAlloc(
                 HGLOBAL hmem, /* [in] Handle of global memory object */
                 SIZE_T size,  /* [in] New size of block */
                 UINT flags    /* [in] How to reallocate object */
) {
   LPVOID               palloc;
   HGLOBAL            hnew;
   PGLOBAL32_INTERN     pintern;
   DWORD heap_flags = (flags & GMEM_ZEROINIT) ? HEAP_ZERO_MEMORY : 0;

   hnew = 0;
   RtlLockHeap(GetProcessHeap());
   if(flags & GMEM_MODIFY) /* modify flags */
   {
      if( ISPOINTER(hmem) && (flags & GMEM_MOVEABLE))
      {
         /* make a fixed block moveable
          * actually only NT is able to do this. But it's soo simple
          */
         if (hmem == 0)
         {
             WARN("GlobalReAlloc with null handle!\n");
             SetLastError( ERROR_NOACCESS );
             hnew = 0;
         }
         else
         {
627
             size = HeapSize(GetProcessHeap(), 0, hmem);
628 629
             hnew = GlobalAlloc(flags, size);
             palloc = GlobalLock(hnew);
630
             memcpy(palloc, hmem, size);
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
             GlobalUnlock(hnew);
             GlobalFree(hmem);
         }
      }
      else if( ISPOINTER(hmem) &&(flags & GMEM_DISCARDABLE))
      {
         /* change the flags to make our block "discardable" */
         pintern=HANDLE_TO_INTERN(hmem);
         pintern->Flags = pintern->Flags | (GMEM_DISCARDABLE >> 8);
         hnew=hmem;
      }
      else
      {
         SetLastError(ERROR_INVALID_PARAMETER);
         hnew = 0;
      }
   }
   else
   {
      if(ISPOINTER(hmem))
      {
         /* reallocate fixed memory */
653 654
         if (!(flags & GMEM_MOVEABLE))
            heap_flags |= HEAP_REALLOC_IN_PLACE_ONLY;
655
         hnew=HeapReAlloc(GetProcessHeap(), heap_flags, hmem, size);
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
      }
      else
      {
         /* reallocate a moveable block */
         pintern=HANDLE_TO_INTERN(hmem);

#if 0
/* Apparently Windows doesn't care whether the handle is locked at this point */
/* See also the same comment in GlobalFree() */
         if(pintern->LockCount>1) {
            ERR("handle 0x%08lx is still locked, cannot realloc!\n",(DWORD)hmem);
            SetLastError(ERROR_INVALID_HANDLE);
         } else
#endif
         if(size!=0)
         {
            hnew=hmem;
            if(pintern->Pointer)
            {
675 676 677 678 679 680
               if(size > INT_MAX-HGLOBAL_STORAGE)
               {
                   SetLastError(ERROR_OUTOFMEMORY);
                   hnew = 0;
               }
               else if((palloc = HeapReAlloc(GetProcessHeap(), heap_flags,
681 682 683 684 685 686 687 688
                                   (char *) pintern->Pointer-HGLOBAL_STORAGE,
                                   size+HGLOBAL_STORAGE)) == NULL)
                   hnew = 0; /* Block still valid */
               else
                   pintern->Pointer = (char *)palloc+HGLOBAL_STORAGE;
            }
            else
            {
689 690 691 692 693 694
                if(size > INT_MAX-HGLOBAL_STORAGE)
                {
                    SetLastError(ERROR_OUTOFMEMORY);
                    hnew = 0;
                }
                else if((palloc=HeapAlloc(GetProcessHeap(), heap_flags, size+HGLOBAL_STORAGE))
695 696 697 698 699 700 701 702 703 704 705
                   == NULL)
                    hnew = 0;
                else
                {
                    *(HGLOBAL *)palloc = hmem;
                    pintern->Pointer = (char *)palloc + HGLOBAL_STORAGE;
                }
            }
         }
         else
         {
706
            if (pintern->LockCount == 0)
707
            {
708 709 710 711 712 713
                if(pintern->Pointer)
                {
                    HeapFree(GetProcessHeap(), 0, (char *) pintern->Pointer-HGLOBAL_STORAGE);
                    pintern->Pointer = NULL;
                }
                hnew = hmem;
714
            }
715 716
            else
                WARN("not freeing memory associated with locked handle\n");
717 718 719 720 721 722 723 724 725 726
         }
      }
   }
   RtlUnlockHeap(GetProcessHeap());
   return hnew;
}


/***********************************************************************
 *           GlobalFree   (KERNEL32.@)
727 728 729
 *
 * Free a global memory object.
 *
730 731 732
 * PARAMS
 *  hmem [I] Handle of the global memory object
 *
733
 * RETURNS
734 735 736 737 738 739
 *  Success: NULL
 *  Failure: The provided handle
 *
 * NOTES
 *   When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
 *
740
 */
741 742
HGLOBAL WINAPI GlobalFree(HGLOBAL hmem)
{
743 744 745 746 747 748 749 750 751
    PGLOBAL32_INTERN pintern;
    HGLOBAL hreturned;

    RtlLockHeap(GetProcessHeap());
    __TRY
    {
        hreturned = 0;
        if(ISPOINTER(hmem)) /* POINTER */
        {
752
            if(!HeapFree(GetProcessHeap(), HEAP_NO_SERIALIZE, hmem))
753 754 755 756
            {
                SetLastError(ERROR_INVALID_HANDLE);
                hreturned = hmem;
            }
757 758 759 760 761 762 763
        }
        else  /* HANDLE */
        {
            pintern=HANDLE_TO_INTERN(hmem);

            if(pintern->Magic==MAGIC_GLOBAL_USED)
            {
764
                pintern->Magic = 0xdead;
765 766 767 768 769 770 771

                /* WIN98 does not make this test. That is you can free a */
                /* block you have not unlocked. Go figure!!              */
                /* if(pintern->LockCount!=0)  */
                /*    SetLastError(ERROR_INVALID_HANDLE);  */

                if(pintern->Pointer)
772
                    if(!HeapFree(GetProcessHeap(), HEAP_NO_SERIALIZE, (char *)(pintern->Pointer)-HGLOBAL_STORAGE))
773
                        hreturned=hmem;
774
                if(!HeapFree(GetProcessHeap(), HEAP_NO_SERIALIZE, pintern))
775 776
                    hreturned=hmem;
            }
777 778 779 780 781 782
            else
            {
                WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
                SetLastError(ERROR_INVALID_HANDLE);
                hreturned = hmem;
            }
783 784
        }
    }
785
    __EXCEPT_PAGE_FAULT
786
    {
787
        ERR("(%p): Page fault occurred ! Caused by bug ?\n", hmem);
788 789 790 791 792 793 794 795 796 797 798
        SetLastError( ERROR_INVALID_PARAMETER );
        hreturned = hmem;
    }
    __ENDTRY
    RtlUnlockHeap(GetProcessHeap());
    return hreturned;
}


/***********************************************************************
 *           GlobalSize   (KERNEL32.@)
799 800 801
 *
 * Get the size of a global memory object.
 *
802 803 804
 * PARAMS
 *  hmem [I] Handle of the global memory object
 *
805
 * RETURNS
806 807 808 809 810 811
 *  Failure: 0
 *  Success: Size in Bytes of the global memory object
 *
 * NOTES
 *   When the handle is invalid, last error is set to ERROR_INVALID_HANDLE
 *
812
 */
813 814
SIZE_T WINAPI GlobalSize(HGLOBAL hmem)
{
815
   SIZE_T               retval;
816 817
   PGLOBAL32_INTERN     pintern;

818 819 820 821 822
   if (!((ULONG_PTR)hmem >> 16))
   {
       SetLastError(ERROR_INVALID_HANDLE);
       return 0;
   }
823 824 825

   if(ISPOINTER(hmem))
   {
826
      retval=HeapSize(GetProcessHeap(), 0, hmem);
827

828
      if (retval == ~0ul) /* It might be a GMEM_MOVEABLE data pointer */
829
      {
830 831
          retval = HeapSize(GetProcessHeap(), 0, (char*)hmem - HGLOBAL_STORAGE);
          if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
832
      }
833 834 835 836 837 838 839 840 841 842 843 844
   }
   else
   {
      RtlLockHeap(GetProcessHeap());
      pintern=HANDLE_TO_INTERN(hmem);

      if(pintern->Magic==MAGIC_GLOBAL_USED)
      {
         if (!pintern->Pointer) /* handle case of GlobalAlloc( ??,0) */
             retval = 0;
         else
         {
845 846
             retval = HeapSize(GetProcessHeap(), 0, (char *)pintern->Pointer - HGLOBAL_STORAGE );
             if (retval != ~0ul) retval -= HGLOBAL_STORAGE;
847 848 849 850
         }
      }
      else
      {
851 852
         WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
         SetLastError(ERROR_INVALID_HANDLE);
853 854 855 856
         retval=0;
      }
      RtlUnlockHeap(GetProcessHeap());
   }
857
   if (retval == ~0ul) retval = 0;
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
   return retval;
}


/***********************************************************************
 *           GlobalWire   (KERNEL32.@)
 */
LPVOID WINAPI GlobalWire(HGLOBAL hmem)
{
   return GlobalLock( hmem );
}


/***********************************************************************
 *           GlobalUnWire   (KERNEL32.@)
 */
BOOL WINAPI GlobalUnWire(HGLOBAL hmem)
{
   return GlobalUnlock( hmem);
}


/***********************************************************************
 *           GlobalFix   (KERNEL32.@)
 */
VOID WINAPI GlobalFix(HGLOBAL hmem)
{
    GlobalLock( hmem );
}


/***********************************************************************
 *           GlobalUnfix   (KERNEL32.@)
 */
VOID WINAPI GlobalUnfix(HGLOBAL hmem)
{
   GlobalUnlock( hmem);
}


/***********************************************************************
 *           GlobalFlags   (KERNEL32.@)
900 901
 *
 * Get information about a global memory object.
902
 *
903 904
 * PARAMS
 *  hmem [I] Handle of the global memory object 
905 906
 *
 * RETURNS
907 908 909
 *  Failure: GMEM_INVALID_HANDLE, when the provided handle is invalid 
 *  Success: Value specifying allocation flags and lock count
 *
910
 */
911 912
UINT WINAPI GlobalFlags(HGLOBAL hmem)
{
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
   DWORD                retval;
   PGLOBAL32_INTERN     pintern;

   if(ISPOINTER(hmem))
   {
      retval=0;
   }
   else
   {
      RtlLockHeap(GetProcessHeap());
      pintern=HANDLE_TO_INTERN(hmem);
      if(pintern->Magic==MAGIC_GLOBAL_USED)
      {
         retval=pintern->LockCount + (pintern->Flags<<8);
         if(pintern->Pointer==0)
            retval|= GMEM_DISCARDED;
      }
      else
      {
932 933 934
         WARN("invalid handle %p (Magic: 0x%04x)\n", hmem, pintern->Magic);
         SetLastError(ERROR_INVALID_HANDLE);
         retval = GMEM_INVALID_HANDLE;
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
      }
      RtlUnlockHeap(GetProcessHeap());
   }
   return retval;
}


/***********************************************************************
 *           GlobalCompact   (KERNEL32.@)
 */
SIZE_T WINAPI GlobalCompact( DWORD minfree )
{
    return 0;  /* GlobalCompact does nothing in Win32 */
}


/***********************************************************************
 *           LocalAlloc   (KERNEL32.@)
953 954 955
 *
 * Allocate a local memory object.
 *
956 957 958
 * RETURNS
 *	Handle: Success
 *	NULL: Failure
959 960 961 962
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
963
 */
964 965 966 967 968 969 970 971 972 973
HLOCAL WINAPI LocalAlloc( UINT flags, SIZE_T size )
{
    /* LocalAlloc allows a 0-size fixed block, but GlobalAlloc doesn't */
    if (!(flags & LMEM_MOVEABLE))
    {
        DWORD heap_flags = (flags & LMEM_ZEROINIT) ? HEAP_ZERO_MEMORY : 0;
        void *ret = HeapAlloc( GetProcessHeap(), heap_flags, size );
        TRACE( "(flags=%04x) returning %p\n",  flags, ret );
        return ret;
    }
974
    return GlobalAlloc( flags, size );
975 976 977 978 979 980 981 982 983 984 985 986 987 988
}


/***********************************************************************
 *           LocalCompact   (KERNEL32.@)
 */
SIZE_T WINAPI LocalCompact( UINT minfree )
{
    return 0;  /* LocalCompact does nothing in Win32 */
}


/***********************************************************************
 *           LocalFlags   (KERNEL32.@)
989 990 991
 *
 * Get information about a local memory object.
 *
992 993 994
 * RETURNS
 *	Value specifying allocation flags and lock count.
 *	LMEM_INVALID_HANDLE: Failure
995 996 997 998
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
999 1000 1001 1002
 */
UINT WINAPI LocalFlags(
              HLOCAL handle /* [in] Handle of memory object */
) {
1003
    return GlobalFlags( handle );
1004 1005 1006 1007 1008
}


/***********************************************************************
 *           LocalFree   (KERNEL32.@)
1009 1010 1011
 *
 * Free a local memory object.
 *
1012 1013 1014
 * RETURNS
 *	NULL: Success
 *	Handle: Failure
1015 1016 1017 1018
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
1019 1020 1021 1022
 */
HLOCAL WINAPI LocalFree(
                HLOCAL handle /* [in] Handle of memory object */
) {
1023
    return GlobalFree( handle );
1024 1025 1026 1027 1028
}


/***********************************************************************
 *           LocalHandle   (KERNEL32.@)
1029 1030 1031
 *
 * Get the handle associated with the pointer to a local memory block.
 *
1032 1033 1034
 * RETURNS
 *	Handle: Success
 *	NULL: Failure
1035 1036 1037 1038
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
1039 1040
 */
HLOCAL WINAPI LocalHandle(
1041
                LPCVOID ptr /* [in] Address of local memory block */
1042
) {
1043
    return GlobalHandle( ptr );
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
}


/***********************************************************************
 *           LocalLock   (KERNEL32.@)
 * Locks a local memory object and returns pointer to the first byte
 * of the memory block.
 *
 * RETURNS
 *	Pointer: Success
 *	NULL: Failure
1055 1056 1057 1058
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
1059 1060 1061 1062
 */
LPVOID WINAPI LocalLock(
              HLOCAL handle /* [in] Address of local memory object */
) {
1063
    return GlobalLock( handle );
1064 1065 1066 1067 1068
}


/***********************************************************************
 *           LocalReAlloc   (KERNEL32.@)
1069 1070 1071
 *
 * Change the size or attributes of a local memory object.
 *
1072 1073 1074
 * RETURNS
 *	Handle: Success
 *	NULL: Failure
1075 1076 1077 1078
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
1079 1080 1081 1082 1083 1084
 */
HLOCAL WINAPI LocalReAlloc(
                HLOCAL handle, /* [in] Handle of memory object */
                SIZE_T size,   /* [in] New size of block */
                UINT flags     /* [in] How to reallocate object */
) {
1085
    return GlobalReAlloc( handle, size, flags );
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
}


/***********************************************************************
 *           LocalShrink   (KERNEL32.@)
 */
SIZE_T WINAPI LocalShrink( HGLOBAL handle, UINT newsize )
{
    return 0;  /* LocalShrink does nothing in Win32 */
}


/***********************************************************************
 *           LocalSize   (KERNEL32.@)
1100 1101 1102
 *
 * Get the size of a local memory object.
 *
1103 1104 1105
 * RETURNS
 *	Size: Success
 *	0: Failure
1106 1107 1108 1109
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
1110 1111 1112 1113
 */
SIZE_T WINAPI LocalSize(
              HLOCAL handle /* [in] Handle of memory object */
) {
1114
    return GlobalSize( handle );
1115 1116 1117 1118 1119
}


/***********************************************************************
 *           LocalUnlock   (KERNEL32.@)
1120 1121 1122
 *
 * Unlock a local memory object.
 *
1123 1124 1125
 * RETURNS
 *	TRUE: Object is still locked
 *	FALSE: Object is unlocked
1126 1127 1128 1129
 *
 * NOTES
 *  Windows memory management does not provide a separate local heap
 *  and global heap.
1130 1131 1132
 */
BOOL WINAPI LocalUnlock(
              HLOCAL handle /* [in] Handle of memory object */
1133 1134 1135 1136 1137 1138 1139 1140
)
{
    if (ISPOINTER( handle ))
    {
        SetLastError( ERROR_NOT_LOCKED );
        return FALSE;
    }

1141
    return GlobalUnlock( handle );
1142 1143 1144
}


1145
/***********************************************************************
1146 1147
 *           GlobalMemoryStatusEx   (KERNEL32.@)
 * A version of GlobalMemoryStatus that can deal with memory over 4GB
1148 1149
 *
 * RETURNS
1150
 *	TRUE
1151
 */
1152 1153 1154
BOOL WINAPI GlobalMemoryStatusEx( LPMEMORYSTATUSEX lpmemex )
{
    static MEMORYSTATUSEX	cached_memstatus;
1155 1156 1157 1158
    static int cache_lastchecked = 0;
    SYSTEM_INFO si;
#ifdef linux
    FILE *f;
1159
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1160
    DWORDLONG total;
1161
#ifdef __APPLE__
1162
    unsigned int val;
1163 1164 1165
#else
    unsigned long val;
#endif
1166
    int mib[2];
1167
    size_t size_sys;
1168 1169 1170
#ifdef HW_MEMSIZE
    uint64_t val64;
#endif
1171 1172 1173
#ifdef VM_SWAPUSAGE
    struct xsw_usage swap;
#endif
1174
#elif defined(sun)
1175
    unsigned long pagesize,maxpages,freepages,swapspace,swapfree;
1176 1177 1178 1179
    struct anoninfo swapinf;
    int rval;
#endif

1180 1181 1182 1183 1184 1185
    if (lpmemex->dwLength != sizeof(*lpmemex))
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return FALSE;
    }

1186
    if (time(NULL)==cache_lastchecked) {
1187
	*lpmemex = cached_memstatus;
1188
	return TRUE;
1189 1190 1191
    }
    cache_lastchecked = time(NULL);

1192 1193 1194 1195 1196
    lpmemex->dwMemoryLoad     = 0;
    lpmemex->ullTotalPhys     = 16*1024*1024;
    lpmemex->ullAvailPhys     = 16*1024*1024;
    lpmemex->ullTotalPageFile = 16*1024*1024;
    lpmemex->ullAvailPageFile = 16*1024*1024;
1197 1198 1199 1200 1201 1202

#ifdef linux
    f = fopen( "/proc/meminfo", "r" );
    if (f)
    {
        char buffer[256];
1203
        unsigned long value;
1204

1205 1206
        lpmemex->ullTotalPhys = lpmemex->ullAvailPhys = 0;
        lpmemex->ullTotalPageFile = lpmemex->ullAvailPageFile = 0;
1207 1208
        while (fgets( buffer, sizeof(buffer), f ))
        {
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
            if (sscanf(buffer, "MemTotal: %lu", &value))
                lpmemex->ullTotalPhys = (ULONG64)value*1024;
            else if (sscanf(buffer, "MemFree: %lu", &value))
                lpmemex->ullAvailPhys = (ULONG64)value*1024;
            else if (sscanf(buffer, "SwapTotal: %lu", &value))
                lpmemex->ullTotalPageFile = (ULONG64)value*1024;
            else if (sscanf(buffer, "SwapFree: %lu", &value))
                lpmemex->ullAvailPageFile = (ULONG64)value*1024;
            else if (sscanf(buffer, "Buffers: %lu", &value))
                lpmemex->ullAvailPhys += (ULONG64)value*1024;
            else if (sscanf(buffer, "Cached: %lu", &value))
                lpmemex->ullAvailPhys += (ULONG64)value*1024;
1221 1222 1223
        }
        fclose( f );
    }
1224
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
1225
    total = 0;
1226
    lpmemex->ullAvailPhys = 0;
1227

1228
    mib[0] = CTL_HW;
1229 1230 1231 1232 1233 1234 1235
#ifdef HW_MEMSIZE
    mib[1] = HW_MEMSIZE;
    size_sys = sizeof(val64);
    if (!sysctl(mib, 2, &val64, &size_sys, NULL, 0) && size_sys == sizeof(val64) && val64)
        total = val64;
#endif

1236 1237
#ifdef HAVE_MACH_MACH_H
    {
1238 1239
        host_name_port_t host = mach_host_self();
        mach_msg_type_number_t count;
1240

1241 1242 1243 1244 1245 1246
#ifdef HOST_VM_INFO64_COUNT
        vm_size_t page_size;
        vm_statistics64_data_t vm_stat;

        count = HOST_VM_INFO64_COUNT;
        if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stat, &count) == KERN_SUCCESS &&
1247
            host_page_size(host, &page_size) == KERN_SUCCESS)
1248 1249 1250 1251 1252 1253 1254 1255 1256
            lpmemex->ullAvailPhys = (vm_stat.free_count + vm_stat.inactive_count) * (DWORDLONG)page_size;
#endif
        if (!total)
        {
            host_basic_info_data_t info;
            count = HOST_BASIC_INFO_COUNT;
            if (host_info(host, HOST_BASIC_INFO, (host_info_t)&info, &count) == KERN_SUCCESS)
                total = info.max_mem;
        }
1257

1258 1259
        mach_port_deallocate(mach_task_self(), host);
    }
1260 1261
#endif

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    if (!total)
    {
        mib[1] = HW_PHYSMEM;
        size_sys = sizeof(val);
        if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val) && val)
            total = val;
    }

    if (total)
        lpmemex->ullTotalPhys = total;

1273 1274 1275 1276 1277 1278 1279 1280 1281
    if (!lpmemex->ullAvailPhys)
    {
        mib[1] = HW_USERMEM;
        size_sys = sizeof(val);
        if (!sysctl(mib, 2, &val, &size_sys, NULL, 0) && size_sys == sizeof(val) && val)
            lpmemex->ullAvailPhys = val;
    }

    if (!lpmemex->ullAvailPhys)
1282 1283 1284 1285
        lpmemex->ullAvailPhys = lpmemex->ullTotalPhys;

    lpmemex->ullTotalPageFile = lpmemex->ullAvailPhys;
    lpmemex->ullAvailPageFile = lpmemex->ullAvailPhys;
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296

#ifdef VM_SWAPUSAGE
    mib[0] = CTL_VM;
    mib[1] = VM_SWAPUSAGE;
    size_sys = sizeof(swap);
    if (!sysctl(mib, 2, &swap, &size_sys, NULL, 0) && size_sys == sizeof(swap))
    {
        lpmemex->ullTotalPageFile = swap.xsu_total;
        lpmemex->ullAvailPageFile = swap.xsu_avail;
    }
#endif
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
#elif defined ( sun )
    pagesize=sysconf(_SC_PAGESIZE);
    maxpages=sysconf(_SC_PHYS_PAGES);
    freepages=sysconf(_SC_AVPHYS_PAGES);
    rval=swapctl(SC_AINFO, &swapinf);
    if(rval >-1)
    {
        swapspace=swapinf.ani_max*pagesize;
        swapfree=swapinf.ani_free*pagesize;
    }else
    {

        WARN("Swap size cannot be determined , assuming equal to physical memory\n");
        swapspace=maxpages*pagesize;
        swapfree=maxpages*pagesize;
    }
    lpmemex->ullTotalPhys=pagesize*maxpages;
    lpmemex->ullAvailPhys = pagesize*freepages;
    lpmemex->ullTotalPageFile = swapspace;
    lpmemex->ullAvailPageFile = swapfree;
1317
#endif
1318

1319 1320 1321 1322 1323 1324
    if (lpmemex->ullTotalPhys)
    {
        lpmemex->dwMemoryLoad = (lpmemex->ullTotalPhys-lpmemex->ullAvailPhys)
                                  / (lpmemex->ullTotalPhys / 100);
    }

1325 1326 1327 1328 1329 1330 1331
    /* Win98 returns only the swapsize in ullTotalPageFile/ullAvailPageFile,
       WinXP returns the size of physical memory + swapsize;
       mimic the behavior of XP.
       Note: Project2k refuses to start if it sees less than 1Mb of free swap.
    */
    lpmemex->ullTotalPageFile += lpmemex->ullTotalPhys;
    lpmemex->ullAvailPageFile += lpmemex->ullAvailPhys;
1332

1333 1334 1335 1336 1337 1338 1339
    /* Titan Quest refuses to run if TotalPageFile <= ullTotalPhys */
    if(lpmemex->ullTotalPageFile == lpmemex->ullTotalPhys)
    {
        lpmemex->ullTotalPhys -= 1;
        lpmemex->ullAvailPhys -= 1;
    }

1340 1341
    /* FIXME: should do something for other systems */
    GetSystemInfo(&si);
1342
    lpmemex->ullTotalVirtual  = (ULONG_PTR)si.lpMaximumApplicationAddress-(ULONG_PTR)si.lpMinimumApplicationAddress;
1343
    /* FIXME: we should track down all the already allocated VM pages and subtract them, for now arbitrarily remove 64KB so that it matches NT */
1344 1345 1346 1347 1348 1349 1350 1351 1352
    lpmemex->ullAvailVirtual  = lpmemex->ullTotalVirtual-64*1024;

    /* MSDN says about AvailExtendedVirtual: Size of unreserved and uncommitted
       memory in the extended portion of the virtual address space of the calling
       process, in bytes.
       However, I don't know what this means, so set it to zero :(
    */
    lpmemex->ullAvailExtendedVirtual = 0;

1353
    cached_memstatus = *lpmemex;
1354

1355
    TRACE_(globalmem)("<-- LPMEMORYSTATUSEX: dwLength %d, dwMemoryLoad %d, ullTotalPhys %s, ullAvailPhys %s,"
1356 1357 1358 1359 1360 1361 1362
          " ullTotalPageFile %s, ullAvailPageFile %s, ullTotalVirtual %s, ullAvailVirtual %s\n",
          lpmemex->dwLength, lpmemex->dwMemoryLoad, wine_dbgstr_longlong(lpmemex->ullTotalPhys),
          wine_dbgstr_longlong(lpmemex->ullAvailPhys), wine_dbgstr_longlong(lpmemex->ullTotalPageFile),
          wine_dbgstr_longlong(lpmemex->ullAvailPageFile), wine_dbgstr_longlong(lpmemex->ullTotalVirtual),
          wine_dbgstr_longlong(lpmemex->ullAvailVirtual) );

    return TRUE;
1363 1364 1365
}

/***********************************************************************
1366 1367 1368
 *           GlobalMemoryStatus   (KERNEL32.@)
 * Provides information about the status of the memory, so apps can tell
 * roughly how much they are able to allocate
1369 1370
 *
 * RETURNS
1371
 *      None
1372
 */
1373
VOID WINAPI GlobalMemoryStatus( LPMEMORYSTATUS lpBuffer )
1374
{
1375
    MEMORYSTATUSEX memstatus;
1376
    OSVERSIONINFOW osver;
1377
    IMAGE_NT_HEADERS *nt = RtlImageNtHeader( GetModuleHandleW(0) );
1378 1379 1380 1381

    /* Because GlobalMemoryStatus is identical to GlobalMemoryStatusEX save
       for one extra field in the struct, and the lack of a bug, we simply
       call GlobalMemoryStatusEx and copy the values across. */
1382
    memstatus.dwLength = sizeof(memstatus);
1383 1384 1385 1386 1387 1388 1389 1390
    GlobalMemoryStatusEx(&memstatus);

    lpBuffer->dwLength = sizeof(*lpBuffer);
    lpBuffer->dwMemoryLoad = memstatus.dwMemoryLoad;

    /* Windows 2000 and later report -1 when values are greater than 4 Gb.
     * NT reports values modulo 4 Gb.
     */
1391 1392 1393

    osver.dwOSVersionInfoSize = sizeof(osver);
    GetVersionExW(&osver);
1394

1395
    if ( osver.dwMajorVersion >= 5 || osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
1396
    {
1397 1398
        lpBuffer->dwTotalPhys = min( memstatus.ullTotalPhys, MAXDWORD );
        lpBuffer->dwAvailPhys = min( memstatus.ullAvailPhys, MAXDWORD );
1399 1400
        /* Limit value for apps that do not expect so much memory. Remove last 512 kb to make Sacrifice demo happy. */
        lpBuffer->dwTotalPageFile = min( memstatus.ullTotalPageFile, 0xfff7ffff );
1401 1402 1403 1404
        lpBuffer->dwAvailPageFile = min( memstatus.ullAvailPageFile, MAXDWORD );
        lpBuffer->dwTotalVirtual = min( memstatus.ullTotalVirtual, MAXDWORD );
        lpBuffer->dwAvailVirtual = min( memstatus.ullAvailVirtual, MAXDWORD );

1405
    }
1406
    else /* duplicate NT bug */
1407
    {
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
        lpBuffer->dwTotalPhys = memstatus.ullTotalPhys;
        lpBuffer->dwAvailPhys = memstatus.ullAvailPhys;
        lpBuffer->dwTotalPageFile = memstatus.ullTotalPageFile;
        lpBuffer->dwAvailPageFile = memstatus.ullAvailPageFile;
        lpBuffer->dwTotalVirtual = memstatus.ullTotalVirtual;
        lpBuffer->dwAvailVirtual = memstatus.ullAvailVirtual;
    }

    /* values are limited to 2Gb unless the app has the IMAGE_FILE_LARGE_ADDRESS_AWARE flag */
    /* page file sizes are not limited (Adobe Illustrator 8 depends on this) */
    if (!(nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE))
    {
        if (lpBuffer->dwTotalPhys > MAXLONG) lpBuffer->dwTotalPhys = MAXLONG;
        if (lpBuffer->dwAvailPhys > MAXLONG) lpBuffer->dwAvailPhys = MAXLONG;
        if (lpBuffer->dwTotalVirtual > MAXLONG) lpBuffer->dwTotalVirtual = MAXLONG;
        if (lpBuffer->dwAvailVirtual > MAXLONG) lpBuffer->dwAvailVirtual = MAXLONG;
1424 1425 1426 1427 1428
    }

    /* work around for broken photoshop 4 installer */
    if ( lpBuffer->dwAvailPhys +  lpBuffer->dwAvailPageFile >= 2U*1024*1024*1024)
         lpBuffer->dwAvailPageFile = 2U*1024*1024*1024 -  lpBuffer->dwAvailPhys - 1;
1429 1430

    /* limit page file size for really old binaries */
1431 1432
    if (nt->OptionalHeader.MajorSubsystemVersion < 4 ||
        nt->OptionalHeader.MajorOperatingSystemVersion < 4)
1433 1434 1435 1436 1437
    {
        if (lpBuffer->dwTotalPageFile > MAXLONG) lpBuffer->dwTotalPageFile = MAXLONG;
        if (lpBuffer->dwAvailPageFile > MAXLONG) lpBuffer->dwAvailPageFile = MAXLONG;
    }

1438
    TRACE_(globalmem)("Length %u, MemoryLoad %u, TotalPhys %lx, AvailPhys %lx,"
1439 1440 1441 1442
          " TotalPageFile %lx, AvailPageFile %lx, TotalVirtual %lx, AvailVirtual %lx\n",
          lpBuffer->dwLength, lpBuffer->dwMemoryLoad, lpBuffer->dwTotalPhys,
          lpBuffer->dwAvailPhys, lpBuffer->dwTotalPageFile, lpBuffer->dwAvailPageFile,
          lpBuffer->dwTotalVirtual, lpBuffer->dwAvailVirtual );
1443
}
1444

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
/***********************************************************************
 *           GetPhysicallyInstalledSystemMemory   (KERNEL32.@)
 */
BOOL WINAPI GetPhysicallyInstalledSystemMemory(ULONGLONG *total_memory)
{
    MEMORYSTATUSEX memstatus;

    FIXME("stub: %p\n", total_memory);

    if (!total_memory)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    memstatus.dwLength = sizeof(memstatus);
    GlobalMemoryStatusEx(&memstatus);
    *total_memory = memstatus.ullTotalPhys / 1024;
    return TRUE;
}

1466 1467 1468 1469 1470 1471
BOOL WINAPI GetSystemFileCacheSize(PSIZE_T mincache, PSIZE_T maxcache, PDWORD flags)
{
    FIXME("stub: %p %p %p\n", mincache, maxcache, flags);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}
1472 1473 1474 1475 1476 1477 1478

BOOL WINAPI SetSystemFileCacheSize(SIZE_T mincache, SIZE_T maxcache, DWORD flags)
{
    FIXME("stub: %ld %ld %d\n", mincache, maxcache, flags);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}
1479 1480 1481 1482 1483 1484 1485

BOOL WINAPI AllocateUserPhysicalPages(HANDLE process, ULONG_PTR *pages, ULONG_PTR *userarray)
{
    FIXME("stub: %p %p %p\n",process, pages, userarray);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}
1486 1487 1488 1489 1490 1491 1492 1493

BOOL WINAPI FreeUserPhysicalPages(HANDLE process, ULONG_PTR *pages, ULONG_PTR *userarray)
{
    FIXME("stub: %p %p %p\n", process, pages, userarray);
    *pages = 0;
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}