alloc.c 197 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Storage allocation and gc for GNU Emacs Lisp interpreter.
2

3
Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2014 Free Software
4
Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
12 13 14 15 16 17 18

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
19
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
20

21
#include <config.h>
22

23
#include <stdio.h>
24
#include <limits.h>		/* For CHAR_BIT.  */
25

26
#ifdef ENABLE_CHECKING
27
#include <signal.h>		/* For SIGABRT.  */
28 29
#endif

30
#ifdef HAVE_PTHREAD
31 32 33
#include <pthread.h>
#endif

Jim Blandy's avatar
Jim Blandy committed
34
#include "lisp.h"
35
#include "process.h"
36
#include "intervals.h"
Jim Blandy's avatar
Jim Blandy committed
37
#include "puresize.h"
38
#include "character.h"
Jim Blandy's avatar
Jim Blandy committed
39 40
#include "buffer.h"
#include "window.h"
41
#include "keyboard.h"
Jim Blandy's avatar
Jim Blandy committed
42
#include "frame.h"
43
#include "blockinput.h"
44
#include "termhooks.h"		/* For struct terminal.  */
45 46 47
#ifdef HAVE_WINDOW_SYSTEM
#include TERM_HEADER
#endif /* HAVE_WINDOW_SYSTEM */
48

49
#include <verify.h>
50
#include <execinfo.h>           /* For backtrace.  */
51

52 53 54 55
#ifdef HAVE_LINUX_SYSINFO
#include <sys/sysinfo.h>
#endif

56 57 58 59
#ifdef MSDOS
#include "dosfns.h"		/* For dos_memory_info.  */
#endif

60 61 62 63 64 65
#if (defined ENABLE_CHECKING			\
     && defined HAVE_VALGRIND_VALGRIND_H	\
     && !defined USE_VALGRIND)
# define USE_VALGRIND 1
#endif

66 67 68
#if USE_VALGRIND
#include <valgrind/valgrind.h>
#include <valgrind/memcheck.h>
69
static bool valgrind_p;
70 71
#endif

72 73 74 75 76 77
#ifdef USE_LOCAL_ALLOCATORS
# if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
#  error "Stack-allocated Lisp objects are not compatible with GCPROs"
# endif
#endif

78 79 80 81 82 83
/* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
   Doable only if GC_MARK_STACK.  */
#if ! GC_MARK_STACK
# undef GC_CHECK_MARKED_OBJECTS
#endif

Kenichi Handa's avatar
Kenichi Handa committed
84
/* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
85 86
   memory.  Can do this only if using gmalloc.c and if not checking
   marked objects.  */
Kenichi Handa's avatar
Kenichi Handa committed
87

88
#if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
89
     || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
Kenichi Handa's avatar
Kenichi Handa committed
90 91 92
#undef GC_MALLOC_CHECK
#endif

93
#include <unistd.h>
94 95
#include <fcntl.h>

Paul Eggert's avatar
Paul Eggert committed
96 97 98
#ifdef USE_GTK
# include "gtkutil.h"
#endif
99
#ifdef WINDOWSNT
Eli Zaretskii's avatar
Eli Zaretskii committed
100
#include "w32.h"
101
#include "w32heap.h"	/* for sbrk */
102 103
#endif

104
#ifdef DOUG_LEA_MALLOC
105

106
#include <malloc.h>
107

108 109 110
/* Specify maximum number of areas to mmap.  It would be nice to use a
   value that explicitly means "no limit".  */

111 112
#define MMAP_MAX_AREAS 100000000

113
#endif /* not DOUG_LEA_MALLOC */
114

115 116 117
/* Mark, unmark, query mark bit of a Lisp string.  S must be a pointer
   to a struct Lisp_String.  */

118 119
#define MARK_STRING(S)		((S)->size |= ARRAY_MARK_FLAG)
#define UNMARK_STRING(S)	((S)->size &= ~ARRAY_MARK_FLAG)
120
#define STRING_MARKED_P(S)	(((S)->size & ARRAY_MARK_FLAG) != 0)
121

122 123 124
#define VECTOR_MARK(V)		((V)->header.size |= ARRAY_MARK_FLAG)
#define VECTOR_UNMARK(V)	((V)->header.size &= ~ARRAY_MARK_FLAG)
#define VECTOR_MARKED_P(V)	(((V)->header.size & ARRAY_MARK_FLAG) != 0)
125

126 127
/* Default value of gc_cons_threshold (see below).  */

128
#define GC_DEFAULT_THRESHOLD (100000 * word_size)
129

130 131 132
/* Global variables.  */
struct emacs_globals globals;

133 134
/* Number of bytes of consing done since the last gc.  */

Dmitry Antipov's avatar
Dmitry Antipov committed
135
EMACS_INT consing_since_gc;
Jim Blandy's avatar
Jim Blandy committed
136

137 138
/* Similar minimum, computed from Vgc_cons_percentage.  */

Dmitry Antipov's avatar
Dmitry Antipov committed
139
EMACS_INT gc_relative_threshold;
140

141 142 143
/* Minimum number of bytes of consing since GC before next GC,
   when memory is full.  */

Dmitry Antipov's avatar
Dmitry Antipov committed
144
EMACS_INT memory_full_cons_threshold;
145

146
/* True during GC.  */
147

148
bool gc_in_progress;
Jim Blandy's avatar
Jim Blandy committed
149

150
/* True means abort if try to GC.
151 152 153
   This is for code which is written on the assumption that
   no GC will happen, so as to verify that assumption.  */

154
bool abort_on_gc;
155

156 157
/* Number of live and free conses etc.  */

158
static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
159
static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
160
static EMACS_INT total_free_floats, total_floats;
161

162
/* Points to memory space allocated as "spare", to be freed if we run
163 164
   out of memory.  We keep one large block, four cons-blocks, and
   two string blocks.  */
165

166
static char *spare_memory[7];
167

168 169
/* 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.  */
170

171
#define SPARE_MEMORY (1 << 14)
172

Richard M. Stallman's avatar
Richard M. Stallman committed
173 174 175 176 177
/* Initialize it to a nonzero value to force it into data space
   (rather than bss space).  That way unexec will remap it into text
   space (pure), on some systems.  We have not implemented the
   remapping on more recent systems because this is less important
   nowadays than in the days of small memories and timesharing.  */
178

Andreas Schwab's avatar
Andreas Schwab committed
179
EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
Jim Blandy's avatar
Jim Blandy committed
180
#define PUREBEG (char *) pure
181

182
/* Pointer to the pure area, and its size.  */
183

184
static char *purebeg;
185
static ptrdiff_t pure_size;
186 187 188 189

/* Number of bytes of pure storage used before pure storage overflowed.
   If this is non-zero, this implies that an overflow occurred.  */

190
static ptrdiff_t pure_bytes_used_before_overflow;
Jim Blandy's avatar
Jim Blandy committed
191

192
/* True if P points into pure space.  */
193 194

#define PURE_POINTER_P(P)					\
195
  ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
196

197
/* Index in pure at which next pure Lisp object will be allocated..  */
198

199
static ptrdiff_t pure_bytes_used_lisp;
200 201 202

/* Number of bytes allocated for non-Lisp objects in pure storage.  */

203
static ptrdiff_t pure_bytes_used_non_lisp;
204

205 206 207
/* If nonzero, this is a warning delivered by malloc and not yet
   displayed.  */

208
const char *pending_malloc_warning;
Jim Blandy's avatar
Jim Blandy committed
209

210 211 212 213 214 215 216 217 218 219 220
#if 0 /* Normally, pointer sanity only on request... */
#ifdef ENABLE_CHECKING
#define SUSPICIOUS_OBJECT_CHECKING 1
#endif
#endif

/* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
   bug is unresolved.  */
#define SUSPICIOUS_OBJECT_CHECKING 1

#ifdef SUSPICIOUS_OBJECT_CHECKING
221 222
struct suspicious_free_record
{
223 224
  void *suspicious_object;
  void *backtrace[128];
225
};
226
static void *suspicious_objects[32];
227
static int suspicious_object_index;
228
struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
229 230 231
static int suspicious_free_history_index;
/* Find the first currently-monitored suspicious pointer in range
   [begin,end) or NULL if no such pointer exists.  */
232 233
static void *find_suspicious_object_in_range (void *begin, void *end);
static void detect_suspicious_free (void *ptr);
234
#else
235 236
# define find_suspicious_object_in_range(begin, end) NULL
# define detect_suspicious_free(ptr) (void)
237 238
#endif

Jim Blandy's avatar
Jim Blandy committed
239 240 241 242 243 244 245 246
/* 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.  */

247
#if MAX_SAVE_STACK > 0
248
static char *stack_copy;
249
static ptrdiff_t stack_copy_size;
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

/* 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 */
Jim Blandy's avatar
Jim Blandy committed
271

272 273 274 275 276 277 278 279
static Lisp_Object Qconses;
static Lisp_Object Qsymbols;
static Lisp_Object Qmiscs;
static Lisp_Object Qstrings;
static Lisp_Object Qvectors;
static Lisp_Object Qfloats;
static Lisp_Object Qintervals;
static Lisp_Object Qbuffers;
280
static Lisp_Object Qstring_bytes, Qvector_slots, Qheap;
281
static Lisp_Object Qgc_cons_threshold;
282
Lisp_Object Qautomatic_gc;
283
Lisp_Object Qchar_table_extra_slots;
284

285 286
/* Hook run after GC has finished.  */

287
static Lisp_Object Qpost_gc_hook;
288

289 290
static void mark_terminals (void);
static void gc_sweep (void);
291
static Lisp_Object make_pure_vector (ptrdiff_t);
292
static void mark_buffer (struct buffer *);
293

294
#if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
295 296
static void refill_memory_reserve (void);
#endif
297 298
static void compact_small_strings (void);
static void free_large_strings (void);
299
extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
300

301 302 303
/* 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.  */
304 305 306 307 308 309 310 311 312 313

enum mem_type
{
  MEM_TYPE_NON_LISP,
  MEM_TYPE_BUFFER,
  MEM_TYPE_CONS,
  MEM_TYPE_STRING,
  MEM_TYPE_MISC,
  MEM_TYPE_SYMBOL,
  MEM_TYPE_FLOAT,
314 315 316
  /* 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.  */
317 318
  MEM_TYPE_VECTORLIKE,
  /* Special type to denote vector blocks.  */
319 320 321
  MEM_TYPE_VECTOR_BLOCK,
  /* Special type to denote reserved memory.  */
  MEM_TYPE_SPARE
322 323
};

324
#if GC_MARK_STACK || defined GC_MALLOC_CHECK
325 326 327 328

/* A unique object in pure space used to make some Lisp objects
   on free lists recognizable in O(1).  */

329
static Lisp_Object Vdead;
330
#define DEADP(x) EQ (x, Vdead)
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
#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
{
Richard M. Stallman's avatar
Richard M. Stallman committed
364 365 366 367 368 369
  /* 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;
370 371 372 373 374 375

  /* Start and end of allocated region.  */
  void *start, *end;

  /* Node color.  */
  enum {MEM_BLACK, MEM_RED} color;
376

377 378 379 380 381 382 383 384 385 386 387 388
  /* Memory type.  */
  enum mem_type type;
};

/* Base address of stack.  Set in main.  */

Lisp_Object *stack_base;

/* Root of the tree describing allocated Lisp memory.  */

static struct mem_node *mem_root;

389 390 391 392
/* Lowest and highest known address in the heap.  */

static void *min_heap_address, *max_heap_address;

393 394 395 396 397
/* Sentinel node of the tree.  */

static struct mem_node mem_z;
#define MEM_NIL &mem_z

398 399 400 401 402 403
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 *);
404
static struct mem_node *mem_find (void *);
405

406
#endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
407

408 409 410 411
#ifndef DEADP
# define DEADP(x) 0
#endif

412 413 414 415
/* Recording what needs to be marked for gc.  */

struct gcpro *gcprolist;

416 417
/* Addresses of staticpro'd variables.  Initialize it to a nonzero
   value; otherwise some compilers put it into BSS.  */
418

419
enum { NSTATICS = 2048 };
420
static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
421 422 423

/* Index of next unused slot in staticvec.  */

424
static int staticidx;
425

Paul Eggert's avatar
Paul Eggert committed
426
static void *pure_alloc (size_t, int);
427

428 429 430
/* Return X rounded to the next multiple of Y.  Arguments should not
   have side effects, as they are evaluated more than once.  Assume X
   + Y - 1 does not overflow.  Tune for Y being a power of 2.  */
431

432 433 434
#define ROUNDUP(x, y) ((y) & ((y) - 1)					\
		       ? ((x) + (y) - 1) - ((x) + (y) - 1) % (y)	\
		       : ((x) + (y) - 1) & ~ ((y) - 1))
435

436 437 438 439 440 441 442
/* Return PTR rounded up to the next multiple of ALIGNMENT.  */

static void *
ALIGN (void *ptr, int alignment)
{
  return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
}
443

444 445 446 447 448
static void
XFLOAT_INIT (Lisp_Object f, double n)
{
  XFLOAT (f)->u.data = n;
}
449

450 451 452 453 454 455 456 457 458 459 460 461
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.  We also can't use mmap for lisp objects
Paul Eggert's avatar
Paul Eggert committed
462
     if we might dump: unexec doesn't preserve the contents of mmapped
463 464 465 466
     regions.  */
  return pointers_fit_in_lispobj_p () && !might_dump;
}

Jim Blandy's avatar
Jim Blandy committed
467

468 469 470 471
/************************************************************************
				Malloc
 ************************************************************************/

472
/* Function malloc calls this if it finds we are near exhausting storage.  */
473 474

void
475
malloc_warning (const char *str)
Jim Blandy's avatar
Jim Blandy committed
476 477 478 479
{
  pending_malloc_warning = str;
}

480

481
/* Display an already-pending malloc warning.  */
482

483
void
484
display_malloc_warning (void)
Jim Blandy's avatar
Jim Blandy committed
485
{
486 487 488 489
  call3 (intern ("display-warning"),
	 intern ("alloc"),
	 build_string (pending_malloc_warning),
	 intern ("emergency"));
Jim Blandy's avatar
Jim Blandy committed
490 491
  pending_malloc_warning = 0;
}
492

493 494 495
/* Called if we can't allocate relocatable space for a buffer.  */

void
496
buffer_memory_full (ptrdiff_t nbytes)
497
{
498 499 500 501 502 503
  /* 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.  */
504 505

#ifndef REL_ALLOC
Paul Eggert's avatar
Paul Eggert committed
506
  memory_full (nbytes);
Paul Eggert's avatar
Paul Eggert committed
507
#else
508 509
  /* This used to call error, but if we've run out of memory, we could
     get infinite recursion trying to build the string.  */
510
  xsignal (Qnil, Vmemory_signal_data);
Paul Eggert's avatar
Paul Eggert committed
511
#endif
Jim Blandy's avatar
Jim Blandy committed
512 513
}

514 515 516 517 518
/* 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))
519

520
#ifndef XMALLOC_OVERRUN_CHECK
521
#define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
522
#else
523

524 525
/* Check for overrun in malloc'ed buffers by wrapping a header and trailer
   around each block.
Kim F. Storm's avatar
Kim F. Storm committed
526

527 528 529 530
   The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
   followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
   block size in little-endian order.  The trailer consists of
   XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
Kim F. Storm's avatar
Kim F. Storm committed
531 532

   The header is used to detect whether this block has been allocated
533 534
   through these functions, as some low-level libc functions may
   bypass the malloc hooks.  */
Kim F. Storm's avatar
Kim F. Storm committed
535

536
#define XMALLOC_OVERRUN_CHECK_SIZE 16
537
#define XMALLOC_OVERRUN_CHECK_OVERHEAD \
538 539 540
  (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)

/* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
541 542 543
   hold a size_t value and (2) the header size is a multiple of the
   alignment that Emacs needs for C types and for USE_LSB_TAG.  */
#define XMALLOC_BASE_ALIGNMENT				\
544
  alignof (union { long double d; intmax_t i; void *p; })
545

546
#if USE_LSB_TAG
547
# define XMALLOC_HEADER_ALIGNMENT \
548
    COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
549 550 551 552
#else
# define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
#endif
#define XMALLOC_OVERRUN_SIZE_SIZE				\
553 554 555 556
   (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t)		\
      + XMALLOC_HEADER_ALIGNMENT - 1)				\
     / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT)	\
    - XMALLOC_OVERRUN_CHECK_SIZE)
Kim F. Storm's avatar
Kim F. Storm committed
557

558 559 560 561 562
static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
  { '\x9a', '\x9b', '\xae', '\xaf',
    '\xbf', '\xbe', '\xce', '\xcf',
    '\xea', '\xeb', '\xec', '\xed',
    '\xdf', '\xde', '\x9c', '\x9d' };
563

564 565 566 567 568
static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
  { '\xaa', '\xab', '\xac', '\xad',
    '\xba', '\xbb', '\xbc', '\xbd',
    '\xca', '\xcb', '\xcc', '\xcd',
    '\xda', '\xdb', '\xdc', '\xdd' };
569

570
/* Insert and extract the block size in the header.  */
Kim F. Storm's avatar
Kim F. Storm committed
571

572 573 574 575
static void
xmalloc_put_size (unsigned char *ptr, size_t size)
{
  int i;
576
  for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
577
    {
578
      *--ptr = size & ((1 << CHAR_BIT) - 1);
579 580 581
      size >>= CHAR_BIT;
    }
}
Kim F. Storm's avatar
Kim F. Storm committed
582

583 584 585 586 587
static size_t
xmalloc_get_size (unsigned char *ptr)
{
  size_t size = 0;
  int i;
588 589
  ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
  for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
590 591 592 593 594 595
    {
      size <<= CHAR_BIT;
      size += *ptr++;
    }
  return size;
}
Kim F. Storm's avatar
Kim F. Storm committed
596 597 598 599


/* Like malloc, but wraps allocated block with header and trailer.  */

Paul Eggert's avatar
Paul Eggert committed
600
static void *
601
overrun_check_malloc (size_t size)
602
{
Kim F. Storm's avatar
Kim F. Storm committed
603
  register unsigned char *val;
604
  if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
605
    emacs_abort ();
606

607 608
  val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
  if (val)
609
    {
610
      memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
611
      val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
612
      xmalloc_put_size (val, size);
613 614
      memcpy (val + size, xmalloc_overrun_check_trailer,
	      XMALLOC_OVERRUN_CHECK_SIZE);
615
    }
Paul Eggert's avatar
Paul Eggert committed
616
  return val;
617 618
}

Kim F. Storm's avatar
Kim F. Storm committed
619 620 621 622

/* Like realloc, but checks old block for overrun, and wraps new block
   with header and trailer.  */

Paul Eggert's avatar
Paul Eggert committed
623 624
static void *
overrun_check_realloc (void *block, size_t size)
625
{
626
  register unsigned char *val = (unsigned char *) block;
627
  if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
628
    emacs_abort ();
629 630

  if (val
631
      && memcmp (xmalloc_overrun_check_header,
632
		 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
633
		 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
634
    {
635
      size_t osize = xmalloc_get_size (val);
636 637
      if (memcmp (xmalloc_overrun_check_trailer, val + osize,
		  XMALLOC_OVERRUN_CHECK_SIZE))
638
	emacs_abort ();
639
      memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
640 641
      val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
      memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
642 643
    }

644
  val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
645

646
  if (val)
647
    {
648
      memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
649
      val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
650
      xmalloc_put_size (val, size);
651 652
      memcpy (val + size, xmalloc_overrun_check_trailer,
	      XMALLOC_OVERRUN_CHECK_SIZE);
653
    }
Paul Eggert's avatar
Paul Eggert committed
654
  return val;
655 656
}

Kim F. Storm's avatar
Kim F. Storm committed
657 658
/* Like free, but checks block for overrun.  */

659
static void
Paul Eggert's avatar
Paul Eggert committed
660
overrun_check_free (void *block)
661
{
662
  unsigned char *val = (unsigned char *) block;
663 664

  if (val
665
      && memcmp (xmalloc_overrun_check_header,
666
		 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
667
		 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
668
    {
669
      size_t osize = xmalloc_get_size (val);
670 671
      if (memcmp (xmalloc_overrun_check_trailer, val + osize,
		  XMALLOC_OVERRUN_CHECK_SIZE))
672
	emacs_abort ();
673
#ifdef XMALLOC_CLEAR_FREE_MEMORY
674
      val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
675
      memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
676
#else
677
      memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
678 679
      val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
      memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
680
#endif
681 682 683 684 685 686 687 688 689 690 691 692 693
    }

  free (val);
}

#undef malloc
#undef realloc
#undef free
#define malloc overrun_check_malloc
#define realloc overrun_check_realloc
#define free overrun_check_free
#endif

694 695 696 697 698 699 700 701 702 703 704 705 706 707
/* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
   BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
   If that variable is set, block input while in one of Emacs's memory
   allocation functions.  There should be no need for this debugging
   option, since signal handlers do not allocate memory, but Emacs
   formerly allocated memory in signal handlers and this compile-time
   option remains as a way to help debug the issue should it rear its
   ugly head again.  */
#ifdef XMALLOC_BLOCK_INPUT_CHECK
bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
static void
malloc_block_input (void)
{
  if (block_input_in_memory_allocators)
708
    block_input ();
709 710 711 712 713
}
static void
malloc_unblock_input (void)
{
  if (block_input_in_memory_allocators)
714
    unblock_input ();
715 716 717
}
# define MALLOC_BLOCK_INPUT malloc_block_input ()
# define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
718
#else
719 720
# define MALLOC_BLOCK_INPUT ((void) 0)
# define MALLOC_UNBLOCK_INPUT ((void) 0)
721
#endif
Kim F. Storm's avatar
Kim F. Storm committed
722

Stefan Monnier's avatar
Stefan Monnier committed
723 724 725 726 727 728 729
#define MALLOC_PROBE(size)			\
  do {						\
    if (profiler_memory_running)		\
      malloc_probe (size);			\
  } while (0)


730
/* Like malloc but check for no memory and block interrupt input..  */
Jim Blandy's avatar
Jim Blandy committed
731

Paul Eggert's avatar
Paul Eggert committed
732
void *
733
xmalloc (size_t size)
Jim Blandy's avatar
Jim Blandy committed
734
{
Paul Eggert's avatar
Paul Eggert committed
735
  void *val;
Jim Blandy's avatar
Jim Blandy committed
736

737
  MALLOC_BLOCK_INPUT;
Paul Eggert's avatar
Paul Eggert committed
738
  val = malloc (size);
739
  MALLOC_UNBLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
740

741
  if (!val && size)
Paul Eggert's avatar
Paul Eggert committed
742
    memory_full (size);
743
  MALLOC_PROBE (size);
Jim Blandy's avatar
Jim Blandy committed
744 745 746
  return val;
}

Dmitry Antipov's avatar
Dmitry Antipov committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760
/* Like the above, but zeroes out the memory just allocated.  */

void *
xzalloc (size_t size)
{
  void *val;

  MALLOC_BLOCK_INPUT;
  val = malloc (size);
  MALLOC_UNBLOCK_INPUT;

  if (!val && size)
    memory_full (size);
  memset (val, 0, size);
761
  MALLOC_PROBE (size);
Dmitry Antipov's avatar
Dmitry Antipov committed
762 763
  return val;
}
764 765 766

/* Like realloc but check for no memory and block interrupt input..  */

Paul Eggert's avatar
Paul Eggert committed
767 768
void *
xrealloc (void *block, size_t size)
Jim Blandy's avatar
Jim Blandy committed
769
{
Paul Eggert's avatar
Paul Eggert committed
770
  void *val;
Jim Blandy's avatar
Jim Blandy committed
771

772
  MALLOC_BLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
773 774 775
  /* We must call malloc explicitly when BLOCK is 0, since some
     reallocs don't do this.  */
  if (! block)
Paul Eggert's avatar
Paul Eggert committed
776
    val = malloc (size);
Noah Friedman's avatar
Noah Friedman committed
777
  else
Paul Eggert's avatar
Paul Eggert committed
778
    val = realloc (block, size);
779
  MALLOC_UNBLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
780

Paul Eggert's avatar
Paul Eggert committed
781 782
  if (!val && size)
    memory_full (size);
783
  MALLOC_PROBE (size);
Jim Blandy's avatar
Jim Blandy committed
784 785
  return val;
}
786

787

Dave Love's avatar
Dave Love committed
788
/* Like free but block interrupt input.  */
789

790
void
Paul Eggert's avatar
Paul Eggert committed
791
xfree (void *block)
792
{
793 794
  if (!block)
    return;
795
  MALLOC_BLOCK_INPUT;
796
  free (block);
797
  MALLOC_UNBLOCK_INPUT;
798
  /* We don't call refill_memory_reserve here
799
     because in practice the call in r_alloc_free seems to suffice.  */
800 801
}

802

803 804 805 806 807 808 809 810 811 812 813 814
/* 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.  */
verify (INT_MAX <= PTRDIFF_MAX);


/* Allocate an array of NITEMS items, each of size ITEM_SIZE.
   Signal an error on memory exhaustion, and block interrupt input.  */

void *
xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
{
Paul Eggert's avatar
Paul Eggert committed
815 816
  eassert (0 <= nitems && 0 < item_size);
  if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
817 818 819 820 821 822 823 824 825 826 827
    memory_full (SIZE_MAX);
  return xmalloc (nitems * item_size);
}


/* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
   Signal an error on memory exhaustion, and block interrupt input.  */

void *
xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
{
Paul Eggert's avatar
Paul Eggert committed
828 829
  eassert (0 <= nitems && 0 < item_size);
  if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
    memory_full (SIZE_MAX);
  return xrealloc (pa, nitems * item_size);
}


/* 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
846
   the old one.
847 848 849

   Block interrupt input as needed.  If memory exhaustion occurs, set
   *NITEMS to zero if PA is null, and signal an error (i.e., do not
850 851 852 853 854 855 856
   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.  */
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

void *
xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
	 ptrdiff_t nitems_max, ptrdiff_t item_size)
{
  /* 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%.  */
  ptrdiff_t n = *nitems;
  ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
  ptrdiff_t half_again = n >> 1;
  ptrdiff_t incr_estimate = max (tiny_max, half_again);

  /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
     NITEMS_MAX, and what the C language can represent safely.  */
  ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
  ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
		     ? nitems_max : C_language_max);
  ptrdiff_t nitems_incr_max = n_max - n;
  ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));

Paul Eggert's avatar
Paul Eggert committed
882
  eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
883 884
  if (! pa)
    *nitems = 0;
Paul Eggert's avatar
Paul Eggert committed
885
  if (nitems_incr_max < incr)
886 887 888 889 890 891 892 893
    memory_full (SIZE_MAX);
  n += incr;
  pa = xrealloc (pa, n * item_size);
  *nitems = n;
  return pa;
}


894 895 896
/* Like strdup, but uses xmalloc.  */

char *