Minor improvement in section "Pages" of the usere manual
[emacs.git] / src / w32heap.c
bloba3f87bfc7e636bb88f82ed0f296f6554fbe8ae1d
1 /* Heap management routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994, 2001-2018 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
20 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 Heavily modified by Fabrice Popineau (fabrice.popineau@gmail.com) 28-02-2014
28 Memory allocation scheme for w32/w64:
30 - Buffers are mmap'ed using a very simple emulation of mmap/munmap
31 - During the temacs phase:
32 * we use a private heap declared to be stored into the `dumped_data'
33 * unfortunately, this heap cannot be made growable, so the size of
34 blocks it can allocate is limited to (0x80000 - pagesize)
35 * the blocks that are larger than this are allocated from the end
36 of the `dumped_data' array; there are not so many of them.
37 We use a very simple first-fit scheme to reuse those blocks.
38 * we check that the private heap does not cross the area used
39 by the bigger chunks.
40 - During the emacs phase:
41 * we create a private heap for new memory blocks
42 * we make sure that we never free a block that has been dumped.
43 Freeing a dumped block could work in principle, but may prove
44 unreliable if we distribute binaries of emacs.exe: MS does not
45 guarantee that the heap data structures are the same across all
46 versions of their OS, even though the API is available since XP. */
48 #include <config.h>
49 #include <stdio.h>
50 #include <errno.h>
52 #include <sys/mman.h>
53 #include <sys/resource.h>
54 #include "w32common.h"
55 #include "w32heap.h"
56 #include "lisp.h"
57 #include "w32.h" /* for FD_SETSIZE */
59 /* We chose to leave those declarations here. They are used only in
60 this file. The RtlCreateHeap is available since XP. It is located
61 in ntdll.dll and is available with the DDK. People often
62 complained that HeapCreate doesn't offer the ability to create a
63 heap at a given place, which we need here, and which RtlCreateHeap
64 provides. We reproduce here the definitions available with the
65 DDK. */
67 typedef PVOID (WINAPI * RtlCreateHeap_Proc) (
68 /* _In_ */ ULONG Flags,
69 /* _In_opt_ */ PVOID HeapBase,
70 /* _In_opt_ */ SIZE_T ReserveSize,
71 /* _In_opt_ */ SIZE_T CommitSize,
72 /* _In_opt_ */ PVOID Lock,
73 /* _In_opt_ */ PVOID Parameters
76 typedef LONG NTSTATUS;
78 typedef NTSTATUS (NTAPI *PRTL_HEAP_COMMIT_ROUTINE) (
79 IN PVOID Base,
80 IN OUT PVOID *CommitAddress,
81 IN OUT PSIZE_T CommitSize
84 typedef struct _RTL_HEAP_PARAMETERS {
85 ULONG Length;
86 SIZE_T SegmentReserve;
87 SIZE_T SegmentCommit;
88 SIZE_T DeCommitFreeBlockThreshold;
89 SIZE_T DeCommitTotalFreeThreshold;
90 SIZE_T MaximumAllocationSize;
91 SIZE_T VirtualMemoryThreshold;
92 SIZE_T InitialCommit;
93 SIZE_T InitialReserve;
94 PRTL_HEAP_COMMIT_ROUTINE CommitRoutine;
95 SIZE_T Reserved[ 2 ];
96 } RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS;
98 /* We reserve space for dumping emacs lisp byte-code inside a static
99 array. By storing it in an array, the generic mechanism in
100 unexecw32.c will be able to dump it without the need to add a
101 special segment to the executable. In order to be able to do this
102 without losing too much space, we need to create a Windows heap at
103 the specific address of the static array. The RtlCreateHeap
104 available inside the NT kernel since XP will do this. It allows the
105 creation of a non-growable heap at a specific address. So before
106 dumping, we create a non-growable heap at the address of the
107 dumped_data[] array. After dumping, we reuse memory allocated
108 there without being able to free it (but most of it is not meant to
109 be freed anyway), and we use a new private heap for all new
110 allocations. */
112 /* FIXME: Most of the space reserved for dumped_data[] is only used by
113 the 1st bootstrap-emacs.exe built while bootstrapping. Once the
114 preloaded Lisp files are byte-compiled, the next loadup uses less
115 than half of the size stated below. It would be nice to find a way
116 to build only the first bootstrap-emacs.exe with the large size,
117 and reset that to a lower value afterwards. */
118 #if defined _WIN64 || defined WIDE_EMACS_INT
119 # define DUMPED_HEAP_SIZE (22*1024*1024)
120 #else
121 # define DUMPED_HEAP_SIZE (13*1024*1024)
122 #endif
124 static unsigned char dumped_data[DUMPED_HEAP_SIZE];
126 /* Info for keeping track of our dynamic heap used after dumping. */
127 unsigned char *data_region_base = NULL;
128 unsigned char *data_region_end = NULL;
129 static DWORD_PTR committed = 0;
131 /* The maximum block size that can be handled by a non-growable w32
132 heap is limited by the MaxBlockSize value below.
134 This point deserves an explanation.
136 The W32 heap allocator can be used for a growable heap or a
137 non-growable one.
139 A growable heap is not compatible with a fixed base address for the
140 heap. Only a non-growable one is. One drawback of non-growable
141 heaps is that they can hold only objects smaller than a certain
142 size (the one defined below). Most of the larger blocks are GC'ed
143 before dumping. In any case, and to be safe, we implement a simple
144 first-fit allocation algorithm starting at the end of the
145 dumped_data[] array as depicted below:
147 ----------------------------------------------
148 | | | |
149 | Private heap |-> <-| Big chunks |
150 | | | |
151 ----------------------------------------------
152 ^ ^ ^
153 dumped_data dumped_data bc_limit
154 + committed
158 /* Info for managing our preload heap, which is essentially a fixed size
159 data area in the executable. */
160 #define PAGE_SIZE 0x1000
161 #define MaxBlockSize (0x80000 - PAGE_SIZE)
163 #define MAX_BLOCKS 0x40
165 static struct
167 unsigned char *address;
168 size_t size;
169 DWORD occupied;
170 } blocks[MAX_BLOCKS];
172 static DWORD blocks_number = 0;
173 static unsigned char *bc_limit;
175 /* Handle for the private heap:
176 - inside the dumped_data[] array before dump,
177 - outside of it after dump.
179 HANDLE heap = NULL;
181 /* We redirect the standard allocation functions. */
182 malloc_fn the_malloc_fn;
183 realloc_fn the_realloc_fn;
184 free_fn the_free_fn;
186 /* It doesn't seem to be useful to allocate from a file mapping.
187 It would be if the memory was shared.
188 http://stackoverflow.com/questions/307060/what-is-the-purpose-of-allocating-pages-in-the-pagefile-with-createfilemapping */
190 /* This is the function to commit memory when the heap allocator
191 claims for new memory. Before dumping, we allocate space
192 from the fixed size dumped_data[] array.
194 static NTSTATUS NTAPI
195 dumped_data_commit (PVOID Base, PVOID *CommitAddress, PSIZE_T CommitSize)
197 /* This is used before dumping.
199 The private heap is stored at dumped_data[] address.
200 We commit contiguous areas of the dumped_data array
201 as requests arrive. */
202 *CommitAddress = data_region_base + committed;
203 committed += *CommitSize;
204 /* Check that the private heap area does not overlap the big chunks area. */
205 if (((unsigned char *)(*CommitAddress)) + *CommitSize >= bc_limit)
207 fprintf (stderr,
208 "dumped_data_commit: memory exhausted.\nEnlarge dumped_data[]!\n");
209 exit (-1);
211 return 0;
214 /* Heap creation. */
216 /* We want to turn on Low Fragmentation Heap for XP and older systems.
217 MinGW32 lacks those definitions. */
218 #ifndef MINGW_W64
219 typedef enum _HEAP_INFORMATION_CLASS {
220 HeapCompatibilityInformation
221 } HEAP_INFORMATION_CLASS;
223 typedef WINBASEAPI BOOL (WINAPI * HeapSetInformation_Proc)(HANDLE,HEAP_INFORMATION_CLASS,PVOID,SIZE_T);
224 #endif
226 void
227 init_heap (void)
229 if (using_dynamic_heap)
231 #ifndef MINGW_W64
232 unsigned long enable_lfh = 2;
233 #endif
235 /* After dumping, use a new private heap. We explicitly enable
236 the low fragmentation heap (LFH) here, for the sake of pre
237 Vista versions. Note: this will harmlessly fail on Vista and
238 later, where the low-fragmentation heap is enabled by
239 default. It will also fail on pre-Vista versions when Emacs
240 is run under a debugger; set _NO_DEBUG_HEAP=1 in the
241 environment before starting GDB to get low fragmentation heap
242 on XP and older systems, for the price of losing "certain
243 heap debug options"; for the details see
244 http://msdn.microsoft.com/en-us/library/windows/desktop/aa366705%28v=vs.85%29.aspx. */
245 data_region_end = data_region_base;
247 /* Create the private heap. */
248 heap = HeapCreate (0, 0, 0);
250 #ifndef MINGW_W64
251 /* Set the low-fragmentation heap for OS before Vista. */
252 HMODULE hm_kernel32dll = LoadLibrary ("kernel32.dll");
253 HeapSetInformation_Proc s_pfn_Heap_Set_Information = (HeapSetInformation_Proc) GetProcAddress (hm_kernel32dll, "HeapSetInformation");
254 if (s_pfn_Heap_Set_Information != NULL)
256 if (s_pfn_Heap_Set_Information ((PVOID) heap,
257 HeapCompatibilityInformation,
258 &enable_lfh, sizeof(enable_lfh)) == 0)
259 DebPrint (("Enabling Low Fragmentation Heap failed: error %ld\n",
260 GetLastError ()));
262 #endif
264 if (os_subtype == OS_9X)
266 the_malloc_fn = malloc_after_dump_9x;
267 the_realloc_fn = realloc_after_dump_9x;
268 the_free_fn = free_after_dump_9x;
270 else
272 the_malloc_fn = malloc_after_dump;
273 the_realloc_fn = realloc_after_dump;
274 the_free_fn = free_after_dump;
277 else
279 /* Find the RtlCreateHeap function. Headers for this function
280 are provided with the w32 DDK, but the function is available
281 in ntdll.dll since XP. */
282 HMODULE hm_ntdll = LoadLibrary ("ntdll.dll");
283 RtlCreateHeap_Proc s_pfn_Rtl_Create_Heap
284 = (RtlCreateHeap_Proc) GetProcAddress (hm_ntdll, "RtlCreateHeap");
285 /* Specific parameters for the private heap. */
286 RTL_HEAP_PARAMETERS params;
287 ZeroMemory (&params, sizeof(params));
288 params.Length = sizeof(RTL_HEAP_PARAMETERS);
290 data_region_base = (unsigned char *)ROUND_UP (dumped_data, 0x1000);
291 data_region_end = bc_limit = dumped_data + DUMPED_HEAP_SIZE;
293 params.InitialCommit = committed = 0x1000;
294 params.InitialReserve = sizeof(dumped_data);
295 /* Use our own routine to commit memory from the dumped_data
296 array. */
297 params.CommitRoutine = &dumped_data_commit;
299 /* Create the private heap. */
300 if (s_pfn_Rtl_Create_Heap == NULL)
302 fprintf (stderr, "Cannot build Emacs without RtlCreateHeap being available; exiting.\n");
303 exit (-1);
305 heap = s_pfn_Rtl_Create_Heap (0, data_region_base, 0, 0, NULL, &params);
307 if (os_subtype == OS_9X)
309 fprintf (stderr, "Cannot dump Emacs on Windows 9X; exiting.\n");
310 exit (-1);
312 else
314 the_malloc_fn = malloc_before_dump;
315 the_realloc_fn = realloc_before_dump;
316 the_free_fn = free_before_dump;
320 /* Update system version information to match current system. */
321 cache_system_info ();
325 /* malloc, realloc, free. */
327 #undef malloc
328 #undef realloc
329 #undef free
331 /* FREEABLE_P checks if the block can be safely freed. */
332 #define FREEABLE_P(addr) \
333 ((DWORD_PTR)(unsigned char *)(addr) > 0 \
334 && ((unsigned char *)(addr) < dumped_data \
335 || (unsigned char *)(addr) >= dumped_data + DUMPED_HEAP_SIZE))
337 void *
338 malloc_after_dump (size_t size)
340 /* Use the new private heap. */
341 void *p = HeapAlloc (heap, 0, size);
343 /* After dump, keep track of the "brk value" for sbrk(0). */
344 if (p)
346 unsigned char *new_brk = (unsigned char *)p + size;
348 if (new_brk > data_region_end)
349 data_region_end = new_brk;
351 else
352 errno = ENOMEM;
353 return p;
356 void *
357 malloc_before_dump (size_t size)
359 void *p;
361 /* Before dumping. The private heap can handle only requests for
362 less than MaxBlockSize. */
363 if (size < MaxBlockSize)
365 /* Use the private heap if possible. */
366 p = HeapAlloc (heap, 0, size);
367 if (!p)
368 errno = ENOMEM;
370 else
372 /* Find the first big chunk that can hold the requested size. */
373 int i = 0;
375 for (i = 0; i < blocks_number; i++)
377 if (blocks[i].occupied == 0 && blocks[i].size >= size)
378 break;
380 if (i < blocks_number)
382 /* If found, use it. */
383 p = blocks[i].address;
384 blocks[i].occupied = TRUE;
386 else
388 /* Allocate a new big chunk from the end of the dumped_data
389 array. */
390 if (blocks_number >= MAX_BLOCKS)
392 fprintf (stderr,
393 "malloc_before_dump: no more big chunks available.\nEnlarge MAX_BLOCKS!\n");
394 exit (-1);
396 bc_limit -= size;
397 bc_limit = (unsigned char *)ROUND_DOWN (bc_limit, 0x10);
398 p = bc_limit;
399 blocks[blocks_number].address = p;
400 blocks[blocks_number].size = size;
401 blocks[blocks_number].occupied = TRUE;
402 blocks_number++;
403 /* Check that areas do not overlap. */
404 if (bc_limit < dumped_data + committed)
406 fprintf (stderr,
407 "malloc_before_dump: memory exhausted.\nEnlarge dumped_data[]!\n");
408 exit (-1);
412 return p;
415 /* Re-allocate the previously allocated block in ptr, making the new
416 block SIZE bytes long. */
417 void *
418 realloc_after_dump (void *ptr, size_t size)
420 void *p;
422 /* After dumping. */
423 if (FREEABLE_P (ptr))
425 /* Reallocate the block since it lies in the new heap. */
426 p = HeapReAlloc (heap, 0, ptr, size);
427 if (!p)
428 errno = ENOMEM;
430 else
432 /* If the block lies in the dumped data, do not free it. Only
433 allocate a new one. */
434 p = HeapAlloc (heap, 0, size);
435 if (!p)
436 errno = ENOMEM;
437 else if (ptr)
438 CopyMemory (p, ptr, size);
440 /* After dump, keep track of the "brk value" for sbrk(0). */
441 if (p)
443 unsigned char *new_brk = (unsigned char *)p + size;
445 if (new_brk > data_region_end)
446 data_region_end = new_brk;
448 return p;
451 void *
452 realloc_before_dump (void *ptr, size_t size)
454 void *p;
456 /* Before dumping. */
457 if (dumped_data < (unsigned char *)ptr
458 && (unsigned char *)ptr < bc_limit && size <= MaxBlockSize)
460 p = HeapReAlloc (heap, 0, ptr, size);
461 if (!p)
462 errno = ENOMEM;
464 else
466 /* In this case, either the new block is too large for the heap,
467 or the old block was already too large. In both cases,
468 malloc_before_dump() and free_before_dump() will take care of
469 reallocation. */
470 p = malloc_before_dump (size);
471 /* If SIZE is below MaxBlockSize, malloc_before_dump will try to
472 allocate it in the fixed heap. If that fails, we could have
473 kept the block in its original place, above bc_limit, instead
474 of failing the call as below. But this doesn't seem to be
475 worth the added complexity, as loadup allocates only a very
476 small number of large blocks, and never reallocates them. */
477 if (p && ptr)
479 CopyMemory (p, ptr, size);
480 free_before_dump (ptr);
483 return p;
486 /* Free a block allocated by `malloc', `realloc' or `calloc'. */
487 void
488 free_after_dump (void *ptr)
490 /* After dumping. */
491 if (FREEABLE_P (ptr))
493 /* Free the block if it is in the new private heap. */
494 HeapFree (heap, 0, ptr);
498 void
499 free_before_dump (void *ptr)
501 if (!ptr)
502 return;
504 /* Before dumping. */
505 if (dumped_data < (unsigned char *)ptr
506 && (unsigned char *)ptr < bc_limit)
508 /* Free the block if it is allocated in the private heap. */
509 HeapFree (heap, 0, ptr);
511 else
513 /* Look for the big chunk. */
514 int i;
516 for (i = 0; i < blocks_number; i++)
518 if (blocks[i].address == ptr)
520 /* Reset block occupation if found. */
521 blocks[i].occupied = 0;
522 break;
524 /* What if the block is not found? We should trigger an
525 error here. */
526 eassert (i < blocks_number);
531 /* On Windows 9X, HeapAlloc may return pointers that are not aligned
532 on 8-byte boundary, alignment which is required by the Lisp memory
533 management. To circumvent this problem, manually enforce alignment
534 on Windows 9X. */
536 void *
537 malloc_after_dump_9x (size_t size)
539 void *p = malloc_after_dump (size + 8);
540 void *pa;
541 if (p == NULL)
542 return p;
543 pa = (void*)(((intptr_t)p + 8) & ~7);
544 *((void**)pa-1) = p;
545 return pa;
548 void *
549 realloc_after_dump_9x (void *ptr, size_t size)
551 if (FREEABLE_P (ptr))
553 void *po = *((void**)ptr-1);
554 void *p;
555 void *pa;
556 p = realloc_after_dump (po, size + 8);
557 if (p == NULL)
558 return p;
559 pa = (void*)(((intptr_t)p + 8) & ~7);
560 if (ptr != NULL &&
561 (char*)pa - (char*)p != (char*)ptr - (char*)po)
563 /* Handle the case where alignment in pre-realloc and
564 post-realloc blocks does not match. */
565 MoveMemory (pa, (void*)((char*)p + ((char*)ptr - (char*)po)), size);
567 *((void**)pa-1) = p;
568 return pa;
570 else
572 /* Non-freeable pointers have no alignment-enforcing header
573 (since dumping is not allowed on Windows 9X). */
574 void* p = malloc_after_dump_9x (size);
575 if (p != NULL)
576 CopyMemory (p, ptr, size);
577 return p;
581 void
582 free_after_dump_9x (void *ptr)
584 if (FREEABLE_P (ptr))
586 free_after_dump (*((void**)ptr-1));
590 #ifdef ENABLE_CHECKING
591 void
592 report_temacs_memory_usage (void)
594 DWORD blocks_used = 0;
595 size_t large_mem_used = 0;
596 int i;
598 for (i = 0; i < blocks_number; i++)
599 if (blocks[i].occupied)
601 blocks_used++;
602 large_mem_used += blocks[i].size;
605 /* Emulate 'message', which writes to stderr in non-interactive
606 sessions. */
607 fprintf (stderr,
608 "Dump memory usage: Heap: %" PRIu64 " Large blocks(%lu/%lu): %" PRIu64 "/%" PRIu64 "\n",
609 (unsigned long long)committed, blocks_used, blocks_number,
610 (unsigned long long)large_mem_used,
611 (unsigned long long)(dumped_data + DUMPED_HEAP_SIZE - bc_limit));
613 #endif
615 /* Emulate getpagesize. */
617 getpagesize (void)
619 return sysinfo_cache.dwPageSize;
622 void *
623 sbrk (ptrdiff_t increment)
625 /* data_region_end is the address beyond the last allocated byte.
626 The sbrk() function is not emulated at all, except for a 0 value
627 of its parameter. This is needed by the Emacs Lisp function
628 `memory-limit'. */
629 eassert (increment == 0);
630 return data_region_end;
635 /* MMAP allocation for buffers. */
637 #define MAX_BUFFER_SIZE (512 * 1024 * 1024)
639 void *
640 mmap_alloc (void **var, size_t nbytes)
642 void *p = NULL;
644 /* We implement amortized allocation. We start by reserving twice
645 the size requested and commit only the size requested. Then
646 realloc could proceed and use the reserved pages, reallocating
647 only if needed. Buffer shrink would happen only so that we stay
648 in the 2x range. This is a big win when visiting compressed
649 files, where the final size of the buffer is not known in
650 advance, and the buffer is enlarged several times as the data is
651 decompressed on the fly. */
652 if (nbytes < MAX_BUFFER_SIZE)
653 p = VirtualAlloc (NULL, ROUND_UP (nbytes * 2, get_allocation_unit ()),
654 MEM_RESERVE, PAGE_READWRITE);
656 /* If it fails, or if the request is above 512MB, try with the
657 requested size. */
658 if (p == NULL)
659 p = VirtualAlloc (NULL, ROUND_UP (nbytes, get_allocation_unit ()),
660 MEM_RESERVE, PAGE_READWRITE);
662 if (p != NULL)
664 /* Now, commit pages for NBYTES. */
665 *var = VirtualAlloc (p, nbytes, MEM_COMMIT, PAGE_READWRITE);
666 if (*var == NULL)
667 p = *var;
670 if (!p)
672 DWORD e = GetLastError ();
674 if (e == ERROR_NOT_ENOUGH_MEMORY)
675 errno = ENOMEM;
676 else
678 DebPrint (("mmap_alloc: error %ld\n", e));
679 errno = EINVAL;
683 return *var = p;
686 void
687 mmap_free (void **var)
689 if (*var)
691 if (VirtualFree (*var, 0, MEM_RELEASE) == 0)
692 DebPrint (("mmap_free: error %ld\n", GetLastError ()));
693 *var = NULL;
697 void *
698 mmap_realloc (void **var, size_t nbytes)
700 MEMORY_BASIC_INFORMATION memInfo, m2;
701 void *old_ptr;
703 if (*var == NULL)
704 return mmap_alloc (var, nbytes);
706 /* This case happens in init_buffer(). */
707 if (nbytes == 0)
709 mmap_free (var);
710 return mmap_alloc (var, nbytes);
713 memset (&memInfo, 0, sizeof (memInfo));
714 if (VirtualQuery (*var, &memInfo, sizeof (memInfo)) == 0)
715 DebPrint (("mmap_realloc: VirtualQuery error = %ld\n", GetLastError ()));
717 /* We need to enlarge the block. */
718 if (memInfo.RegionSize < nbytes)
720 memset (&m2, 0, sizeof (m2));
721 if (VirtualQuery ((char *)*var + memInfo.RegionSize, &m2, sizeof(m2)) == 0)
722 DebPrint (("mmap_realloc: VirtualQuery error = %ld\n",
723 GetLastError ()));
724 /* If there is enough room in the current reserved area, then
725 commit more pages as needed. */
726 if (m2.State == MEM_RESERVE
727 && m2.AllocationBase == memInfo.AllocationBase
728 && nbytes <= memInfo.RegionSize + m2.RegionSize)
730 void *p;
732 p = VirtualAlloc (*var, nbytes, MEM_COMMIT, PAGE_READWRITE);
733 if (!p /* && GetLastError() != ERROR_NOT_ENOUGH_MEMORY */)
735 DebPrint (("realloc enlarge: VirtualAlloc (%p + %I64x, %I64x) error %ld\n",
736 *var, (uint64_t)memInfo.RegionSize,
737 (uint64_t)(nbytes - memInfo.RegionSize),
738 GetLastError ()));
739 DebPrint (("next region: %p %p %I64x %x\n", m2.BaseAddress,
740 m2.AllocationBase, (uint64_t)m2.RegionSize,
741 m2.AllocationProtect));
743 else
744 return *var;
746 /* Else we must actually enlarge the block by allocating a new
747 one and copying previous contents from the old to the new one. */
748 old_ptr = *var;
750 if (mmap_alloc (var, nbytes))
752 CopyMemory (*var, old_ptr, memInfo.RegionSize);
753 mmap_free (&old_ptr);
754 return *var;
756 else
758 /* We failed to reallocate the buffer. */
759 *var = old_ptr;
760 return NULL;
764 /* If we are shrinking by more than one page... */
765 if (memInfo.RegionSize > nbytes + getpagesize())
767 /* If we are shrinking a lot... */
768 if ((memInfo.RegionSize / 2) > nbytes)
770 /* Let's give some memory back to the system and release
771 some pages. */
772 old_ptr = *var;
774 if (mmap_alloc (var, nbytes))
776 CopyMemory (*var, old_ptr, nbytes);
777 mmap_free (&old_ptr);
778 return *var;
780 else
782 /* In case we fail to shrink, try to go on with the old block.
783 But that means there is a lot of memory pressure.
784 We could also decommit pages. */
785 *var = old_ptr;
786 return *var;
790 /* We still can decommit pages. */
791 if (VirtualFree ((char *)*var + nbytes + get_page_size(),
792 memInfo.RegionSize - nbytes - get_page_size(),
793 MEM_DECOMMIT) == 0)
794 DebPrint (("mmap_realloc: VirtualFree error %ld\n", GetLastError ()));
795 return *var;
798 /* Not enlarging, not shrinking by more than one page. */
799 return *var;
803 /* Emulation of getrlimit and setrlimit. */
806 getrlimit (rlimit_resource_t rltype, struct rlimit *rlp)
808 int retval = -1;
810 switch (rltype)
812 case RLIMIT_STACK:
814 MEMORY_BASIC_INFORMATION m;
815 /* Implementation note: Posix says that RLIMIT_STACK returns
816 information about the stack size for the main thread. The
817 implementation below returns the stack size for the calling
818 thread, so it's more like pthread_attr_getstacksize. But
819 Emacs clearly wants the latter, given how it uses the
820 results, so the implementation below is more future-proof,
821 if what's now the main thread will become some other thread
822 at some future point. */
823 if (!VirtualQuery ((LPCVOID) &m, &m, sizeof m))
824 errno = EPERM;
825 else
827 rlp->rlim_cur = (DWORD_PTR) &m - (DWORD_PTR) m.AllocationBase;
828 rlp->rlim_max =
829 (DWORD_PTR) m.BaseAddress + m.RegionSize
830 - (DWORD_PTR) m.AllocationBase;
832 /* The last page is the guard page, so subtract that. */
833 rlp->rlim_cur -= getpagesize ();
834 rlp->rlim_max -= getpagesize ();
835 retval = 0;
838 break;
839 case RLIMIT_NOFILE:
840 /* Implementation note: The real value is returned by
841 _getmaxstdio. But our FD_SETSIZE is smaller, to cater to
842 Windows 9X, and process.c includes some logic that's based on
843 the assumption that the handle resource is inherited to child
844 processes. We want to avoid that logic, so we tell process.c
845 our current limit is already equal to FD_SETSIZE. */
846 rlp->rlim_cur = FD_SETSIZE;
847 rlp->rlim_max = 2048; /* see _setmaxstdio documentation */
848 retval = 0;
849 break;
850 default:
851 /* Note: we could return meaningful results for other RLIMIT_*
852 requests, but Emacs doesn't currently need that, so we just
853 punt for them. */
854 errno = ENOSYS;
855 break;
857 return retval;
861 setrlimit (rlimit_resource_t rltype, const struct rlimit *rlp)
863 switch (rltype)
865 case RLIMIT_STACK:
866 case RLIMIT_NOFILE:
867 /* We cannot modfy these limits, so we always fail. */
868 errno = EPERM;
869 break;
870 default:
871 errno = ENOSYS;
872 break;
874 return -1;