Use new function overflow_error in a few places
[emacs.git] / src / w32heap.c
blob8c946825067774d79bd4c3ce659a6af20a72c2f3
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 (23*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 =
254 (HeapSetInformation_Proc) get_proc_addr (hm_kernel32dll,
255 "HeapSetInformation");
256 if (s_pfn_Heap_Set_Information != NULL)
258 if (s_pfn_Heap_Set_Information ((PVOID) heap,
259 HeapCompatibilityInformation,
260 &enable_lfh, sizeof(enable_lfh)) == 0)
261 DebPrint (("Enabling Low Fragmentation Heap failed: error %ld\n",
262 GetLastError ()));
264 #endif
266 if (os_subtype == OS_9X)
268 the_malloc_fn = malloc_after_dump_9x;
269 the_realloc_fn = realloc_after_dump_9x;
270 the_free_fn = free_after_dump_9x;
272 else
274 the_malloc_fn = malloc_after_dump;
275 the_realloc_fn = realloc_after_dump;
276 the_free_fn = free_after_dump;
279 else
281 /* Find the RtlCreateHeap function. Headers for this function
282 are provided with the w32 DDK, but the function is available
283 in ntdll.dll since XP. */
284 HMODULE hm_ntdll = LoadLibrary ("ntdll.dll");
285 RtlCreateHeap_Proc s_pfn_Rtl_Create_Heap
286 = (RtlCreateHeap_Proc) get_proc_addr (hm_ntdll, "RtlCreateHeap");
287 /* Specific parameters for the private heap. */
288 RTL_HEAP_PARAMETERS params;
289 ZeroMemory (&params, sizeof(params));
290 params.Length = sizeof(RTL_HEAP_PARAMETERS);
292 data_region_base = (unsigned char *)ROUND_UP (dumped_data, 0x1000);
293 data_region_end = bc_limit = dumped_data + DUMPED_HEAP_SIZE;
295 params.InitialCommit = committed = 0x1000;
296 params.InitialReserve = sizeof(dumped_data);
297 /* Use our own routine to commit memory from the dumped_data
298 array. */
299 params.CommitRoutine = &dumped_data_commit;
301 /* Create the private heap. */
302 if (s_pfn_Rtl_Create_Heap == NULL)
304 fprintf (stderr, "Cannot build Emacs without RtlCreateHeap being available; exiting.\n");
305 exit (-1);
307 heap = s_pfn_Rtl_Create_Heap (0, data_region_base, 0, 0, NULL, &params);
309 if (os_subtype == OS_9X)
311 fprintf (stderr, "Cannot dump Emacs on Windows 9X; exiting.\n");
312 exit (-1);
314 else
316 the_malloc_fn = malloc_before_dump;
317 the_realloc_fn = realloc_before_dump;
318 the_free_fn = free_before_dump;
322 /* Update system version information to match current system. */
323 cache_system_info ();
327 /* malloc, realloc, free. */
329 #undef malloc
330 #undef realloc
331 #undef free
333 /* FREEABLE_P checks if the block can be safely freed. */
334 #define FREEABLE_P(addr) \
335 ((DWORD_PTR)(unsigned char *)(addr) > 0 \
336 && ((unsigned char *)(addr) < dumped_data \
337 || (unsigned char *)(addr) >= dumped_data + DUMPED_HEAP_SIZE))
339 void *
340 malloc_after_dump (size_t size)
342 /* Use the new private heap. */
343 void *p = HeapAlloc (heap, 0, size);
345 /* After dump, keep track of the "brk value" for sbrk(0). */
346 if (p)
348 unsigned char *new_brk = (unsigned char *)p + size;
350 if (new_brk > data_region_end)
351 data_region_end = new_brk;
353 else
354 errno = ENOMEM;
355 return p;
358 void *
359 malloc_before_dump (size_t size)
361 void *p;
363 /* Before dumping. The private heap can handle only requests for
364 less than MaxBlockSize. */
365 if (size < MaxBlockSize)
367 /* Use the private heap if possible. */
368 p = HeapAlloc (heap, 0, size);
369 if (!p)
370 errno = ENOMEM;
372 else
374 /* Find the first big chunk that can hold the requested size. */
375 int i = 0;
377 for (i = 0; i < blocks_number; i++)
379 if (blocks[i].occupied == 0 && blocks[i].size >= size)
380 break;
382 if (i < blocks_number)
384 /* If found, use it. */
385 p = blocks[i].address;
386 blocks[i].occupied = TRUE;
388 else
390 /* Allocate a new big chunk from the end of the dumped_data
391 array. */
392 if (blocks_number >= MAX_BLOCKS)
394 fprintf (stderr,
395 "malloc_before_dump: no more big chunks available.\nEnlarge MAX_BLOCKS!\n");
396 exit (-1);
398 bc_limit -= size;
399 bc_limit = (unsigned char *)ROUND_DOWN (bc_limit, 0x10);
400 p = bc_limit;
401 blocks[blocks_number].address = p;
402 blocks[blocks_number].size = size;
403 blocks[blocks_number].occupied = TRUE;
404 blocks_number++;
405 /* Check that areas do not overlap. */
406 if (bc_limit < dumped_data + committed)
408 fprintf (stderr,
409 "malloc_before_dump: memory exhausted.\nEnlarge dumped_data[]!\n");
410 exit (-1);
414 return p;
417 /* Re-allocate the previously allocated block in ptr, making the new
418 block SIZE bytes long. */
419 void *
420 realloc_after_dump (void *ptr, size_t size)
422 void *p;
424 /* After dumping. */
425 if (FREEABLE_P (ptr))
427 /* Reallocate the block since it lies in the new heap. */
428 p = HeapReAlloc (heap, 0, ptr, size);
429 if (!p)
430 errno = ENOMEM;
432 else
434 /* If the block lies in the dumped data, do not free it. Only
435 allocate a new one. */
436 p = HeapAlloc (heap, 0, size);
437 if (!p)
438 errno = ENOMEM;
439 else if (ptr)
440 CopyMemory (p, ptr, size);
442 /* After dump, keep track of the "brk value" for sbrk(0). */
443 if (p)
445 unsigned char *new_brk = (unsigned char *)p + size;
447 if (new_brk > data_region_end)
448 data_region_end = new_brk;
450 return p;
453 void *
454 realloc_before_dump (void *ptr, size_t size)
456 void *p;
458 /* Before dumping. */
459 if (dumped_data < (unsigned char *)ptr
460 && (unsigned char *)ptr < bc_limit && size <= MaxBlockSize)
462 p = HeapReAlloc (heap, 0, ptr, size);
463 if (!p)
464 errno = ENOMEM;
466 else
468 /* In this case, either the new block is too large for the heap,
469 or the old block was already too large. In both cases,
470 malloc_before_dump() and free_before_dump() will take care of
471 reallocation. */
472 p = malloc_before_dump (size);
473 /* If SIZE is below MaxBlockSize, malloc_before_dump will try to
474 allocate it in the fixed heap. If that fails, we could have
475 kept the block in its original place, above bc_limit, instead
476 of failing the call as below. But this doesn't seem to be
477 worth the added complexity, as loadup allocates only a very
478 small number of large blocks, and never reallocates them. */
479 if (p && ptr)
481 CopyMemory (p, ptr, size);
482 free_before_dump (ptr);
485 return p;
488 /* Free a block allocated by `malloc', `realloc' or `calloc'. */
489 void
490 free_after_dump (void *ptr)
492 /* After dumping. */
493 if (FREEABLE_P (ptr))
495 /* Free the block if it is in the new private heap. */
496 HeapFree (heap, 0, ptr);
500 void
501 free_before_dump (void *ptr)
503 if (!ptr)
504 return;
506 /* Before dumping. */
507 if (dumped_data < (unsigned char *)ptr
508 && (unsigned char *)ptr < bc_limit)
510 /* Free the block if it is allocated in the private heap. */
511 HeapFree (heap, 0, ptr);
513 else
515 /* Look for the big chunk. */
516 int i;
518 for (i = 0; i < blocks_number; i++)
520 if (blocks[i].address == ptr)
522 /* Reset block occupation if found. */
523 blocks[i].occupied = 0;
524 break;
526 /* What if the block is not found? We should trigger an
527 error here. */
528 eassert (i < blocks_number);
533 /* On Windows 9X, HeapAlloc may return pointers that are not aligned
534 on 8-byte boundary, alignment which is required by the Lisp memory
535 management. To circumvent this problem, manually enforce alignment
536 on Windows 9X. */
538 void *
539 malloc_after_dump_9x (size_t size)
541 void *p = malloc_after_dump (size + 8);
542 void *pa;
543 if (p == NULL)
544 return p;
545 pa = (void*)(((intptr_t)p + 8) & ~7);
546 *((void**)pa-1) = p;
547 return pa;
550 void *
551 realloc_after_dump_9x (void *ptr, size_t size)
553 if (FREEABLE_P (ptr))
555 void *po = *((void**)ptr-1);
556 void *p;
557 void *pa;
558 p = realloc_after_dump (po, size + 8);
559 if (p == NULL)
560 return p;
561 pa = (void*)(((intptr_t)p + 8) & ~7);
562 if (ptr != NULL &&
563 (char*)pa - (char*)p != (char*)ptr - (char*)po)
565 /* Handle the case where alignment in pre-realloc and
566 post-realloc blocks does not match. */
567 MoveMemory (pa, (void*)((char*)p + ((char*)ptr - (char*)po)), size);
569 *((void**)pa-1) = p;
570 return pa;
572 else
574 /* Non-freeable pointers have no alignment-enforcing header
575 (since dumping is not allowed on Windows 9X). */
576 void* p = malloc_after_dump_9x (size);
577 if (p != NULL)
578 CopyMemory (p, ptr, size);
579 return p;
583 void
584 free_after_dump_9x (void *ptr)
586 if (FREEABLE_P (ptr))
588 free_after_dump (*((void**)ptr-1));
592 #ifdef ENABLE_CHECKING
593 void
594 report_temacs_memory_usage (void)
596 DWORD blocks_used = 0;
597 size_t large_mem_used = 0;
598 int i;
600 for (i = 0; i < blocks_number; i++)
601 if (blocks[i].occupied)
603 blocks_used++;
604 large_mem_used += blocks[i].size;
607 /* Emulate 'message', which writes to stderr in non-interactive
608 sessions. */
609 fprintf (stderr,
610 "Dump memory usage: Heap: %" PRIu64 " Large blocks(%lu/%lu): %" PRIu64 "/%" PRIu64 "\n",
611 (unsigned long long)committed, blocks_used, blocks_number,
612 (unsigned long long)large_mem_used,
613 (unsigned long long)(dumped_data + DUMPED_HEAP_SIZE - bc_limit));
615 #endif
617 /* Emulate getpagesize. */
619 getpagesize (void)
621 return sysinfo_cache.dwPageSize;
624 void *
625 sbrk (ptrdiff_t increment)
627 /* data_region_end is the address beyond the last allocated byte.
628 The sbrk() function is not emulated at all, except for a 0 value
629 of its parameter. This is needed by the Emacs Lisp function
630 `memory-limit'. */
631 eassert (increment == 0);
632 return data_region_end;
637 /* MMAP allocation for buffers. */
639 #define MAX_BUFFER_SIZE (512 * 1024 * 1024)
641 void *
642 mmap_alloc (void **var, size_t nbytes)
644 void *p = NULL;
646 /* We implement amortized allocation. We start by reserving twice
647 the size requested and commit only the size requested. Then
648 realloc could proceed and use the reserved pages, reallocating
649 only if needed. Buffer shrink would happen only so that we stay
650 in the 2x range. This is a big win when visiting compressed
651 files, where the final size of the buffer is not known in
652 advance, and the buffer is enlarged several times as the data is
653 decompressed on the fly. */
654 if (nbytes < MAX_BUFFER_SIZE)
655 p = VirtualAlloc (NULL, ROUND_UP (nbytes * 2, get_allocation_unit ()),
656 MEM_RESERVE, PAGE_READWRITE);
658 /* If it fails, or if the request is above 512MB, try with the
659 requested size. */
660 if (p == NULL)
661 p = VirtualAlloc (NULL, ROUND_UP (nbytes, get_allocation_unit ()),
662 MEM_RESERVE, PAGE_READWRITE);
664 if (p != NULL)
666 /* Now, commit pages for NBYTES. */
667 *var = VirtualAlloc (p, nbytes, MEM_COMMIT, PAGE_READWRITE);
668 if (*var == NULL)
669 p = *var;
672 if (!p)
674 DWORD e = GetLastError ();
676 if (e == ERROR_NOT_ENOUGH_MEMORY)
677 errno = ENOMEM;
678 else
680 DebPrint (("mmap_alloc: error %ld\n", e));
681 errno = EINVAL;
685 return *var = p;
688 void
689 mmap_free (void **var)
691 if (*var)
693 if (VirtualFree (*var, 0, MEM_RELEASE) == 0)
694 DebPrint (("mmap_free: error %ld\n", GetLastError ()));
695 *var = NULL;
699 void *
700 mmap_realloc (void **var, size_t nbytes)
702 MEMORY_BASIC_INFORMATION memInfo, m2;
703 void *old_ptr;
705 if (*var == NULL)
706 return mmap_alloc (var, nbytes);
708 /* This case happens in init_buffer(). */
709 if (nbytes == 0)
711 mmap_free (var);
712 return mmap_alloc (var, nbytes);
715 memset (&memInfo, 0, sizeof (memInfo));
716 if (VirtualQuery (*var, &memInfo, sizeof (memInfo)) == 0)
717 DebPrint (("mmap_realloc: VirtualQuery error = %ld\n", GetLastError ()));
719 /* We need to enlarge the block. */
720 if (memInfo.RegionSize < nbytes)
722 memset (&m2, 0, sizeof (m2));
723 if (VirtualQuery ((char *)*var + memInfo.RegionSize, &m2, sizeof(m2)) == 0)
724 DebPrint (("mmap_realloc: VirtualQuery error = %ld\n",
725 GetLastError ()));
726 /* If there is enough room in the current reserved area, then
727 commit more pages as needed. */
728 if (m2.State == MEM_RESERVE
729 && m2.AllocationBase == memInfo.AllocationBase
730 && nbytes <= memInfo.RegionSize + m2.RegionSize)
732 void *p;
734 p = VirtualAlloc (*var, nbytes, MEM_COMMIT, PAGE_READWRITE);
735 if (!p /* && GetLastError() != ERROR_NOT_ENOUGH_MEMORY */)
737 DebPrint (("realloc enlarge: VirtualAlloc (%p + %I64x, %I64x) error %ld\n",
738 *var, (uint64_t)memInfo.RegionSize,
739 (uint64_t)(nbytes - memInfo.RegionSize),
740 GetLastError ()));
741 DebPrint (("next region: %p %p %I64x %x\n", m2.BaseAddress,
742 m2.AllocationBase, (uint64_t)m2.RegionSize,
743 m2.AllocationProtect));
745 else
746 return *var;
748 /* Else we must actually enlarge the block by allocating a new
749 one and copying previous contents from the old to the new one. */
750 old_ptr = *var;
752 if (mmap_alloc (var, nbytes))
754 CopyMemory (*var, old_ptr, memInfo.RegionSize);
755 mmap_free (&old_ptr);
756 return *var;
758 else
760 /* We failed to reallocate the buffer. */
761 *var = old_ptr;
762 return NULL;
766 /* If we are shrinking by more than one page... */
767 if (memInfo.RegionSize > nbytes + getpagesize())
769 /* If we are shrinking a lot... */
770 if ((memInfo.RegionSize / 2) > nbytes)
772 /* Let's give some memory back to the system and release
773 some pages. */
774 old_ptr = *var;
776 if (mmap_alloc (var, nbytes))
778 CopyMemory (*var, old_ptr, nbytes);
779 mmap_free (&old_ptr);
780 return *var;
782 else
784 /* In case we fail to shrink, try to go on with the old block.
785 But that means there is a lot of memory pressure.
786 We could also decommit pages. */
787 *var = old_ptr;
788 return *var;
792 /* We still can decommit pages. */
793 if (VirtualFree ((char *)*var + nbytes + get_page_size(),
794 memInfo.RegionSize - nbytes - get_page_size(),
795 MEM_DECOMMIT) == 0)
796 DebPrint (("mmap_realloc: VirtualFree error %ld\n", GetLastError ()));
797 return *var;
800 /* Not enlarging, not shrinking by more than one page. */
801 return *var;
805 /* Emulation of getrlimit and setrlimit. */
808 getrlimit (rlimit_resource_t rltype, struct rlimit *rlp)
810 int retval = -1;
812 switch (rltype)
814 case RLIMIT_STACK:
816 MEMORY_BASIC_INFORMATION m;
817 /* Implementation note: Posix says that RLIMIT_STACK returns
818 information about the stack size for the main thread. The
819 implementation below returns the stack size for the calling
820 thread, so it's more like pthread_attr_getstacksize. But
821 Emacs clearly wants the latter, given how it uses the
822 results, so the implementation below is more future-proof,
823 if what's now the main thread will become some other thread
824 at some future point. */
825 if (!VirtualQuery ((LPCVOID) &m, &m, sizeof m))
826 errno = EPERM;
827 else
829 rlp->rlim_cur = (DWORD_PTR) &m - (DWORD_PTR) m.AllocationBase;
830 rlp->rlim_max =
831 (DWORD_PTR) m.BaseAddress + m.RegionSize
832 - (DWORD_PTR) m.AllocationBase;
834 /* The last page is the guard page, so subtract that. */
835 rlp->rlim_cur -= getpagesize ();
836 rlp->rlim_max -= getpagesize ();
837 retval = 0;
840 break;
841 case RLIMIT_NOFILE:
842 /* Implementation note: The real value is returned by
843 _getmaxstdio. But our FD_SETSIZE is smaller, to cater to
844 Windows 9X, and process.c includes some logic that's based on
845 the assumption that the handle resource is inherited to child
846 processes. We want to avoid that logic, so we tell process.c
847 our current limit is already equal to FD_SETSIZE. */
848 rlp->rlim_cur = FD_SETSIZE;
849 rlp->rlim_max = 2048; /* see _setmaxstdio documentation */
850 retval = 0;
851 break;
852 default:
853 /* Note: we could return meaningful results for other RLIMIT_*
854 requests, but Emacs doesn't currently need that, so we just
855 punt for them. */
856 errno = ENOSYS;
857 break;
859 return retval;
863 setrlimit (rlimit_resource_t rltype, const struct rlimit *rlp)
865 switch (rltype)
867 case RLIMIT_STACK:
868 case RLIMIT_NOFILE:
869 /* We cannot modfy these limits, so we always fail. */
870 errno = EPERM;
871 break;
872 default:
873 errno = ENOSYS;
874 break;
876 return -1;