Merge branch 'master' into comment-cache
[emacs.git] / src / w32heap.c
blob54de9617494f32c1d993aa5fe17f58dca40f7c83
1 /* Heap management routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994, 2001-2017 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 <http://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 (21*1024*1024)
120 #else
121 # define DUMPED_HEAP_SIZE (12*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 unsigned long enable_lfh = 2;
233 /* After dumping, use a new private heap. We explicitly enable
234 the low fragmentation heap (LFH) here, for the sake of pre
235 Vista versions. Note: this will harmlessly fail on Vista and
236 later, where the low-fragmentation heap is enabled by
237 default. It will also fail on pre-Vista versions when Emacs
238 is run under a debugger; set _NO_DEBUG_HEAP=1 in the
239 environment before starting GDB to get low fragmentation heap
240 on XP and older systems, for the price of losing "certain
241 heap debug options"; for the details see
242 http://msdn.microsoft.com/en-us/library/windows/desktop/aa366705%28v=vs.85%29.aspx. */
243 data_region_end = data_region_base;
245 /* Create the private heap. */
246 heap = HeapCreate (0, 0, 0);
248 #ifndef MINGW_W64
249 /* Set the low-fragmentation heap for OS before Vista. */
250 HMODULE hm_kernel32dll = LoadLibrary ("kernel32.dll");
251 HeapSetInformation_Proc s_pfn_Heap_Set_Information = (HeapSetInformation_Proc) GetProcAddress (hm_kernel32dll, "HeapSetInformation");
252 if (s_pfn_Heap_Set_Information != NULL)
254 if (s_pfn_Heap_Set_Information ((PVOID) heap,
255 HeapCompatibilityInformation,
256 &enable_lfh, sizeof(enable_lfh)) == 0)
257 DebPrint (("Enabling Low Fragmentation Heap failed: error %ld\n",
258 GetLastError ()));
260 #endif
262 if (os_subtype == OS_9X)
264 the_malloc_fn = malloc_after_dump_9x;
265 the_realloc_fn = realloc_after_dump_9x;
266 the_free_fn = free_after_dump_9x;
268 else
270 the_malloc_fn = malloc_after_dump;
271 the_realloc_fn = realloc_after_dump;
272 the_free_fn = free_after_dump;
275 else
277 /* Find the RtlCreateHeap function. Headers for this function
278 are provided with the w32 DDK, but the function is available
279 in ntdll.dll since XP. */
280 HMODULE hm_ntdll = LoadLibrary ("ntdll.dll");
281 RtlCreateHeap_Proc s_pfn_Rtl_Create_Heap
282 = (RtlCreateHeap_Proc) GetProcAddress (hm_ntdll, "RtlCreateHeap");
283 /* Specific parameters for the private heap. */
284 RTL_HEAP_PARAMETERS params;
285 ZeroMemory (&params, sizeof(params));
286 params.Length = sizeof(RTL_HEAP_PARAMETERS);
288 data_region_base = (unsigned char *)ROUND_UP (dumped_data, 0x1000);
289 data_region_end = bc_limit = dumped_data + DUMPED_HEAP_SIZE;
291 params.InitialCommit = committed = 0x1000;
292 params.InitialReserve = sizeof(dumped_data);
293 /* Use our own routine to commit memory from the dumped_data
294 array. */
295 params.CommitRoutine = &dumped_data_commit;
297 /* Create the private heap. */
298 if (s_pfn_Rtl_Create_Heap == NULL)
300 fprintf (stderr, "Cannot build Emacs without RtlCreateHeap being available; exiting.\n");
301 exit (-1);
303 heap = s_pfn_Rtl_Create_Heap (0, data_region_base, 0, 0, NULL, &params);
305 if (os_subtype == OS_9X)
307 fprintf (stderr, "Cannot dump Emacs on Windows 9X; exiting.\n");
308 exit (-1);
310 else
312 the_malloc_fn = malloc_before_dump;
313 the_realloc_fn = realloc_before_dump;
314 the_free_fn = free_before_dump;
318 /* Update system version information to match current system. */
319 cache_system_info ();
323 /* malloc, realloc, free. */
325 #undef malloc
326 #undef realloc
327 #undef free
329 /* FREEABLE_P checks if the block can be safely freed. */
330 #define FREEABLE_P(addr) \
331 ((DWORD_PTR)(unsigned char *)(addr) > 0 \
332 && ((unsigned char *)(addr) < dumped_data \
333 || (unsigned char *)(addr) >= dumped_data + DUMPED_HEAP_SIZE))
335 void *
336 malloc_after_dump (size_t size)
338 /* Use the new private heap. */
339 void *p = HeapAlloc (heap, 0, size);
341 /* After dump, keep track of the "brk value" for sbrk(0). */
342 if (p)
344 unsigned char *new_brk = (unsigned char *)p + size;
346 if (new_brk > data_region_end)
347 data_region_end = new_brk;
349 else
350 errno = ENOMEM;
351 return p;
354 void *
355 malloc_before_dump (size_t size)
357 void *p;
359 /* Before dumping. The private heap can handle only requests for
360 less than MaxBlockSize. */
361 if (size < MaxBlockSize)
363 /* Use the private heap if possible. */
364 p = HeapAlloc (heap, 0, size);
365 if (!p)
366 errno = ENOMEM;
368 else
370 /* Find the first big chunk that can hold the requested size. */
371 int i = 0;
373 for (i = 0; i < blocks_number; i++)
375 if (blocks[i].occupied == 0 && blocks[i].size >= size)
376 break;
378 if (i < blocks_number)
380 /* If found, use it. */
381 p = blocks[i].address;
382 blocks[i].occupied = TRUE;
384 else
386 /* Allocate a new big chunk from the end of the dumped_data
387 array. */
388 if (blocks_number >= MAX_BLOCKS)
390 fprintf (stderr,
391 "malloc_before_dump: no more big chunks available.\nEnlarge MAX_BLOCKS!\n");
392 exit (-1);
394 bc_limit -= size;
395 bc_limit = (unsigned char *)ROUND_DOWN (bc_limit, 0x10);
396 p = bc_limit;
397 blocks[blocks_number].address = p;
398 blocks[blocks_number].size = size;
399 blocks[blocks_number].occupied = TRUE;
400 blocks_number++;
401 /* Check that areas do not overlap. */
402 if (bc_limit < dumped_data + committed)
404 fprintf (stderr,
405 "malloc_before_dump: memory exhausted.\nEnlarge dumped_data[]!\n");
406 exit (-1);
410 return p;
413 /* Re-allocate the previously allocated block in ptr, making the new
414 block SIZE bytes long. */
415 void *
416 realloc_after_dump (void *ptr, size_t size)
418 void *p;
420 /* After dumping. */
421 if (FREEABLE_P (ptr))
423 /* Reallocate the block since it lies in the new heap. */
424 p = HeapReAlloc (heap, 0, ptr, size);
425 if (!p)
426 errno = ENOMEM;
428 else
430 /* If the block lies in the dumped data, do not free it. Only
431 allocate a new one. */
432 p = HeapAlloc (heap, 0, size);
433 if (!p)
434 errno = ENOMEM;
435 else if (ptr)
436 CopyMemory (p, ptr, size);
438 /* After dump, keep track of the "brk value" for sbrk(0). */
439 if (p)
441 unsigned char *new_brk = (unsigned char *)p + size;
443 if (new_brk > data_region_end)
444 data_region_end = new_brk;
446 return p;
449 void *
450 realloc_before_dump (void *ptr, size_t size)
452 void *p;
454 /* Before dumping. */
455 if (dumped_data < (unsigned char *)ptr
456 && (unsigned char *)ptr < bc_limit && size <= MaxBlockSize)
458 p = HeapReAlloc (heap, 0, ptr, size);
459 if (!p)
460 errno = ENOMEM;
462 else
464 /* In this case, either the new block is too large for the heap,
465 or the old block was already too large. In both cases,
466 malloc_before_dump() and free_before_dump() will take care of
467 reallocation. */
468 p = malloc_before_dump (size);
469 /* If SIZE is below MaxBlockSize, malloc_before_dump will try to
470 allocate it in the fixed heap. If that fails, we could have
471 kept the block in its original place, above bc_limit, instead
472 of failing the call as below. But this doesn't seem to be
473 worth the added complexity, as loadup allocates only a very
474 small number of large blocks, and never reallocates them. */
475 if (p && ptr)
477 CopyMemory (p, ptr, size);
478 free_before_dump (ptr);
481 return p;
484 /* Free a block allocated by `malloc', `realloc' or `calloc'. */
485 void
486 free_after_dump (void *ptr)
488 /* After dumping. */
489 if (FREEABLE_P (ptr))
491 /* Free the block if it is in the new private heap. */
492 HeapFree (heap, 0, ptr);
496 void
497 free_before_dump (void *ptr)
499 if (!ptr)
500 return;
502 /* Before dumping. */
503 if (dumped_data < (unsigned char *)ptr
504 && (unsigned char *)ptr < bc_limit)
506 /* Free the block if it is allocated in the private heap. */
507 HeapFree (heap, 0, ptr);
509 else
511 /* Look for the big chunk. */
512 int i;
514 for (i = 0; i < blocks_number; i++)
516 if (blocks[i].address == ptr)
518 /* Reset block occupation if found. */
519 blocks[i].occupied = 0;
520 break;
522 /* What if the block is not found? We should trigger an
523 error here. */
524 eassert (i < blocks_number);
529 /* On Windows 9X, HeapAlloc may return pointers that are not aligned
530 on 8-byte boundary, alignment which is required by the Lisp memory
531 management. To circumvent this problem, manually enforce alignment
532 on Windows 9X. */
534 void *
535 malloc_after_dump_9x (size_t size)
537 void *p = malloc_after_dump (size + 8);
538 void *pa;
539 if (p == NULL)
540 return p;
541 pa = (void*)(((intptr_t)p + 8) & ~7);
542 *((void**)pa-1) = p;
543 return pa;
546 void *
547 realloc_after_dump_9x (void *ptr, size_t size)
549 if (FREEABLE_P (ptr))
551 void *po = *((void**)ptr-1);
552 void *p;
553 void *pa;
554 p = realloc_after_dump (po, size + 8);
555 if (p == NULL)
556 return p;
557 pa = (void*)(((intptr_t)p + 8) & ~7);
558 if (ptr != NULL &&
559 (char*)pa - (char*)p != (char*)ptr - (char*)po)
561 /* Handle the case where alignment in pre-realloc and
562 post-realloc blocks does not match. */
563 MoveMemory (pa, (void*)((char*)p + ((char*)ptr - (char*)po)), size);
565 *((void**)pa-1) = p;
566 return pa;
568 else
570 /* Non-freeable pointers have no alignment-enforcing header
571 (since dumping is not allowed on Windows 9X). */
572 void* p = malloc_after_dump_9x (size);
573 if (p != NULL)
574 CopyMemory (p, ptr, size);
575 return p;
579 void
580 free_after_dump_9x (void *ptr)
582 if (FREEABLE_P (ptr))
584 free_after_dump (*((void**)ptr-1));
588 #ifdef ENABLE_CHECKING
589 void
590 report_temacs_memory_usage (void)
592 DWORD blocks_used = 0;
593 size_t large_mem_used = 0;
594 int i;
596 for (i = 0; i < blocks_number; i++)
597 if (blocks[i].occupied)
599 blocks_used++;
600 large_mem_used += blocks[i].size;
603 /* Emulate 'message', which writes to stderr in non-interactive
604 sessions. */
605 fprintf (stderr,
606 "Dump memory usage: Heap: %" PRIu64 " Large blocks(%lu/%lu): %" PRIu64 "/%" PRIu64 "\n",
607 (unsigned long long)committed, blocks_used, blocks_number,
608 (unsigned long long)large_mem_used,
609 (unsigned long long)(dumped_data + DUMPED_HEAP_SIZE - bc_limit));
611 #endif
613 /* Emulate getpagesize. */
615 getpagesize (void)
617 return sysinfo_cache.dwPageSize;
620 void *
621 sbrk (ptrdiff_t increment)
623 /* data_region_end is the address beyond the last allocated byte.
624 The sbrk() function is not emulated at all, except for a 0 value
625 of its parameter. This is needed by the Emacs Lisp function
626 `memory-limit'. */
627 eassert (increment == 0);
628 return data_region_end;
633 /* MMAP allocation for buffers. */
635 #define MAX_BUFFER_SIZE (512 * 1024 * 1024)
637 void *
638 mmap_alloc (void **var, size_t nbytes)
640 void *p = NULL;
642 /* We implement amortized allocation. We start by reserving twice
643 the size requested and commit only the size requested. Then
644 realloc could proceed and use the reserved pages, reallocating
645 only if needed. Buffer shrink would happen only so that we stay
646 in the 2x range. This is a big win when visiting compressed
647 files, where the final size of the buffer is not known in
648 advance, and the buffer is enlarged several times as the data is
649 decompressed on the fly. */
650 if (nbytes < MAX_BUFFER_SIZE)
651 p = VirtualAlloc (NULL, ROUND_UP (nbytes * 2, get_allocation_unit ()),
652 MEM_RESERVE, PAGE_READWRITE);
654 /* If it fails, or if the request is above 512MB, try with the
655 requested size. */
656 if (p == NULL)
657 p = VirtualAlloc (NULL, ROUND_UP (nbytes, get_allocation_unit ()),
658 MEM_RESERVE, PAGE_READWRITE);
660 if (p != NULL)
662 /* Now, commit pages for NBYTES. */
663 *var = VirtualAlloc (p, nbytes, MEM_COMMIT, PAGE_READWRITE);
664 if (*var == NULL)
665 p = *var;
668 if (!p)
670 DWORD e = GetLastError ();
672 if (e == ERROR_NOT_ENOUGH_MEMORY)
673 errno = ENOMEM;
674 else
676 DebPrint (("mmap_alloc: error %ld\n", e));
677 errno = EINVAL;
681 return *var = p;
684 void
685 mmap_free (void **var)
687 if (*var)
689 if (VirtualFree (*var, 0, MEM_RELEASE) == 0)
690 DebPrint (("mmap_free: error %ld\n", GetLastError ()));
691 *var = NULL;
695 void *
696 mmap_realloc (void **var, size_t nbytes)
698 MEMORY_BASIC_INFORMATION memInfo, m2;
699 void *old_ptr;
701 if (*var == NULL)
702 return mmap_alloc (var, nbytes);
704 /* This case happens in init_buffer(). */
705 if (nbytes == 0)
707 mmap_free (var);
708 return mmap_alloc (var, nbytes);
711 memset (&memInfo, 0, sizeof (memInfo));
712 if (VirtualQuery (*var, &memInfo, sizeof (memInfo)) == 0)
713 DebPrint (("mmap_realloc: VirtualQuery error = %ld\n", GetLastError ()));
715 /* We need to enlarge the block. */
716 if (memInfo.RegionSize < nbytes)
718 memset (&m2, 0, sizeof (m2));
719 if (VirtualQuery ((char *)*var + memInfo.RegionSize, &m2, sizeof(m2)) == 0)
720 DebPrint (("mmap_realloc: VirtualQuery error = %ld\n",
721 GetLastError ()));
722 /* If there is enough room in the current reserved area, then
723 commit more pages as needed. */
724 if (m2.State == MEM_RESERVE
725 && m2.AllocationBase == memInfo.AllocationBase
726 && nbytes <= memInfo.RegionSize + m2.RegionSize)
728 void *p;
730 p = VirtualAlloc (*var, nbytes, MEM_COMMIT, PAGE_READWRITE);
731 if (!p /* && GetLastError() != ERROR_NOT_ENOUGH_MEMORY */)
733 DebPrint (("realloc enlarge: VirtualAlloc (%p + %I64x, %I64x) error %ld\n",
734 *var, (uint64_t)memInfo.RegionSize,
735 (uint64_t)(nbytes - memInfo.RegionSize),
736 GetLastError ()));
737 DebPrint (("next region: %p %p %I64x %x\n", m2.BaseAddress,
738 m2.AllocationBase, (uint64_t)m2.RegionSize,
739 m2.AllocationProtect));
741 else
742 return *var;
744 /* Else we must actually enlarge the block by allocating a new
745 one and copying previous contents from the old to the new one. */
746 old_ptr = *var;
748 if (mmap_alloc (var, nbytes))
750 CopyMemory (*var, old_ptr, memInfo.RegionSize);
751 mmap_free (&old_ptr);
752 return *var;
754 else
756 /* We failed to reallocate the buffer. */
757 *var = old_ptr;
758 return NULL;
762 /* If we are shrinking by more than one page... */
763 if (memInfo.RegionSize > nbytes + getpagesize())
765 /* If we are shrinking a lot... */
766 if ((memInfo.RegionSize / 2) > nbytes)
768 /* Let's give some memory back to the system and release
769 some pages. */
770 old_ptr = *var;
772 if (mmap_alloc (var, nbytes))
774 CopyMemory (*var, old_ptr, nbytes);
775 mmap_free (&old_ptr);
776 return *var;
778 else
780 /* In case we fail to shrink, try to go on with the old block.
781 But that means there is a lot of memory pressure.
782 We could also decommit pages. */
783 *var = old_ptr;
784 return *var;
788 /* We still can decommit pages. */
789 if (VirtualFree ((char *)*var + nbytes + get_page_size(),
790 memInfo.RegionSize - nbytes - get_page_size(),
791 MEM_DECOMMIT) == 0)
792 DebPrint (("mmap_realloc: VirtualFree error %ld\n", GetLastError ()));
793 return *var;
796 /* Not enlarging, not shrinking by more than one page. */
797 return *var;
801 /* Emulation of getrlimit and setrlimit. */
804 getrlimit (rlimit_resource_t rltype, struct rlimit *rlp)
806 int retval = -1;
808 switch (rltype)
810 case RLIMIT_STACK:
812 MEMORY_BASIC_INFORMATION m;
813 /* Implementation note: Posix says that RLIMIT_STACK returns
814 information about the stack size for the main thread. The
815 implementation below returns the stack size for the calling
816 thread, so it's more like pthread_attr_getstacksize. But
817 Emacs clearly wants the latter, given how it uses the
818 results, so the implementation below is more future-proof,
819 if what's now the main thread will become some other thread
820 at some future point. */
821 if (!VirtualQuery ((LPCVOID) &m, &m, sizeof m))
822 errno = EPERM;
823 else
825 rlp->rlim_cur = (DWORD_PTR) &m - (DWORD_PTR) m.AllocationBase;
826 rlp->rlim_max =
827 (DWORD_PTR) m.BaseAddress + m.RegionSize
828 - (DWORD_PTR) m.AllocationBase;
830 /* The last page is the guard page, so subtract that. */
831 rlp->rlim_cur -= getpagesize ();
832 rlp->rlim_max -= getpagesize ();
833 retval = 0;
836 break;
837 case RLIMIT_NOFILE:
838 /* Implementation note: The real value is returned by
839 _getmaxstdio. But our FD_SETSIZE is smaller, to cater to
840 Windows 9X, and process.c includes some logic that's based on
841 the assumption that the handle resource is inherited to child
842 processes. We want to avoid that logic, so we tell process.c
843 our current limit is already equal to FD_SETSIZE. */
844 rlp->rlim_cur = FD_SETSIZE;
845 rlp->rlim_max = 2048; /* see _setmaxstdio documentation */
846 retval = 0;
847 break;
848 default:
849 /* Note: we could return meaningful results for other RLIMIT_*
850 requests, but Emacs doesn't currently need that, so we just
851 punt for them. */
852 errno = ENOSYS;
853 break;
855 return retval;
859 setrlimit (rlimit_resource_t rltype, const struct rlimit *rlp)
861 switch (rltype)
863 case RLIMIT_STACK:
864 case RLIMIT_NOFILE:
865 /* We cannot modfy these limits, so we always fail. */
866 errno = EPERM;
867 break;
868 default:
869 errno = ENOSYS;
870 break;
872 return -1;