mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathalloc.c
More file actions
7639 lines (6435 loc) · 214 KB
/
Copy pathalloc.c
File metadata and controls
7639 lines (6435 loc) · 214 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
154
155
156
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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Storage allocation and gc for GNU Emacs Lisp interpreter.
Copyright (C) 1985-2026 Free Software Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Emacs 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
#include <config.h>
#ifdef HAVE_MALLOC_H
# include <malloc.h>
#endif
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <limits.h> /* For CHAR_BIT. */
#include <signal.h> /* For SIGABRT, SIGDANGER. */
#ifdef HAVE_PTHREAD
#include <pthread.h>
#endif
#include "lisp.h"
#include "bignum.h"
#include "dispextern.h"
#include "intervals.h"
#include "sysstdio.h"
#include "systime.h"
#include "character.h"
#include "buffer.h"
#include "window.h"
#include "keyboard.h"
#include "frame.h"
#include "blockinput.h"
#include "pdumper.h"
#include "termhooks.h" /* For struct terminal. */
#include "itree.h"
#ifdef HAVE_WINDOW_SYSTEM
#include TERM_HEADER
#endif /* HAVE_WINDOW_SYSTEM */
#if defined HAVE_ANDROID && !defined ANDROID_STUBIFY
#include "sfntfont.h"
#endif
#ifdef HAVE_TREE_SITTER
#include "treesit.h"
#endif
#include <flexmember.h>
#include <verify.h>
#include <execinfo.h> /* For backtrace. */
#ifdef HAVE_LINUX_SYSINFO
#include <sys/sysinfo.h>
#endif
#ifdef MSDOS
#include "dosfns.h" /* For dos_memory_info. */
#endif
#if (defined ENABLE_CHECKING \
&& defined HAVE_VALGRIND_VALGRIND_H && !defined USE_VALGRIND)
# define USE_VALGRIND 1
#endif
#if USE_VALGRIND
#include <valgrind/valgrind.h>
#include <valgrind/memcheck.h>
#endif
/* AddressSanitizer exposes additional functions for manually marking
memory as poisoned/unpoisoned. When ASan is enabled and the needed
header is available, memory is poisoned when:
* An ablock is freed (lisp_align_free), or ablocks are initially
allocated (lisp_align_malloc).
* An interval_block is initially allocated (make_interval).
* A dead INTERVAL is put on the interval free list
(sweep_intervals).
* A sdata is marked as dead (sweep_strings, pin_string).
* An sblock is initially allocated (allocate_string_data).
* A string_block is initially allocated (allocate_string).
* A dead string is put on string_free_list (sweep_strings).
* A float_block is initially allocated (make_float).
* A dead float is put on float_free_list.
* A cons_block is initially allocated (Fcons).
* A dead cons is put on cons_free_list (sweep_cons).
* A dead vector is put on vector_free_list (setup_on_free_list),
or a new vector block is allocated (allocate_vector_from_block).
Accordingly, objects reused from the free list are unpoisoned.
This feature can be disabled with the run-time flag
`allow_user_poisoning' set to zero. */
#if ADDRESS_SANITIZER && defined HAVE_SANITIZER_ASAN_INTERFACE_H \
&& !defined GC_ASAN_POISON_OBJECTS
# define GC_ASAN_POISON_OBJECTS 1
# include <sanitizer/asan_interface.h>
#else
# define GC_ASAN_POISON_OBJECTS 0
#endif
/* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
We turn that on by default when ENABLE_CHECKING is defined;
define GC_CHECK_MARKED_OBJECTS to zero to disable. */
#if defined ENABLE_CHECKING && !defined GC_CHECK_MARKED_OBJECTS
# define GC_CHECK_MARKED_OBJECTS 1
#endif
#ifndef GC_CHECK_MARKED_OBJECTS
# define GC_CHECK_MARKED_OBJECTS 0
#endif
/* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
memory. Can do this only if using gmalloc.c and if not checking
marked objects. */
#if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
|| GC_CHECK_MARKED_OBJECTS)
#undef GC_MALLOC_CHECK
#endif
#include <unistd.h>
#include <fcntl.h>
#ifdef USE_GTK
# include "gtkutil.h"
#endif
#ifdef WINDOWSNT
#include "w32.h"
#include "w32heap.h" /* for sbrk */
#endif
/* A type with alignment at least as large as any object that Emacs
allocates. This is not max_align_t because some platforms (e.g.,
mingw) have buggy malloc implementations that do not align for
max_align_t. This union contains types of all GCALIGNED_STRUCT
components visible here. */
union emacs_align_type
{
struct frame frame;
struct Lisp_Bignum Lisp_Bignum;
struct Lisp_CondVar Lisp_CondVar;
struct Lisp_Finalizer Lisp_Finalizer;
struct Lisp_Float Lisp_Float;
struct Lisp_Hash_Table Lisp_Hash_Table;
struct Lisp_Marker Lisp_Marker;
struct Lisp_Misc_Ptr Lisp_Misc_Ptr;
struct Lisp_Mutex Lisp_Mutex;
struct Lisp_Overlay Lisp_Overlay;
struct Lisp_Subr Lisp_Subr;
struct Lisp_Sqlite Lisp_Sqlite;
struct Lisp_User_Ptr Lisp_User_Ptr;
struct terminal terminal;
struct thread_state thread_state;
struct window window;
/* Omit the following since they would require including process.h
etc, or because they are defined with flexible array members, which
are rejected by some C99 compilers when this union subsequently
appears in an `alignof' expression. In practice their alignments
never exceed that of the structs already listed. */
#if 0
struct Lisp_Bool_Vector Lisp_Bool_Vector;
struct Lisp_Char_Table Lisp_Char_Table;
struct Lisp_Sub_Char_Table Lisp_Sub_Char_Table;
struct Lisp_Module_Function Lisp_Module_Function;
struct Lisp_Process Lisp_Process;
struct Lisp_Vector Lisp_Vector;
struct save_window_data save_window_data;
struct scroll_bar scroll_bar;
struct xwidget_view xwidget_view;
struct xwidget xwidget;
#endif
};
/* MALLOC_SIZE_NEAR (N) is a good number to pass to malloc when
allocating a block of memory with size close to N bytes.
For best results N should be a power of 2.
When calculating how much memory to allocate, GNU malloc (SIZE)
adds sizeof (size_t) to SIZE for internal overhead, and then rounds
up to a multiple of MALLOC_ALIGNMENT. Emacs can improve
performance a bit on GNU platforms by arranging for the resulting
size to be a power of two. This heuristic is good for glibc 2.26
(2017) and later, and does not affect correctness on other
platforms. */
#define MALLOC_SIZE_NEAR(n) \
(ROUNDUP (max (n, sizeof (size_t)), MALLOC_ALIGNMENT) - sizeof (size_t))
#ifdef __i386
enum { MALLOC_ALIGNMENT = 16 };
#else
enum { MALLOC_ALIGNMENT = max (2 * sizeof (size_t), alignof (long double)) };
#endif
#ifdef DOUG_LEA_MALLOC
/* Specify maximum number of areas to mmap. It would be nice to use a
value that explicitly means "no limit". */
# define MMAP_MAX_AREAS 100000000
/* Restore the dumped malloc state. Because malloc can be invoked
even before main (e.g. by the dynamic linker), the dumped malloc
state must be restored as early as possible using this special hook. */
static void
malloc_initialize_hook (void)
{
static bool malloc_using_checking;
if (! initialized)
{
malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
}
else
{
if (!malloc_using_checking)
{
/* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
ignored if the heap to be restored was constructed without
malloc checking. Can't use unsetenv, since that calls malloc. */
char **p = environ;
if (p)
for (; *p; p++)
if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
{
do
*p = p[1];
while (*++p);
break;
}
}
}
}
/* Declare the malloc initialization hook, which runs before 'main' starts.
EXTERNALLY_VISIBLE works around Bug#22522. */
typedef void (*voidfuncptr) (void);
# ifndef __MALLOC_HOOK_VOLATILE
# define __MALLOC_HOOK_VOLATILE
# endif
voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
= malloc_initialize_hook;
#endif
/* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
to a struct Lisp_String. */
#define XMARK_STRING(S) ((S)->u.s.size |= ARRAY_MARK_FLAG)
#define XUNMARK_STRING(S) ((S)->u.s.size &= ~ARRAY_MARK_FLAG)
#define XSTRING_MARKED_P(S) (((S)->u.s.size & ARRAY_MARK_FLAG) != 0)
#define XMARK_VECTOR(V) ((V)->header.size |= ARRAY_MARK_FLAG)
#define XUNMARK_VECTOR(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
#define XVECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
/* Default value of gc_cons_threshold (see below). */
#define GC_DEFAULT_THRESHOLD (100000 * word_size)
/* Global variables. */
struct emacs_globals globals;
/* maybe_gc collects garbage if this goes negative. */
EMACS_INT consing_until_gc;
#ifdef HAVE_PDUMPER
/* Number of finalizers run: used to loop over GC until we stop
generating garbage. */
int number_finalizers_run;
#endif
/* True during GC. */
bool gc_in_progress;
/* System byte and object counts reported by GC. */
/* Assume byte counts fit in uintptr_t and object counts fit into
intptr_t. */
typedef uintptr_t byte_ct;
typedef intptr_t object_ct;
/* Large-magnitude value for a threshold count, which fits in EMACS_INT.
Using only half the EMACS_INT range avoids overflow hassles.
There is no need to fit these counts into fixnums. */
#define HI_THRESHOLD (EMACS_INT_MAX / 2)
/* Number of live and free conses etc. counted by the most-recent GC. */
static struct gcstat
{
object_ct total_conses, total_free_conses;
object_ct total_symbols, total_free_symbols;
object_ct total_strings, total_free_strings;
byte_ct total_string_bytes;
object_ct total_vectors, total_vector_slots, total_free_vector_slots;
object_ct total_floats, total_free_floats;
object_ct total_intervals, total_free_intervals;
object_ct total_buffers;
/* Size of the ancillary arrays of live hash-table and obarray objects.
The objects themselves are not included (counted as vectors above). */
byte_ct total_hash_table_bytes;
} gcstat;
/* Total size of ancillary arrays of all allocated hash-table and obarray
objects, both dead and alive. This number is always kept up-to-date. */
static ptrdiff_t hash_table_allocated_bytes = 0;
/* Points to memory space allocated as "spare", to be freed if we run
out of memory. We keep one large block, four cons-blocks, and
two string blocks. */
static char *spare_memory[7];
/* Amount of spare memory to keep in large reserve block, or to see
whether this much is available when malloc fails on a larger request. */
#define SPARE_MEMORY (1 << 14)
/* If positive, garbage collection is inhibited. Otherwise, zero. */
intptr_t garbage_collection_inhibited;
/* The GC threshold in bytes, the last time it was calculated
from gc-cons-threshold and gc-cons-percentage. */
static EMACS_INT gc_threshold;
/* If nonzero, this is a warning delivered by malloc and not yet
displayed. */
const char *pending_malloc_warning;
/* Maximum amount of C stack to save when a GC happens. */
#ifndef MAX_SAVE_STACK
#define MAX_SAVE_STACK 16000
#endif
/* Buffer in which we save a copy of the C stack at each GC. */
#if MAX_SAVE_STACK > 0
static char *stack_copy;
static ptrdiff_t stack_copy_size;
/* Copy to DEST a block of memory from SRC of size SIZE bytes,
avoiding any address sanitization. */
static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
no_sanitize_memcpy (void *dest, void const *src, size_t size)
{
if (! ADDRESS_SANITIZER)
return memcpy (dest, src, size);
else
{
size_t i;
char *d = dest;
char const *s = src;
for (i = 0; i < size; i++)
d[i] = s[i];
return dest;
}
}
#endif /* MAX_SAVE_STACK > 0 */
static struct Lisp_Vector *allocate_clear_vector (ptrdiff_t, bool);
static void unchain_finalizer (struct Lisp_Finalizer *);
static void mark_terminals (void);
static void gc_sweep (void);
static void mark_buffer (struct buffer *);
#if !defined REL_ALLOC || defined SYSTEM_MALLOC
static void refill_memory_reserve (void);
#endif
static void compact_small_strings (void);
static void free_large_strings (void);
extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
static bool vector_marked_p (struct Lisp_Vector const *);
static bool vectorlike_marked_p (union vectorlike_header const *);
static void set_vectorlike_marked (union vectorlike_header *);
static bool interval_marked_p (INTERVAL);
static void set_interval_marked (INTERVAL);
/* When scanning the C stack for live Lisp objects, Emacs keeps track of
what memory allocated via lisp_malloc and lisp_align_malloc is intended
for what purpose. This enumeration specifies the type of memory. */
enum mem_type
{
MEM_TYPE_NON_LISP,
MEM_TYPE_CONS,
MEM_TYPE_STRING,
MEM_TYPE_SYMBOL,
MEM_TYPE_FLOAT,
/* Since all non-bool pseudovectors are small enough to be
allocated from vector blocks, this memory type denotes
large regular vectors and large bool pseudovectors. */
MEM_TYPE_VECTORLIKE,
/* Special type to denote vector blocks. */
MEM_TYPE_VECTOR_BLOCK,
/* Special type to denote reserved memory. */
MEM_TYPE_SPARE
};
static bool
deadp (Lisp_Object x)
{
return BASE_EQ (x, dead_object ());
}
#ifdef GC_MALLOC_CHECK
enum mem_type allocated_mem_type;
#endif /* GC_MALLOC_CHECK */
/* A node in the red-black tree describing allocated memory containing
Lisp data. Each such block is recorded with its start and end
address when it is allocated, and removed from the tree when it
is freed.
A red-black tree is a balanced binary tree with the following
properties:
1. Every node is either red or black.
2. Every leaf is black.
3. If a node is red, then both of its children are black.
4. Every simple path from a node to a descendant leaf contains
the same number of black nodes.
5. The root is always black.
When nodes are inserted into the tree, or deleted from the tree,
the tree is "fixed" so that these properties are always true.
A red-black tree with N internal nodes has height at most 2
log(N+1). Searches, insertions and deletions are done in O(log N).
Please see a text book about data structures for a detailed
description of red-black trees. Any book worth its salt should
describe them. */
struct mem_node
{
/* Children of this node. These pointers are never NULL. When there
is no child, the value is MEM_NIL, which points to a dummy node. */
struct mem_node *left, *right;
/* The parent of this node. In the root node, this is NULL. */
struct mem_node *parent;
/* Start and end of allocated region. */
void *start, *end;
/* Node color. */
enum {MEM_BLACK, MEM_RED} color;
/* Memory type. */
enum mem_type type;
};
/* Root of the tree describing allocated Lisp memory. */
static struct mem_node *mem_root;
/* Lowest and highest known address in the heap. */
static void *min_heap_address, *max_heap_address;
/* Sentinel node of the tree. */
static struct mem_node mem_z;
#define MEM_NIL &mem_z
static struct mem_node *mem_insert (void *, void *, enum mem_type);
static void mem_insert_fixup (struct mem_node *);
static void mem_rotate_left (struct mem_node *);
static void mem_rotate_right (struct mem_node *);
static void mem_delete (struct mem_node *);
static void mem_delete_fixup (struct mem_node *);
static struct mem_node *mem_find (void *);
/* Addresses of staticpro'd variables. */
Lisp_Object const *staticvec[NSTATICS];
/* Index of next unused slot in staticvec. */
int staticidx;
/* Extract the pointer hidden within O. */
static ATTRIBUTE_NO_SANITIZE_UNDEFINED void *
XPNTR (Lisp_Object a)
{
return (BARE_SYMBOL_P (a)
? (char *) lispsym + (XLI (a) - LISP_WORD_TAG (Lisp_Symbol))
: (char *) XLP (a) - (XLI (a) & ~VALMASK));
}
static void
XFLOAT_INIT (Lisp_Object f, double n)
{
XFLOAT (f)->u.data = n;
}
/* Account for allocation of NBYTES in the heap. This is a separate
function to avoid hassles with implementation-defined conversion
from unsigned to signed types. */
static void
tally_consing (ptrdiff_t nbytes)
{
consing_until_gc -= nbytes;
}
#ifdef DOUG_LEA_MALLOC
static bool
pointers_fit_in_lispobj_p (void)
{
return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
}
static bool
mmap_lisp_allowed_p (void)
{
/* If we can't store all memory addresses in our lisp objects, it's
risky to let the heap use mmap and give us addresses from all
over our address space. */
return pointers_fit_in_lispobj_p ();
}
#endif
/* Head of a circularly-linked list of extant finalizers. */
struct Lisp_Finalizer finalizers;
/* Head of a circularly-linked list of finalizers that must be invoked
because we deemed them unreachable. This list must be global, and
not a local inside garbage_collect, in case we GC again while
running finalizers. */
struct Lisp_Finalizer doomed_finalizers;
/************************************************************************
Malloc
************************************************************************/
#if defined SIGDANGER || (!defined SYSTEM_MALLOC)
/* Function malloc calls this if it finds we are near exhausting storage. */
void
malloc_warning (const char *str)
{
pending_malloc_warning = str;
}
#endif
/* Display an already-pending malloc warning. */
void
display_malloc_warning (void)
{
calln (Qdisplay_warning,
Qalloc,
build_string (pending_malloc_warning),
QCemergency);
pending_malloc_warning = 0;
}
/* Called if we can't allocate relocatable space for a buffer. */
void
buffer_memory_full (ptrdiff_t nbytes)
{
/* If buffers use the relocating allocator, no need to free
spare_memory, because we may have plenty of malloc space left
that we could get, and if we don't, the malloc that fails will
itself cause spare_memory to be freed. If buffers don't use the
relocating allocator, treat this like any other failing
malloc. */
#ifndef REL_ALLOC
memory_full (nbytes);
#else
/* This used to call error, but if we've run out of memory, we could
get infinite recursion trying to build the string. */
xsignal (Qnil, Vmemory_signal_data);
#endif
}
/* A common multiple of the positive integers A and B. Ideally this
would be the least common multiple, but there's no way to do that
as a constant expression in C, so do the best that we can easily do. */
#define COMMON_MULTIPLE(a, b) \
((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
/* Alignment needed for memory blocks managed by the garbage collector. */
enum { LISP_ALIGNMENT = alignof (union { union emacs_align_type x;
GCALIGNED_UNION_MEMBER }) };
static_assert (LISP_ALIGNMENT % GCALIGNMENT == 0);
/* Emacs assumes that malloc (N) returns storage suitably aligned for
any Lisp object whenever N is a multiple of LISP_ALIGNMENT.
This Emacs assumption holds for current Emacs porting targets.
On all current Emacs porting targets, it also happens that
alignof (max_align_t) is a multiple of LISP_ALIGNMENT.
Check this with a static_assert. If the static_assert fails on an
unusual platform, Emacs may well not work, so inspect this module's
source code carefully with the unusual platform's quirks in mind.
In practice the static_assert works even for buggy platforms where
malloc can yield an unaligned address if given a large but unaligned
size; Emacs avoids the bug because it aligns the size before calling
malloc. The static_assert also works for MinGW circa 2020, where
alignof (max_align_t) is 16 even though the malloc alignment is only 8;
Emacs avoids the bug because on this platform it never does anything
that requires an alignment of 16. */
enum { MALLOC_IS_LISP_ALIGNED = alignof (max_align_t) % LISP_ALIGNMENT == 0 };
static_assert (MALLOC_IS_LISP_ALIGNED);
/* Most of Emacs does not assume PTRDIFF_MAX <= SIZE_MAX, and may use
expressions like min (PTRDIFF_MAX, SIZE_MAX) to port even to
theoretical platforms where the assumption does not hold.
However, some parts of Emacs pass nonnegative ptrdiff_t values to
allocator functions like xmalloc that expect size_t.
This is portable in practice; check it here to document the assumption. */
static_assert (PTRDIFF_MAX <= SIZE_MAX);
#define MALLOC_PROBE(size) \
do { \
if (profiler_memory_running) \
malloc_probe (size); \
} while (0)
/* Like malloc but check for no memory, and profile allocations. */
void *
xmalloc (size_t size)
{
void *val = malloc (size);
if (!val)
memory_full (size);
MALLOC_PROBE (size);
return val;
}
/* Like the above, but zero out the memory just allocated.
Calling this can be faster than allocating and zeroing,
as the calloc implementation can avoid the zeroing overhead
when obtaining memory directly from the operating system. */
void *
xzalloc (size_t size)
{
void *val = calloc (1, size);
if (!val)
memory_full (size);
MALLOC_PROBE (size);
return val;
}
/* Like xzalloc, but for an array of N objects each of size S. */
void *
xcalloc (size_t n, size_t s)
{
void *val = calloc (n, s);
if (!val)
{
size_t size;
memory_full (ckd_mul (&size, n, s) ? SIZE_MAX : size);
}
MALLOC_PROBE (n * s);
return val;
}
/* Like realloc but check for no memory, and profile allocations. */
void *
xrealloc (void *block, size_t size)
{
void *val = realloc (block, size);
if (!val)
memory_full (size);
MALLOC_PROBE (size);
return val;
}
/* Like free but do not free pdumper objects. */
void
xfree (void *block)
{
if (!block)
return;
if (pdumper_object_p (block))
return;
free (block);
/* We don't call refill_memory_reserve here
because in practice the call in r_alloc_free seems to suffice. */
}
/* Other parts of Emacs pass large int values to allocator functions
expecting ptrdiff_t. This is portable in practice, but check it to
be safe. */
static_assert (INT_MAX <= PTRDIFF_MAX);
/* Allocate an array of NITEMS items, each of size ITEM_SIZE.
Signal an error on memory exhaustion, and profile allocations. */
void *
xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
{
eassert (0 <= nitems && 0 < item_size);
ptrdiff_t nbytes;
if (ckd_mul (&nbytes, nitems, item_size) || SIZE_MAX < nbytes)
memory_full_up ();
return xmalloc (nbytes);
}
/* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
Signal an error on memory exhaustion, and profile allocations. */
void *
xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
{
eassert (0 <= nitems && 0 < item_size);
ptrdiff_t nbytes;
if (ckd_mul (&nbytes, nitems, item_size) || SIZE_MAX < nbytes)
memory_full_up ();
return xrealloc (pa, nbytes);
}
/* Grow PA, which points to an array of *NITEMS items, and return the
location of the reallocated array, updating *NITEMS to reflect its
new size. The new array will contain at least NITEMS_INCR_MIN more
items, but will not contain more than NITEMS_MAX items total.
ITEM_SIZE is the size of each item, in bytes.
ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
nonnegative. If NITEMS_MAX is -1, it is treated as if it were
infinity.
If PA is null, then allocate a new array instead of reallocating
the old one.
Profile memory allocations. If memory exhaustion occurs, set
*NITEMS to zero if PA is null, and signal an error (i.e., do not
return).
Thus, to grow an array A without saving its old contents, do
{ xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
The A = NULL avoids a dangling pointer if xpalloc exhausts memory
and signals an error, and later this code is reexecuted and
attempts to free A. */
void *
xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
ptrdiff_t nitems_max, ptrdiff_t item_size)
{
ptrdiff_t n0 = *nitems;
eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
/* The approximate size to use for initial small allocation
requests. This is the largest "small" request for the GNU C
library malloc. */
enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
/* If the array is tiny, grow it to about (but no greater than)
DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
Adjust the growth according to three constraints: NITEMS_INCR_MIN,
NITEMS_MAX, and what the C language can represent safely. */
ptrdiff_t n, nbytes;
if (ckd_add (&n, n0, n0 >> 1))
n = PTRDIFF_MAX;
if (0 <= nitems_max && nitems_max < n)
n = nitems_max;
ptrdiff_t adjusted_nbytes
= ((ckd_mul (&nbytes, n, item_size) || SIZE_MAX < nbytes)
? min (PTRDIFF_MAX, SIZE_MAX)
: nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
if (adjusted_nbytes)
{
n = adjusted_nbytes / item_size;
nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
}
if (! pa)
*nitems = 0;
if (n - n0 < nitems_incr_min
&& (ckd_add (&n, n0, nitems_incr_min)
|| (0 <= nitems_max && nitems_max < n)
|| ckd_mul (&nbytes, n, item_size)))
memory_full_up ();
pa = xrealloc (pa, nbytes);
*nitems = n;
return pa;
}
/* Like strdup, but uses xmalloc. */
char *
xstrdup (const char *s)
{
ptrdiff_t size;
eassert (s);
size = strlen (s) + 1;
return memcpy (xmalloc (size), s, size);
}
/* Like above, but duplicates Lisp string to C string. */
char *
xlispstrdup (Lisp_Object string)
{
ptrdiff_t size = SBYTES (string) + 1;
return memcpy (xmalloc (size), SSDATA (string), size);
}
/* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
pointed to. If STRING is null, assign it without copying anything.
Allocate before freeing, to avoid a dangling pointer if allocation
fails. */
void
dupstring (char **ptr, char const *string)
{
char *old = *ptr;
*ptr = string ? xstrdup (string) : 0;
xfree (old);
}
/* Like putenv, but (1) use the equivalent of xmalloc and (2) the
argument is a const pointer. */
void
xputenv (char const *string)
{
if (putenv ((char *) string) != 0)
memory_full (0);
}
/* Return a newly allocated memory block of SIZE bytes, remembering
to free it when unwinding. */
void *
record_xmalloc (size_t size)
{
void *p = xmalloc (size);
record_unwind_protect_ptr (xfree, p);
return p;
}
#if ! USE_LSB_TAG
extern void *lisp_malloc_loser;
void *lisp_malloc_loser EXTERNALLY_VISIBLE;
#endif
/* Allocate memory for Lisp data.
NBYTES is the number of bytes to allocate;
it must be a multiple of LISP_ALIGNMENT.
If CLEARIT, arrange for the allocated memory to be cleared
by using calloc, which can be faster than malloc+memset.
TYPE describes the intended use of the allocated memory block
(for strings, for conses, ...).
Return a null pointer if and only if allocation failed.
Code allocating heap memory for Lisp should use this function to get
a pointer P; that way, if T is an enum Lisp_Type value and
L == make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T. */
static void *
lisp_malloc (ptrdiff_t nbytes, bool clearit, enum mem_type type)
{
register void *val;
#ifdef GC_MALLOC_CHECK
allocated_mem_type = type;
#endif
val = clearit ? calloc (1, nbytes) : malloc (nbytes);
#if ! USE_LSB_TAG
/* If the memory just allocated cannot be addressed thru a Lisp
object's pointer, and it needs to be,
that's equivalent to running out of memory. */
if (val && type != MEM_TYPE_NON_LISP)
{
Lisp_Object tem;
XSETCONS (tem, (char *) val + nbytes - 1);
if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
{
lisp_malloc_loser = val;
free (val);
val = 0;
}
}
#endif
#ifndef GC_MALLOC_CHECK
if (val && type != MEM_TYPE_NON_LISP)
mem_insert (val, (char *) val + nbytes, type);
#endif
if (!val)
memory_full (nbytes);
MALLOC_PROBE (nbytes);
return val;
}
/* Free BLOCK. This must be called to free memory allocated with a
call to lisp_malloc. */
static void
lisp_free (void *block)
{
if (pdumper_object_p (block))
return;
#ifndef GC_MALLOC_CHECK
struct mem_node *m = mem_find (block);
#endif
free (block);
#ifndef GC_MALLOC_CHECK
mem_delete (m);
#endif
}
/***** Allocation of aligned blocks of memory to store Lisp data. *****/
/* The entry point is lisp_align_malloc which returns blocks of at most
BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
/* Byte alignment of storage blocks. */
# define BLOCK_ALIGN (1 << 15)
static_assert (POWER_OF_2 (BLOCK_ALIGN));
/* Use aligned_alloc if it or a simple substitute is available. */
#if (defined HAVE_ALIGNED_ALLOC \
|| (!defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
# define USE_ALIGNED_ALLOC 1
#elif defined HAVE_POSIX_MEMALIGN
# define USE_ALIGNED_ALLOC 1
# define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h. */
static void *
aligned_alloc (size_t alignment, size_t size)
{
/* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
Verify this for all arguments this function is given. */
static_assert (BLOCK_ALIGN % sizeof (void *) == 0
&& POWER_OF_2 (BLOCK_ALIGN / sizeof (void *)));
eassert (alignment == BLOCK_ALIGN);
void *p;
return posix_memalign (&p, alignment, size) == 0 ? p : 0;
}
#endif
/* Padding to leave at the end of a malloc'd block. This is to give
malloc a chance to minimize the amount of memory wasted to alignment.
It should be tuned to the particular malloc library used.
On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
aligned_alloc on the other hand would ideally prefer a value of 4
because otherwise, there's 1020 bytes wasted between each ablocks.
In Emacs, testing shows that those 1020 can most of the time be
efficiently used by malloc to place other objects, so a value of 0 can
still preferable unless you have a lot of aligned blocks and virtually
nothing else. */
#define BLOCK_PADDING 0
#define BLOCK_BYTES \