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

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2016 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 <errno.h>
24
#include <stdio.h>
25
#include <limits.h>		/* For CHAR_BIT.  */
26
#include <signal.h>		/* For SIGABRT, SIGDANGER.  */
27

28
#ifdef HAVE_PTHREAD
29 30 31
#include <pthread.h>
#endif

Jim Blandy's avatar
Jim Blandy committed
32
#include "lisp.h"
33
#include "dispextern.h"
34
#include "intervals.h"
Jim Blandy's avatar
Jim Blandy committed
35
#include "puresize.h"
36
#include "sheap.h"
37
#include "systime.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 <flexmember.h>
50
#include <verify.h>
51
#include <execinfo.h>           /* For backtrace.  */
52

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

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

61 62 63 64
#ifdef HAVE_MALLOC_H
# include <malloc.h>
#endif

65 66 67 68 69 70
#if (defined ENABLE_CHECKING			\
     && defined HAVE_VALGRIND_VALGRIND_H	\
     && !defined USE_VALGRIND)
# define USE_VALGRIND 1
#endif

71 72 73
#if USE_VALGRIND
#include <valgrind/valgrind.h>
#include <valgrind/memcheck.h>
74
static bool valgrind_p;
75 76
#endif

77
/* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.  */
78

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

83
#if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
84
     || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
Kenichi Handa's avatar
Kenichi Handa committed
85 86 87
#undef GC_MALLOC_CHECK
#endif

88
#include <unistd.h>
89 90
#include <fcntl.h>

Paul Eggert's avatar
Paul Eggert committed
91 92 93
#ifdef USE_GTK
# include "gtkutil.h"
#endif
94
#ifdef WINDOWSNT
Eli Zaretskii's avatar
Eli Zaretskii committed
95
#include "w32.h"
96
#include "w32heap.h"	/* for sbrk */
97 98
#endif

Paul Eggert's avatar
Paul Eggert committed
99 100 101 102 103 104 105 106 107 108 109 110
#if defined DOUG_LEA_MALLOC || defined GNU_LINUX
/* The address where the heap starts.  */
void *
my_heap_start (void)
{
  static void *start;
  if (! start)
    start = sbrk (0);
  return start;
}
#endif

111
#ifdef DOUG_LEA_MALLOC
112 113 114 115

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

116 117
#define MMAP_MAX_AREAS 100000000

Paul Eggert's avatar
Paul Eggert committed
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
/* A pointer to the memory allocated that copies that static data
   inside glibc's malloc.  */
static void *malloc_state_ptr;

/* 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)
    {
      my_heap_start ();
      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;
		}
	}

155 156
      if (malloc_set_state (malloc_state_ptr) != 0)
	emacs_abort ();
Paul Eggert's avatar
Paul Eggert committed
157 158 159 160 161 162
# ifndef XMALLOC_OVERRUN_CHECK
      alloc_unexec_post ();
# endif
    }
}

Paul Eggert's avatar
Paul Eggert committed
163 164
/* Declare the malloc initialization hook, which runs before 'main' starts.
   EXTERNALLY_VISIBLE works around Bug#22522.  */
Paul Eggert's avatar
Paul Eggert committed
165 166 167
# ifndef __MALLOC_HOOK_VOLATILE
#  define __MALLOC_HOOK_VOLATILE
# endif
Paul Eggert's avatar
Paul Eggert committed
168
voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
Paul Eggert's avatar
Paul Eggert committed
169 170 171
  = malloc_initialize_hook;

#endif
172

173 174 175 176 177 178 179
/* Allocator-related actions to do just before and after unexec.  */

void
alloc_unexec_pre (void)
{
#ifdef DOUG_LEA_MALLOC
  malloc_state_ptr = malloc_get_state ();
180 181
  if (!malloc_state_ptr)
    fatal ("malloc_get_state: %s", strerror (errno));
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
#endif
#ifdef HYBRID_MALLOC
  bss_sbrk_did_unexec = true;
#endif
}

void
alloc_unexec_post (void)
{
#ifdef DOUG_LEA_MALLOC
  free (malloc_state_ptr);
#endif
#ifdef HYBRID_MALLOC
  bss_sbrk_did_unexec = false;
#endif
}

199 200 201
/* Mark, unmark, query mark bit of a Lisp string.  S must be a pointer
   to a struct Lisp_String.  */

202 203
#define MARK_STRING(S)		((S)->size |= ARRAY_MARK_FLAG)
#define UNMARK_STRING(S)	((S)->size &= ~ARRAY_MARK_FLAG)
204
#define STRING_MARKED_P(S)	(((S)->size & ARRAY_MARK_FLAG) != 0)
205

206 207 208
#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)
209

210 211
/* Default value of gc_cons_threshold (see below).  */

212
#define GC_DEFAULT_THRESHOLD (100000 * word_size)
213

214 215 216
/* Global variables.  */
struct emacs_globals globals;

217 218
/* Number of bytes of consing done since the last gc.  */

Dmitry Antipov's avatar
Dmitry Antipov committed
219
EMACS_INT consing_since_gc;
Jim Blandy's avatar
Jim Blandy committed
220

221 222
/* Similar minimum, computed from Vgc_cons_percentage.  */

Dmitry Antipov's avatar
Dmitry Antipov committed
223
EMACS_INT gc_relative_threshold;
224

225 226 227
/* Minimum number of bytes of consing since GC before next GC,
   when memory is full.  */

Dmitry Antipov's avatar
Dmitry Antipov committed
228
EMACS_INT memory_full_cons_threshold;
229

230
/* True during GC.  */
231

232
bool gc_in_progress;
Jim Blandy's avatar
Jim Blandy committed
233

234 235
/* Number of live and free conses etc.  */

236
static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
237
static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
238
static EMACS_INT total_free_floats, total_floats;
239

240
/* Points to memory space allocated as "spare", to be freed if we run
241 242
   out of memory.  We keep one large block, four cons-blocks, and
   two string blocks.  */
243

244
static char *spare_memory[7];
245

246 247
/* 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.  */
248

249
#define SPARE_MEMORY (1 << 14)
250

Richard M. Stallman's avatar
Richard M. Stallman committed
251 252 253 254 255
/* 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.  */
256

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

260
/* Pointer to the pure area, and its size.  */
261

262
static char *purebeg;
263
static ptrdiff_t pure_size;
264 265 266 267

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

268
static ptrdiff_t pure_bytes_used_before_overflow;
Jim Blandy's avatar
Jim Blandy committed
269

270
/* Index in pure at which next pure Lisp object will be allocated..  */
271

272
static ptrdiff_t pure_bytes_used_lisp;
273 274 275

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

276
static ptrdiff_t pure_bytes_used_non_lisp;
277

278 279 280
/* If nonzero, this is a warning delivered by malloc and not yet
   displayed.  */

281
const char *pending_malloc_warning;
Jim Blandy's avatar
Jim Blandy committed
282

283 284 285 286 287 288 289 290 291 292 293
#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
294 295
struct suspicious_free_record
{
296 297
  void *suspicious_object;
  void *backtrace[128];
298
};
299
static void *suspicious_objects[32];
300
static int suspicious_object_index;
301
struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
302 303 304
static int suspicious_free_history_index;
/* Find the first currently-monitored suspicious pointer in range
   [begin,end) or NULL if no such pointer exists.  */
305 306
static void *find_suspicious_object_in_range (void *begin, void *end);
static void detect_suspicious_free (void *ptr);
307
#else
308 309
# define find_suspicious_object_in_range(begin, end) NULL
# define detect_suspicious_free(ptr) (void)
310 311
#endif

Jim Blandy's avatar
Jim Blandy committed
312 313 314 315 316 317 318 319
/* 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.  */

320
#if MAX_SAVE_STACK > 0
321
static char *stack_copy;
322
static ptrdiff_t stack_copy_size;
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

/* 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
344

345 346
static void mark_terminals (void);
static void gc_sweep (void);
347
static Lisp_Object make_pure_vector (ptrdiff_t);
348
static void mark_buffer (struct buffer *);
349

350
#if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
351 352
static void refill_memory_reserve (void);
#endif
353 354
static void compact_small_strings (void);
static void free_large_strings (void);
355
extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
356

357 358 359
/* 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.  */
360 361 362 363 364 365 366 367 368 369

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,
370 371 372
  /* 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.  */
373 374
  MEM_TYPE_VECTORLIKE,
  /* Special type to denote vector blocks.  */
375 376 377
  MEM_TYPE_VECTOR_BLOCK,
  /* Special type to denote reserved memory.  */
  MEM_TYPE_SPARE
378 379
};

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

383
static Lisp_Object Vdead;
384
#define DEADP(x) EQ (x, Vdead)
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
#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
418 419 420 421 422 423
  /* 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;
424 425 426 427 428 429

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

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

431 432 433 434 435 436 437 438 439 440 441 442
  /* 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;

443 444 445 446
/* Lowest and highest known address in the heap.  */

static void *min_heap_address, *max_heap_address;

447 448 449 450 451
/* Sentinel node of the tree.  */

static struct mem_node mem_z;
#define MEM_NIL &mem_z

452 453 454 455 456 457
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 *);
458
static struct mem_node *mem_find (void *);
459

460 461 462 463
#ifndef DEADP
# define DEADP(x) 0
#endif

464 465
/* Addresses of staticpro'd variables.  Initialize it to a nonzero
   value; otherwise some compilers put it into BSS.  */
466

467
enum { NSTATICS = 2048 };
468
static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
469 470 471

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

472
static int staticidx;
473

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

Paul Eggert's avatar
Paul Eggert committed
476
/* True if N is a power of 2.  N should be positive.  */
477

Paul Eggert's avatar
Paul Eggert committed
478 479 480 481 482 483 484 485 486 487
#define POWER_OF_2(n) (((n) & ((n) - 1)) == 0)

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

#define ROUNDUP(x, y) (POWER_OF_2 (y)					\
		       ? ((y) - 1 + (x)) & ~ ((y) - 1)			\
		       : ((y) - 1 + (x)) - ((y) - 1 + (x)) % (y))
488

489 490 491
/* Return PTR rounded up to the next multiple of ALIGNMENT.  */

static void *
Paul Eggert's avatar
Paul Eggert committed
492
pointer_align (void *ptr, int alignment)
493 494 495
{
  return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
}
496

Paul Eggert's avatar
Paul Eggert committed
497 498 499 500
/* Extract the pointer hidden within A, if A is not a symbol.
   If A is a symbol, extract the hidden pointer's offset from lispsym,
   converted to void *.  */

501 502
#define macro_XPNTR_OR_SYMBOL_OFFSET(a) \
  ((void *) (intptr_t) (USE_LSB_TAG ? XLI (a) - XTYPE (a) : XLI (a) & VALMASK))
Paul Eggert's avatar
Paul Eggert committed
503 504 505

/* Extract the pointer hidden within A.  */

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
#define macro_XPNTR(a) \
  ((void *) ((intptr_t) XPNTR_OR_SYMBOL_OFFSET (a) \
	     + (SYMBOLP (a) ? (char *) lispsym : NULL)))

/* For pointer access, define XPNTR and XPNTR_OR_SYMBOL_OFFSET as
   functions, as functions are cleaner and can be used in debuggers.
   Also, define them as macros if being compiled with GCC without
   optimization, for performance in that case.  The macro_* names are
   private to this section of code.  */

static ATTRIBUTE_UNUSED void *
XPNTR_OR_SYMBOL_OFFSET (Lisp_Object a)
{
  return macro_XPNTR_OR_SYMBOL_OFFSET (a);
}
static ATTRIBUTE_UNUSED void *
Paul Eggert's avatar
Paul Eggert committed
522 523
XPNTR (Lisp_Object a)
{
524
  return macro_XPNTR (a);
Paul Eggert's avatar
Paul Eggert committed
525 526
}

527 528 529 530 531
#if DEFINE_KEY_OPS_AS_MACROS
# define XPNTR_OR_SYMBOL_OFFSET(a) macro_XPNTR_OR_SYMBOL_OFFSET (a)
# define XPNTR(a) macro_XPNTR (a)
#endif

532 533 534 535 536
static void
XFLOAT_INIT (Lisp_Object f, double n)
{
  XFLOAT (f)->u.data = n;
}
537

538
#ifdef DOUG_LEA_MALLOC
539 540 541 542 543 544 545 546 547 548 549 550
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
551
     if we might dump: unexec doesn't preserve the contents of mmapped
552 553 554
     regions.  */
  return pointers_fit_in_lispobj_p () && !might_dump;
}
555
#endif
556

Daniel Colascione's avatar
Daniel Colascione committed
557 558 559 560 561 562 563 564 565
/* Head of a circularly-linked list of extant finalizers. */
static 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_1, in case we GC again while
   running finalizers.  */
static struct Lisp_Finalizer doomed_finalizers;

Jim Blandy's avatar
Jim Blandy committed
566

567 568 569 570
/************************************************************************
				Malloc
 ************************************************************************/

571 572
#if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)

573
/* Function malloc calls this if it finds we are near exhausting storage.  */
574 575

void
576
malloc_warning (const char *str)
Jim Blandy's avatar
Jim Blandy committed
577 578 579 580
{
  pending_malloc_warning = str;
}

581
#endif
582

583
/* Display an already-pending malloc warning.  */
584

585
void
586
display_malloc_warning (void)
Jim Blandy's avatar
Jim Blandy committed
587
{
588 589 590 591
  call3 (intern ("display-warning"),
	 intern ("alloc"),
	 build_string (pending_malloc_warning),
	 intern ("emergency"));
Jim Blandy's avatar
Jim Blandy committed
592 593
  pending_malloc_warning = 0;
}
594

595 596 597
/* Called if we can't allocate relocatable space for a buffer.  */

void
598
buffer_memory_full (ptrdiff_t nbytes)
599
{
600 601 602 603 604 605
  /* 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.  */
606 607

#ifndef REL_ALLOC
Paul Eggert's avatar
Paul Eggert committed
608
  memory_full (nbytes);
Paul Eggert's avatar
Paul Eggert committed
609
#else
610 611
  /* This used to call error, but if we've run out of memory, we could
     get infinite recursion trying to build the string.  */
612
  xsignal (Qnil, Vmemory_signal_data);
Paul Eggert's avatar
Paul Eggert committed
613
#endif
Jim Blandy's avatar
Jim Blandy committed
614 615
}

616 617 618 619 620
/* 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))
621

622
#ifndef XMALLOC_OVERRUN_CHECK
623
#define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
624
#else
625

626 627
/* 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
628

629 630 631 632
   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
633 634

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

638
#define XMALLOC_OVERRUN_CHECK_SIZE 16
639
#define XMALLOC_OVERRUN_CHECK_OVERHEAD \
640 641
  (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)

642
#define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
643

644 645
#define XMALLOC_HEADER_ALIGNMENT \
   COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
Paul Eggert's avatar
Paul Eggert committed
646 647 648 649

/* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
   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.  */
650
#define XMALLOC_OVERRUN_SIZE_SIZE				\
651 652 653 654
   (((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
655

656 657 658 659 660
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' };
661

662 663 664 665 666
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' };
667

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

670 671 672 673
static void
xmalloc_put_size (unsigned char *ptr, size_t size)
{
  int i;
674
  for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
675
    {
676
      *--ptr = size & ((1 << CHAR_BIT) - 1);
677 678 679
      size >>= CHAR_BIT;
    }
}
Kim F. Storm's avatar
Kim F. Storm committed
680

681 682 683 684 685
static size_t
xmalloc_get_size (unsigned char *ptr)
{
  size_t size = 0;
  int i;
686 687
  ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
  for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
688 689 690 691 692 693
    {
      size <<= CHAR_BIT;
      size += *ptr++;
    }
  return size;
}
Kim F. Storm's avatar
Kim F. Storm committed
694 695 696 697


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

Paul Eggert's avatar
Paul Eggert committed
698
static void *
699
overrun_check_malloc (size_t size)
700
{
Kim F. Storm's avatar
Kim F. Storm committed
701
  register unsigned char *val;
702
  if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
703
    emacs_abort ();
704

705 706
  val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
  if (val)
707
    {
708
      memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
709
      val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
710
      xmalloc_put_size (val, size);
711 712
      memcpy (val + size, xmalloc_overrun_check_trailer,
	      XMALLOC_OVERRUN_CHECK_SIZE);
713
    }
Paul Eggert's avatar
Paul Eggert committed
714
  return val;
715 716
}

Kim F. Storm's avatar
Kim F. Storm committed
717 718 719 720

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

Paul Eggert's avatar
Paul Eggert committed
721 722
static void *
overrun_check_realloc (void *block, size_t size)
723
{
724
  register unsigned char *val = (unsigned char *) block;
725
  if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
726
    emacs_abort ();
727 728

  if (val
729
      && memcmp (xmalloc_overrun_check_header,
730
		 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
731
		 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
732
    {
733
      size_t osize = xmalloc_get_size (val);
734 735
      if (memcmp (xmalloc_overrun_check_trailer, val + osize,
		  XMALLOC_OVERRUN_CHECK_SIZE))
736
	emacs_abort ();
737
      memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
738 739
      val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
      memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
740 741
    }

742
  val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
743

744
  if (val)
745
    {
746
      memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
747
      val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
748
      xmalloc_put_size (val, size);
749 750
      memcpy (val + size, xmalloc_overrun_check_trailer,
	      XMALLOC_OVERRUN_CHECK_SIZE);
751
    }
Paul Eggert's avatar
Paul Eggert committed
752
  return val;
753 754
}

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

757
static void
Paul Eggert's avatar
Paul Eggert committed
758
overrun_check_free (void *block)
759
{
760
  unsigned char *val = (unsigned char *) block;
761 762

  if (val
763
      && memcmp (xmalloc_overrun_check_header,
764
		 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
765
		 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
766
    {
767
      size_t osize = xmalloc_get_size (val);
768 769
      if (memcmp (xmalloc_overrun_check_trailer, val + osize,
		  XMALLOC_OVERRUN_CHECK_SIZE))
770
	emacs_abort ();
771
#ifdef XMALLOC_CLEAR_FREE_MEMORY
772
      val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
773
      memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
774
#else
775
      memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
776 777
      val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
      memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
778
#endif
779 780 781 782 783 784 785 786 787 788 789 790 791
    }

  free (val);
}

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

792 793 794 795 796 797 798 799 800 801 802 803 804 805
/* 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)
806
    block_input ();
807 808 809 810 811
}
static void
malloc_unblock_input (void)
{
  if (block_input_in_memory_allocators)
812
    unblock_input ();
813 814 815
}
# define MALLOC_BLOCK_INPUT malloc_block_input ()
# define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
816
#else
817 818
# define MALLOC_BLOCK_INPUT ((void) 0)
# define MALLOC_UNBLOCK_INPUT ((void) 0)
819
#endif
Kim F. Storm's avatar
Kim F. Storm committed
820

Stefan Monnier's avatar
Stefan Monnier committed
821 822 823 824 825 826
#define MALLOC_PROBE(size)			\
  do {						\
    if (profiler_memory_running)		\
      malloc_probe (size);			\
  } while (0)

Paul Eggert's avatar
Paul Eggert committed
827 828
static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
static void *lrealloc (void *, size_t);
Stefan Monnier's avatar
Stefan Monnier committed
829

Paul Eggert's avatar
Paul Eggert committed
830
/* Like malloc but check for no memory and block interrupt input.  */
Jim Blandy's avatar
Jim Blandy committed
831

Paul Eggert's avatar
Paul Eggert committed
832
void *
833
xmalloc (size_t size)
Jim Blandy's avatar
Jim Blandy committed
834
{
Paul Eggert's avatar
Paul Eggert committed
835
  void *val;
Jim Blandy's avatar
Jim Blandy committed
836

837
  MALLOC_BLOCK_INPUT;
Paul Eggert's avatar
Paul Eggert committed
838
  val = lmalloc (size);
839
  MALLOC_UNBLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
840

841
  if (!val && size)
Paul Eggert's avatar
Paul Eggert committed
842
    memory_full (size);
843
  MALLOC_PROBE (size);
Jim Blandy's avatar
Jim Blandy committed
844 845 846
  return val;
}

Dmitry Antipov's avatar
Dmitry Antipov committed
847 848 849 850 851 852 853 854
/* Like the above, but zeroes out the memory just allocated.  */

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

  MALLOC_BLOCK_INPUT;
Paul Eggert's avatar
Paul Eggert committed
855
  val = lmalloc (size);
Dmitry Antipov's avatar
Dmitry Antipov committed
856 857 858 859 860
  MALLOC_UNBLOCK_INPUT;

  if (!val && size)
    memory_full (size);
  memset (val, 0, size);
861
  MALLOC_PROBE (size);
Dmitry Antipov's avatar
Dmitry Antipov committed
862 863
  return val;
}
864 865 866

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

Paul Eggert's avatar
Paul Eggert committed
867 868
void *
xrealloc (void *block, size_t size)
Jim Blandy's avatar
Jim Blandy committed
869
{
Paul Eggert's avatar
Paul Eggert committed
870
  void *val;
Jim Blandy's avatar
Jim Blandy committed
871

872
  MALLOC_BLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
873 874 875
  /* 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
876
    val = lmalloc (size);
Noah Friedman's avatar
Noah Friedman committed
877
  else
Paul Eggert's avatar
Paul Eggert committed
878
    val = lrealloc (block, size);
879
  MALLOC_UNBLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
880

Paul Eggert's avatar
Paul Eggert committed
881 882
  if (!val && size)
    memory_full (size);
883
  MALLOC_PROBE (size);
Jim Blandy's avatar
Jim Blandy committed
884 885
  return val;
}
886

887

Dave Love's avatar
Dave Love committed
888
/* Like free but block interrupt input.  */
889

890
void
Paul Eggert's avatar
Paul Eggert committed
891
xfree (void *block)
892
{
893 894
  if (!block)
    return;
895
  MALLOC_BLOCK_INPUT;
896
  free (block);
897
  MALLOC_UNBLOCK_INPUT;
898
  /* We don't call refill_memory_reserve here
899
     because in practice the call in r_alloc_free seems to suffice.  */
900 901
}

902

903 904 905 906 907 908 909 910 911 912 913 914
/* 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
915
  eassert (0 <= nitems && 0 < item_size);
916 917
  ptrdiff_t nbytes;
  if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
918
    memory_full (SIZE_MAX);
919
  return xmalloc (nbytes);
920 921 922 923 924 925 926 927 928
}


/* 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
929
  eassert (0 <= nitems && 0 < item_size);
930 931
  ptrdiff_t nbytes;
  if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
932
    memory_full (SIZE_MAX);
933
  return xrealloc (pa, nbytes);
934 935 936 937 938 939 940 941 942 943 944 945 946 947
}


/* 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
948
   the old one.
949 950 951

   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
952 953 954 955 956 957 958
   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.  */
959 960 961 962 963

void *
xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
	 ptrdiff_t nitems_max, ptrdiff_t item_size)
{
964 965 966
  ptrdiff_t n0 = *nitems;
  eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);

967 968 969 970 971 972
  /* 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)
973 974
     DEFAULT_MXFAST bytes.  Otherwise, grow it by about 50%.
     Adjust the growth according to three constraints: NITEMS_INCR_MIN,
975 976
     NITEMS_MAX, and what the C language can represent safely.  */

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991