alloc.c 116 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Storage allocation and gc for GNU Emacs Lisp interpreter.
2
   Copyright (C) 1985, 86, 88, 93, 94, 95, 97, 98, 1999, 2000
Richard M. Stallman's avatar
Richard M. Stallman committed
3
      Free Software Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4 5 6 7 8

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
9
the Free Software Foundation; either version 2, or (at your option)
Jim Blandy's avatar
Jim Blandy committed
10 11 12 13 14 15 16 17 18
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; see the file COPYING.  If not, write to
19 20
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */
Jim Blandy's avatar
Jim Blandy committed
21

22
#include <config.h>
23

24
/* Note that this declares bzero on OSF/1.  How dumb.  */
25

26
#include <signal.h>
27

28 29 30
/* This file is part of the core Lisp implementation, and thus must
   deal with the real data structures.  If the Lisp implementation is
   replaced, this file likely will not be used.  */
31

32
#undef HIDE_LISP_IMPLEMENTATION
Jim Blandy's avatar
Jim Blandy committed
33
#include "lisp.h"
34
#include "intervals.h"
Jim Blandy's avatar
Jim Blandy committed
35
#include "puresize.h"
Jim Blandy's avatar
Jim Blandy committed
36 37
#include "buffer.h"
#include "window.h"
Jim Blandy's avatar
Jim Blandy committed
38
#include "frame.h"
39
#include "blockinput.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
40
#include "keyboard.h"
41
#include "charset.h"
Jim Blandy's avatar
Jim Blandy committed
42
#include "syssignal.h"
43
#include <setjmp.h>
Jim Blandy's avatar
Jim Blandy committed
44

Karl Heuer's avatar
Karl Heuer committed
45 46
extern char *sbrk ();

47
#ifdef DOUG_LEA_MALLOC
48

49 50
#include <malloc.h>
#define __malloc_size_t int
51

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

55 56
#define MMAP_MAX_AREAS 100000000

57 58
#else /* not DOUG_LEA_MALLOC */

59 60 61 62 63 64 65 66 67 68
/* The following come from gmalloc.c.  */

#if defined (__STDC__) && __STDC__
#include <stddef.h>
#define	__malloc_size_t		size_t
#else
#define	__malloc_size_t		unsigned int
#endif
extern __malloc_size_t _bytes_used;
extern int __malloc_extra_blocks;
69 70

#endif /* not DOUG_LEA_MALLOC */
71

Jim Blandy's avatar
Jim Blandy committed
72
#define max(A,B) ((A) > (B) ? (A) : (B))
73
#define min(A,B) ((A) < (B) ? (A) : (B))
Jim Blandy's avatar
Jim Blandy committed
74 75 76 77 78

/* Macro to verify that storage intended for Lisp objects is not
   out of range to fit in the space for a pointer.
   ADDRESS is the start of the block, and SIZE
   is the amount of space within which objects can start.  */
79

Jim Blandy's avatar
Jim Blandy committed
80 81 82 83
#define VALIDATE_LISP_STORAGE(address, size)			\
do								\
  {								\
    Lisp_Object val;						\
84
    XSETCONS (val, (char *) address + size);		\
Jim Blandy's avatar
Jim Blandy committed
85 86
    if ((char *) XCONS (val) != (char *) address + size)	\
      {								\
87
	xfree (address);					\
Jim Blandy's avatar
Jim Blandy committed
88 89 90 91
	memory_full ();						\
      }								\
  } while (0)

92
/* Value of _bytes_used, when spare_memory was freed.  */
93

94 95
static __malloc_size_t bytes_used_when_full;

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
/* Mark, unmark, query mark bit of a Lisp string.  S must be a pointer
   to a struct Lisp_String.  */

#define MARK_STRING(S)		XMARK ((S)->size)
#define UNMARK_STRING(S)	XUNMARK ((S)->size)
#define STRING_MARKED_P(S)	XMARKBIT ((S)->size)

/* Value is the number of bytes/chars of S, a pointer to a struct
   Lisp_String.  This must be used instead of STRING_BYTES (S) or
   S->size during GC, because S->size contains the mark bit for
   strings.  */

#define GC_STRING_BYTES(S)	(STRING_BYTES (S) & ~MARKBIT)
#define GC_STRING_CHARS(S)	((S)->size & ~MARKBIT)

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

Jim Blandy's avatar
Jim Blandy committed
113 114
int consing_since_gc;

115
/* Count the amount of consing of various sorts of space.  */
116

117 118 119 120 121 122 123
int cons_cells_consed;
int floats_consed;
int vector_cells_consed;
int symbols_consed;
int string_chars_consed;
int misc_objects_consed;
int intervals_consed;
124 125 126
int strings_consed;

/* Number of bytes of consing since GC before another GC should be done. */
127

128
int gc_cons_threshold;
Jim Blandy's avatar
Jim Blandy committed
129

130 131
/* Nonzero during GC.  */

Jim Blandy's avatar
Jim Blandy committed
132 133
int gc_in_progress;

134
/* Nonzero means display messages at beginning and end of GC.  */
135

136 137
int garbage_collection_messages;

Jim Blandy's avatar
Jim Blandy committed
138 139 140
#ifndef VIRT_ADDR_VARIES
extern
#endif /* VIRT_ADDR_VARIES */
141
int malloc_sbrk_used;
Jim Blandy's avatar
Jim Blandy committed
142 143 144 145

#ifndef VIRT_ADDR_VARIES
extern
#endif /* VIRT_ADDR_VARIES */
146
int malloc_sbrk_unused;
Jim Blandy's avatar
Jim Blandy committed
147

Jim Blandy's avatar
Jim Blandy committed
148
/* Two limits controlling how much undo information to keep.  */
149

Jim Blandy's avatar
Jim Blandy committed
150 151
int undo_limit;
int undo_strong_limit;
Jim Blandy's avatar
Jim Blandy committed
152

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

static int total_conses, total_markers, total_symbols, total_vector_size;
static int total_free_conses, total_free_markers, total_free_symbols;
static int total_free_floats, total_floats;
158

159 160 161
/* Points to memory space allocated as "spare", to be freed if we run
   out of memory.  */

162 163 164
static char *spare_memory;

/* Amount of spare memory to keep in reserve.  */
165

166 167 168
#define SPARE_MEMORY (1 << 14)

/* Number of extra blocks malloc should get when it needs more core.  */
169

170 171
static int malloc_hysteresis;

172 173 174
/* Nonzero when malloc is called for allocating Lisp object space.
   Currently set but not used.  */

Karl Heuer's avatar
Karl Heuer committed
175 176
int allocating_for_lisp;

177 178
/* Non-nil means defun should do purecopy on the function definition.  */

Jim Blandy's avatar
Jim Blandy committed
179 180 181
Lisp_Object Vpurify_flag;

#ifndef HAVE_SHM
182 183 184 185

/* Force it into data space! */

EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
Jim Blandy's avatar
Jim Blandy committed
186
#define PUREBEG (char *) pure
187 188 189

#else /* not HAVE_SHM */

Jim Blandy's avatar
Jim Blandy committed
190 191
#define pure PURE_SEG_BITS   /* Use shared memory segment */
#define PUREBEG (char *)PURE_SEG_BITS
Jim Blandy's avatar
Jim Blandy committed
192 193 194

/* This variable is used only by the XPNTR macro when HAVE_SHM is
   defined.  If we used the PURESIZE macro directly there, that would
195
   make most of Emacs dependent on puresize.h, which we don't want -
Jim Blandy's avatar
Jim Blandy committed
196 197 198
   you should be able to change that without too much recompilation.
   So map_in_data initializes pure_size, and the dependencies work
   out.  */
199

200
EMACS_INT pure_size;
201

Jim Blandy's avatar
Jim Blandy committed
202 203
#endif /* not HAVE_SHM */

204 205 206 207 208 209 210 211
/* Value is non-zero if P points into pure space.  */

#define PURE_POINTER_P(P)					\
     (((PNTR_COMPARISON_TYPE) (P)				\
       < (PNTR_COMPARISON_TYPE) ((char *) pure + PURESIZE))	\
      && ((PNTR_COMPARISON_TYPE) (P)				\
	  >= (PNTR_COMPARISON_TYPE) pure))

212 213
/* Index in pure at which next pure object will be allocated.. */

Jim Blandy's avatar
Jim Blandy committed
214 215
int pureptr;

216 217 218
/* If nonzero, this is a warning delivered by malloc and not yet
   displayed.  */

Jim Blandy's avatar
Jim Blandy committed
219 220
char *pending_malloc_warning;

221
/* Pre-computed signal argument for use when memory is exhausted.  */
222

223
Lisp_Object memory_signal_data;
224

Jim Blandy's avatar
Jim Blandy committed
225 226 227 228 229 230 231 232 233 234 235
/* 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.  */

char *stack_copy;
int stack_copy_size;

236 237 238
/* Non-zero means ignore malloc warnings.  Set during initialization.
   Currently not used.  */

Jim Blandy's avatar
Jim Blandy committed
239
int ignore_warnings;
Joseph Arceneaux's avatar
Joseph Arceneaux committed
240

241
Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
242

243 244 245
static void mark_buffer P_ ((Lisp_Object));
static void mark_kboards P_ ((void));
static void gc_sweep P_ ((void));
246 247 248 249 250 251 252 253
static void mark_glyph_matrix P_ ((struct glyph_matrix *));
static void mark_face_cache P_ ((struct face_cache *));

#ifdef HAVE_WINDOW_SYSTEM
static void mark_image P_ ((struct image *));
static void mark_image_cache P_ ((struct frame *));
#endif /* HAVE_WINDOW_SYSTEM */

254 255 256 257
static struct Lisp_String *allocate_string P_ ((void));
static void compact_small_strings P_ ((void));
static void free_large_strings P_ ((void));
static void sweep_strings P_ ((void));
Richard M. Stallman's avatar
Richard M. Stallman committed
258 259

extern int message_enable_multibyte;
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

/* When scanning the C stack for live Lisp objects, Emacs keeps track
   of what memory allocated via lisp_malloc is intended for what
   purpose.  This enumeration specifies the type of memory.  */

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,
  MEM_TYPE_VECTOR
};

277 278 279 280 281 282 283 284 285 286 287
#if GC_MARK_STACK

#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
#include <stdio.h>		/* For fprintf.  */
#endif

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

Lisp_Object Vdead;

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
struct mem_node;
static void *lisp_malloc P_ ((int, enum mem_type));
static void mark_stack P_ ((void));
static void init_stack P_ ((Lisp_Object *));
static int live_vector_p P_ ((struct mem_node *, void *));
static int live_buffer_p P_ ((struct mem_node *, void *));
static int live_string_p P_ ((struct mem_node *, void *));
static int live_cons_p P_ ((struct mem_node *, void *));
static int live_symbol_p P_ ((struct mem_node *, void *));
static int live_float_p P_ ((struct mem_node *, void *));
static int live_misc_p P_ ((struct mem_node *, void *));
static void mark_memory P_ ((void *, void *));
static void mem_init P_ ((void));
static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
static void mem_insert_fixup P_ ((struct mem_node *));
static void mem_rotate_left P_ ((struct mem_node *));
static void mem_rotate_right P_ ((struct mem_node *));
static void mem_delete P_ ((struct mem_node *));
static void mem_delete_fixup P_ ((struct mem_node *));
static INLINE struct mem_node *mem_find P_ ((void *));

#if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
static void check_gcpros P_ ((void));
#endif

#endif /* GC_MARK_STACK != 0 */

Jim Blandy's avatar
Jim Blandy committed
315

316 317 318 319 320 321
/************************************************************************
				Malloc
 ************************************************************************/

/* Write STR to Vstandard_output plus some advice on how to free some
   memory.  Called when memory gets low.  */
322

Jim Blandy's avatar
Jim Blandy committed
323 324 325 326 327 328 329 330 331 332 333
Lisp_Object
malloc_warning_1 (str)
     Lisp_Object str;
{
  Fprinc (str, Vstandard_output);
  write_string ("\nKilling some buffers may delay running out of memory.\n", -1);
  write_string ("However, certainly by the time you receive the 95% warning,\n", -1);
  write_string ("you should clean up, kill this Emacs, and start a new one.", -1);
  return Qnil;
}

334 335 336

/* Function malloc calls this if it finds we are near exhausting
   storage.  */
337 338

void
Jim Blandy's avatar
Jim Blandy committed
339 340 341 342 343 344
malloc_warning (str)
     char *str;
{
  pending_malloc_warning = str;
}

345 346 347

/* Display a malloc warning in buffer *Danger*.  */

348
void
Jim Blandy's avatar
Jim Blandy committed
349 350 351 352 353 354 355 356 357
display_malloc_warning ()
{
  register Lisp_Object val;

  val = build_string (pending_malloc_warning);
  pending_malloc_warning = 0;
  internal_with_output_to_temp_buffer (" *Danger*", malloc_warning_1, val);
}

358

359
#ifdef DOUG_LEA_MALLOC
360
#  define BYTES_USED (mallinfo ().arena)
361
#else
362
#  define BYTES_USED _bytes_used
363 364
#endif

365

366
/* Called if malloc returns zero.  */
367

368
void
Jim Blandy's avatar
Jim Blandy committed
369 370
memory_full ()
{
371
#ifndef SYSTEM_MALLOC
372
  bytes_used_when_full = BYTES_USED;
373 374 375 376 377 378 379 380 381
#endif

  /* The first time we get here, free the spare memory.  */
  if (spare_memory)
    {
      free (spare_memory);
      spare_memory = 0;
    }

382 383
  /* This used to call error, but if we've run out of memory, we could
     get infinite recursion trying to build the string.  */
384
  while (1)
385
    Fsignal (Qnil, memory_signal_data);
386 387
}

388

389 390 391 392 393
/* Called if we can't allocate relocatable space for a buffer.  */

void
buffer_memory_full ()
{
394 395 396 397 398 399
  /* 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.  */
400 401 402 403 404

#ifndef REL_ALLOC
  memory_full ();
#endif

405 406
  /* This used to call error, but if we've run out of memory, we could
     get infinite recursion trying to build the string.  */
407 408
  while (1)
    Fsignal (Qerror, memory_signal_data);
Jim Blandy's avatar
Jim Blandy committed
409 410
}

411 412

/* Like malloc but check for no memory and block interrupt input..  */
Jim Blandy's avatar
Jim Blandy committed
413 414 415 416 417 418 419

long *
xmalloc (size)
     int size;
{
  register long *val;

420
  BLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
421
  val = (long *) malloc (size);
422
  UNBLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
423

424 425
  if (!val && size)
    memory_full ();
Jim Blandy's avatar
Jim Blandy committed
426 427 428
  return val;
}

429 430 431

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

Jim Blandy's avatar
Jim Blandy committed
432 433 434 435 436 437 438
long *
xrealloc (block, size)
     long *block;
     int size;
{
  register long *val;

439
  BLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
440 441 442 443
  /* We must call malloc explicitly when BLOCK is 0, since some
     reallocs don't do this.  */
  if (! block)
    val = (long *) malloc (size);
Noah Friedman's avatar
Noah Friedman committed
444
  else
Jim Blandy's avatar
Jim Blandy committed
445
    val = (long *) realloc (block, size);
446
  UNBLOCK_INPUT;
Jim Blandy's avatar
Jim Blandy committed
447 448 449 450

  if (!val && size) memory_full ();
  return val;
}
451

452 453 454

/* Like free but block interrupt input..  */

455 456 457 458 459 460 461 462 463
void
xfree (block)
     long *block;
{
  BLOCK_INPUT;
  free (block);
  UNBLOCK_INPUT;
}

464

465 466 467 468 469 470 471 472
/* Like malloc but used for allocating Lisp data.  NBYTES is the
   number of bytes to allocate, TYPE describes the intended use of the
   allcated memory block (for strings, for conses, ...).  */

static void *
lisp_malloc (nbytes, type)
     int nbytes;
     enum mem_type type;
473
{
474
  register void *val;
475 476 477

  BLOCK_INPUT;
  allocating_for_lisp++;
478
  val = (void *) malloc (nbytes);
479 480 481
  allocating_for_lisp--;
  UNBLOCK_INPUT;

482 483 484 485 486 487 488 489
  if (!val && nbytes)
    memory_full ();
  
#if GC_MARK_STACK
  if (type != MEM_TYPE_NON_LISP)
    mem_insert (val, (char *) val + nbytes, type);
#endif
  
490 491 492
  return val;
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

/* Return a new buffer structure allocated from the heap with
   a call to lisp_malloc.  */

struct buffer *
allocate_buffer ()
{
  return (struct buffer *) lisp_malloc (sizeof (struct buffer),
					MEM_TYPE_BUFFER);
}


/* Free BLOCK.  This must be called to free memory allocated with a
   call to lisp_malloc.  */

508 509 510 511 512 513 514
void
lisp_free (block)
     long *block;
{
  BLOCK_INPUT;
  allocating_for_lisp++;
  free (block);
515 516 517
#if GC_MARK_STACK
  mem_delete (mem_find (block));
#endif
518 519 520
  allocating_for_lisp--;
  UNBLOCK_INPUT;
}
521

522 523 524 525 526 527 528 529 530 531 532 533

/* Arranging to disable input signals while we're in malloc.

   This only works with GNU malloc.  To help out systems which can't
   use GNU malloc, all the calls to malloc, realloc, and free
   elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
   pairs; unfortunately, we have no idea what C library functions
   might call malloc, so we can't really protect them unless you're
   using GNU malloc.  Fortunately, most of the major operating can use
   GNU malloc.  */

#ifndef SYSTEM_MALLOC
534

535 536 537 538 539 540
extern void * (*__malloc_hook) ();
static void * (*old_malloc_hook) ();
extern void * (*__realloc_hook) ();
static void * (*old_realloc_hook) ();
extern void (*__free_hook) ();
static void (*old_free_hook) ();
541

542 543
/* This function is used as the hook for free to call.  */

544 545 546 547 548 549 550
static void
emacs_blocked_free (ptr)
     void *ptr;
{
  BLOCK_INPUT;
  __free_hook = old_free_hook;
  free (ptr);
551 552 553 554 555 556 557 558 559
  /* If we released our reserve (due to running out of memory),
     and we have a fair amount free once again,
     try to set aside another reserve in case we run out once more.  */
  if (spare_memory == 0
      /* Verify there is enough space that even with the malloc
	 hysteresis this call won't run out again.
	 The code here is correct as long as SPARE_MEMORY
	 is substantially larger than the block size malloc uses.  */
      && (bytes_used_when_full
560
	  > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
561 562
    spare_memory = (char *) malloc (SPARE_MEMORY);

563
  __free_hook = emacs_blocked_free;
564 565 566
  UNBLOCK_INPUT;
}

567

568 569 570 571 572 573 574 575 576 577 578 579 580
/* If we released our reserve (due to running out of memory),
   and we have a fair amount free once again,
   try to set aside another reserve in case we run out once more.

   This is called when a relocatable block is freed in ralloc.c.  */

void
refill_memory_reserve ()
{
  if (spare_memory == 0)
    spare_memory = (char *) malloc (SPARE_MEMORY);
}

581

582 583
/* This function is the malloc hook that Emacs uses.  */

584 585 586 587 588 589 590 591
static void *
emacs_blocked_malloc (size)
     unsigned size;
{
  void *value;

  BLOCK_INPUT;
  __malloc_hook = old_malloc_hook;
592
#ifdef DOUG_LEA_MALLOC
593
    mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
594
#else
595
    __malloc_extra_blocks = malloc_hysteresis;
596
#endif
597
  value = (void *) malloc (size);
598
  __malloc_hook = emacs_blocked_malloc;
599 600 601 602 603
  UNBLOCK_INPUT;

  return value;
}

604 605 606

/* This function is the realloc hook that Emacs uses.  */

607 608 609 610 611 612 613 614 615
static void *
emacs_blocked_realloc (ptr, size)
     void *ptr;
     unsigned size;
{
  void *value;

  BLOCK_INPUT;
  __realloc_hook = old_realloc_hook;
616
  value = (void *) realloc (ptr, size);
617
  __realloc_hook = emacs_blocked_realloc;
618 619 620 621 622
  UNBLOCK_INPUT;

  return value;
}

623 624 625

/* Called from main to set up malloc to use our hooks.  */

626 627 628
void
uninterrupt_malloc ()
{
629 630
  if (__free_hook != emacs_blocked_free)
    old_free_hook = __free_hook;
631
  __free_hook = emacs_blocked_free;
632

633 634
  if (__malloc_hook != emacs_blocked_malloc)
    old_malloc_hook = __malloc_hook;
635
  __malloc_hook = emacs_blocked_malloc;
636

637 638
  if (__realloc_hook != emacs_blocked_realloc)
    old_realloc_hook = __realloc_hook;
639
  __realloc_hook = emacs_blocked_realloc;
640
}
641 642 643 644

#endif /* not SYSTEM_MALLOC */


Jim Blandy's avatar
Jim Blandy committed
645

646 647 648
/***********************************************************************
			 Interval Allocation
 ***********************************************************************/
649

650 651 652
/* Number of intervals allocated in an interval_block structure.
   The 1020 is 1024 minus malloc overhead.  */

653 654 655
#define INTERVAL_BLOCK_SIZE \
  ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))

656 657 658
/* Intervals are allocated in chunks in form of an interval_block
   structure.  */

659
struct interval_block
660 661 662 663
{
  struct interval_block *next;
  struct interval intervals[INTERVAL_BLOCK_SIZE];
};
664

665 666 667
/* Current interval block.  Its `next' pointer points to older
   blocks.  */

668
struct interval_block *interval_block;
669 670 671 672

/* Index in interval_block above of the next unused interval
   structure.  */

673
static int interval_block_index;
674 675 676

/* Number of free and live intervals.  */

677
static int total_free_intervals, total_intervals;
678

679 680
/* List of free intervals.  */

681 682
INTERVAL interval_free_list;

683
/* Total number of interval blocks now in use.  */
684

685 686
int n_interval_blocks;

687 688 689

/* Initialize interval allocation.  */

690 691 692 693
static void
init_intervals ()
{
  interval_block
694 695
    = (struct interval_block *) lisp_malloc (sizeof *interval_block,
					     MEM_TYPE_NON_LISP);
696
  interval_block->next = 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
697
  bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
698 699
  interval_block_index = 0;
  interval_free_list = 0;
700
  n_interval_blocks = 1;
701 702
}

703 704

/* Return a new interval.  */
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

INTERVAL
make_interval ()
{
  INTERVAL val;

  if (interval_free_list)
    {
      val = interval_free_list;
      interval_free_list = interval_free_list->parent;
    }
  else
    {
      if (interval_block_index == INTERVAL_BLOCK_SIZE)
	{
Karl Heuer's avatar
Karl Heuer committed
720 721
	  register struct interval_block *newi;

722 723
	  newi = (struct interval_block *) lisp_malloc (sizeof *newi,
							MEM_TYPE_NON_LISP);
724 725 726 727 728

	  VALIDATE_LISP_STORAGE (newi, sizeof *newi);
	  newi->next = interval_block;
	  interval_block = newi;
	  interval_block_index = 0;
729
	  n_interval_blocks++;
730 731 732 733
	}
      val = &interval_block->intervals[interval_block_index++];
    }
  consing_since_gc += sizeof (struct interval);
734
  intervals_consed++;
735 736 737 738
  RESET_INTERVAL (val);
  return val;
}

739 740

/* Mark Lisp objects in interval I. */
741 742

static void
743
mark_interval (i, dummy)
744
     register INTERVAL i;
745
     Lisp_Object dummy;
746 747 748 749 750 751 752
{
  if (XMARKBIT (i->plist))
    abort ();
  mark_object (&i->plist);
  XMARK (i->plist);
}

753 754 755 756

/* Mark the interval tree rooted in TREE.  Don't call this directly;
   use the macro MARK_INTERVAL_TREE instead.  */

757 758 759 760
static void
mark_interval_tree (tree)
     register INTERVAL tree;
{
761 762 763 764 765 766 767
  /* No need to test if this tree has been marked already; this
     function is always called through the MARK_INTERVAL_TREE macro,
     which takes care of that.  */

  /* XMARK expands to an assignment; the LHS of an assignment can't be
     a cast.  */
  XMARK (* (Lisp_Object *) &tree->parent);
768

769
  traverse_intervals (tree, 1, 0, mark_interval, Qnil);
770 771
}

772 773 774

/* Mark the interval tree rooted in I.  */

775 776 777
#define MARK_INTERVAL_TREE(i)				\
  do {							\
    if (!NULL_INTERVAL_P (i)				\
778
	&& ! XMARKBIT (*(Lisp_Object *) &i->parent))	\
779 780
      mark_interval_tree (i);				\
  } while (0)
781

782

783
/* The oddity in the call to XUNMARK is necessary because XUNMARK
784 785 786 787 788 789 790 791 792 793 794
   expands to an assignment to its argument, and most C compilers
   don't support casts on the left operand of `='.  */

#define UNMARK_BALANCE_INTERVALS(i)			\
  do {							\
   if (! NULL_INTERVAL_P (i))				\
     {							\
       XUNMARK (* (Lisp_Object *) (&(i)->parent));	\
       (i) = balance_intervals (i);			\
     }							\
  } while (0)
795

796

797

798 799 800
/***********************************************************************
			  String Allocation
 ***********************************************************************/
801

802 803 804 805 806 807
/* Lisp_Strings are allocated in string_block structures.  When a new
   string_block is allocated, all the Lisp_Strings it contains are
   added to a free-list stiing_free_list.  When a new Lisp_String is
   needed, it is taken from that list.  During the sweep phase of GC,
   string_blocks that are entirely free are freed, except two which
   we keep.
Jim Blandy's avatar
Jim Blandy committed
808

809 810 811
   String data is allocated from sblock structures.  Strings larger
   than LARGE_STRING_BYTES, get their own sblock, data for smaller
   strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
Jim Blandy's avatar
Jim Blandy committed
812

813 814 815 816
   Sblocks consist internally of sdata structures, one for each
   Lisp_String.  The sdata structure points to the Lisp_String it
   belongs to.  The Lisp_String points back to the `u.data' member of
   its sdata structure.
Jim Blandy's avatar
Jim Blandy committed
817

818 819 820 821 822 823
   When a Lisp_String is freed during GC, it is put back on
   string_free_list, and its `data' member and its sdata's `string'
   pointer is set to null.  The size of the string is recorded in the
   `u.nbytes' member of the sdata.  So, sdata structures that are no
   longer used, can be easily recognized, and it's easy to compact the
   sblocks of small strings which we do in compact_small_strings.  */
Jim Blandy's avatar
Jim Blandy committed
824

825 826
/* Size in bytes of an sblock structure used for small strings.  This
   is 8192 minus malloc overhead.  */
Jim Blandy's avatar
Jim Blandy committed
827

828
#define SBLOCK_SIZE 8188
829

830 831
/* Strings larger than this are considered large strings.  String data
   for large strings is allocated from individual sblocks.  */
Jim Blandy's avatar
Jim Blandy committed
832

833 834 835 836 837 838
#define LARGE_STRING_BYTES 1024

/* Structure describing string memory sub-allocated from an sblock.
   This is where the contents of Lisp strings are stored.  */

struct sdata
Jim Blandy's avatar
Jim Blandy committed
839
{
840 841
  /* Back-pointer to the string this sdata belongs to.  If null, this
     structure is free, and the NBYTES member of the union below
842
     contains the string's byte size (the same value that STRING_BYTES
843 844 845 846
     would return if STRING were non-null).  If non-null, STRING_BYTES
     (STRING) is the size of the data, and DATA contains the string's
     contents.  */
  struct Lisp_String *string;
Jim Blandy's avatar
Jim Blandy committed
847

848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
  union
  {
    /* When STRING in non-null.  */
    unsigned char data[1];

    /* When STRING is null.  */
    EMACS_INT nbytes;
  } u;
};

/* Structure describing a block of memory which is sub-allocated to
   obtain string data memory for strings.  Blocks for small strings
   are of fixed size SBLOCK_SIZE.  Blocks for large strings are made
   as large as needed.  */

struct sblock
Jim Blandy's avatar
Jim Blandy committed
864
{
865 866
  /* Next in list.  */
  struct sblock *next;
Jim Blandy's avatar
Jim Blandy committed
867

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
  /* Pointer to the next free sdata block.  This points past the end
     of the sblock if there isn't any space left in this block.  */
  struct sdata *next_free;

  /* Start of data.  */
  struct sdata first_data;
};

/* Number of Lisp strings in a string_block structure.  The 1020 is
   1024 minus malloc overhead.  */

#define STRINGS_IN_STRING_BLOCK \
  ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))

/* Structure describing a block from which Lisp_String structures
   are allocated.  */

struct string_block
Jim Blandy's avatar
Jim Blandy committed
886
{
887 888 889
  struct string_block *next;
  struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
};
Jim Blandy's avatar
Jim Blandy committed
890

891 892 893
/* Head and tail of the list of sblock structures holding Lisp string
   data.  We always allocate from current_sblock.  The NEXT pointers
   in the sblock structures go from oldest_sblock to current_sblock.  */
Karl Heuer's avatar
Karl Heuer committed
894

895
static struct sblock *oldest_sblock, *current_sblock;
Jim Blandy's avatar
Jim Blandy committed
896

897
/* List of sblocks for large strings.  */
Jim Blandy's avatar
Jim Blandy committed
898

899
static struct sblock *large_sblocks;
Jim Blandy's avatar
Jim Blandy committed
900

901
/* List of string_block structures, and how many there are.  */
Jim Blandy's avatar
Jim Blandy committed
902

903 904
static struct string_block *string_blocks;
static int n_string_blocks;
Jim Blandy's avatar
Jim Blandy committed
905

906
/* Free-list of Lisp_Strings.  */
Jim Blandy's avatar
Jim Blandy committed
907

908
static struct Lisp_String *string_free_list;
Jim Blandy's avatar
Jim Blandy committed
909

910
/* Number of live and free Lisp_Strings.  */
911

912
static int total_strings, total_free_strings;
Jim Blandy's avatar
Jim Blandy committed
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
/* Number of bytes used by live strings.  */

static int total_string_size;

/* Given a pointer to a Lisp_String S which is on the free-list
   string_free_list, return a pointer to its successor in the
   free-list.  */

#define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))

/* Return a pointer to the sdata structure belonging to Lisp string S.
   S must be live, i.e. S->data must not be null.  S->data is actually
   a pointer to the `u.data' member of its sdata structure; the
   structure starts at a constant offset in front of that.  */
   
#define SDATA_OF_STRING(S) \
     ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))

/* Value is the size of an sdata structure large enough to hold NBYTES
   bytes of string data.  The value returned includes a terminating
   NUL byte, the size of the sdata structure, and padding.  */

#define SDATA_SIZE(NBYTES)			\
     ((sizeof (struct Lisp_String *)		\
       + (NBYTES) + 1				\
       + sizeof (EMACS_INT) - 1)		\
      & ~(sizeof (EMACS_INT) - 1))


/* Initialize string allocation.  Called from init_alloc_once.  */
944 945

void
946
init_strings ()
Jim Blandy's avatar
Jim Blandy committed
947
{
948 949 950 951 952
  total_strings = total_free_strings = total_string_size = 0;
  oldest_sblock = current_sblock = large_sblocks = NULL;
  string_blocks = NULL;
  n_string_blocks = 0;
  string_free_list = NULL;
Jim Blandy's avatar
Jim Blandy committed
953 954
}

955 956 957 958 959

/* Return a new Lisp_String.  */

static struct Lisp_String *
allocate_string ()
Jim Blandy's avatar
Jim Blandy committed
960
{
961
  struct Lisp_String *s;
Jim Blandy's avatar
Jim Blandy committed
962

963 964 965
  /* If the free-list is empty, allocate a new string_block, and
     add all the Lisp_Strings in it to the free-list.  */
  if (string_free_list == NULL)
Jim Blandy's avatar
Jim Blandy committed
966
    {
967 968 969
      struct string_block *b;
      int i;

970
      b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
971 972 973 974 975 976 977
      VALIDATE_LISP_STORAGE (b, sizeof *b);
      bzero (b, sizeof *b);
      b->next = string_blocks;
      string_blocks = b;
      ++n_string_blocks;

      for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
Jim Blandy's avatar
Jim Blandy committed
978
	{
979 980 981
	  s = b->strings + i;
	  NEXT_FREE_LISP_STRING (s) = string_free_list;
	  string_free_list = s;
Jim Blandy's avatar
Jim Blandy committed
982
	}
983 984

      total_free_strings += STRINGS_IN_STRING_BLOCK;
Jim Blandy's avatar
Jim Blandy committed
985
    }
986

987 988 989
  /* Pop a Lisp_String off the free-list.  */
  s = string_free_list;
  string_free_list = NEXT_FREE_LISP_STRING (s);
990

991 992
  /* Probably not strictly necessary, but play it safe.  */
  bzero (s, sizeof *s);
993

994 995 996 997
  --total_free_strings;
  ++total_strings;
  ++strings_consed;
  consing_since_gc += sizeof *s;
998

999
  return s;
1000
}
Jim Blandy's avatar
Jim Blandy committed
1001 1002


1003 1004 1005 1006 1007
/* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
   plus a NUL byte at the end.  Allocate an sdata structure for S, and
   set S->data to its `u.data' member.  Store a NUL byte at the end of
   S->data.  Set S->size to NCHARS and S->size_byte to NBYTES.  Free
   S->data if it was initially non-null.  */
Jim Blandy's avatar
Jim Blandy committed
1008

1009 1010 1011 1012
void
allocate_string_data (s, nchars, nbytes)
     struct Lisp_String *s;
     int nchars, nbytes;
Jim Blandy's avatar
Jim Blandy committed
1013
{
1014 1015 1016
  struct sdata *data;
  struct sblock *b;
  int needed;
Jim Blandy's avatar
Jim Blandy committed
1017

1018 1019 1020
  /* Determine the number of bytes needed to store NBYTES bytes
     of string data.  */
  needed = SDATA_SIZE (nbytes);
Jim Blandy's avatar
Jim Blandy committed
1021

1022 1023 1024 1025 1026 1027 1028 1029 1030
  if (nbytes > LARGE_STRING_BYTES)
    {
      int size = sizeof *b - sizeof (struct sdata) + needed;

#ifdef DOUG_LEA_MALLOC
      /* Prevent mmap'ing the chunk (which is potentially very large). */
      mallopt (M_MMAP_MAX, 0);
#endif

1031
      b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
      
#ifdef DOUG_LEA_MALLOC
      /* Back to a reasonable maximum of mmap'ed areas. */
      mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
#endif
  
      b->next_free = &b->first_data;
      b->first_data.string = NULL;
      b->next = large_sblocks;
      large_sblocks = b;
    }
  else if (current_sblock == NULL
	   || (((char *) current_sblock + SBLOCK_SIZE
		- (char *) current_sblock->next_free)
	       < needed))
    {
      /* Not enough room in the current sblock.  */
1049
      b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
      b->next_free = &b->first_data;
      b->first_data.string = NULL;
      b->next = NULL;

      if (current_sblock)
	current_sblock->next = b;
      else
	oldest_sblock = b;
      current_sblock = b;
    }
  else
    b = current_sblock;
      
  /* If S had already data assigned, mark that as free by setting
     its string back-pointer to null, and recording the size of
     the data in it..  */
  if (s->data)
    {
      data = SDATA_OF_STRING (s);
      data->u.nbytes = GC_STRING_BYTES (s);
      data->string = NULL;
    }
  
  data = b->next_free;
  data->string = s;
  s->data = data->u.data;
  s->size = nchars;
  s->size_byte = nbytes;
  s->data[nbytes] = '\0';
  b->next_free = (struct sdata *) ((char *) data + needed);
  
  consing_since_gc += needed;
}


/* Sweep and compact strings.  */

static void
sweep_strings ()
{
  struct string_block *b, *next;
  struct string_block *live_blocks = NULL;
  
  string_free_list = NULL;
  total_strings = total_free_strings = 0;
  total_string_size = 0;

  /* Scan strings_blocks, free Lisp_Strings that aren't marked.  */
  for (b = string_blocks; b; b = next)
    {
      int i, nfree = 0;
      struct Lisp_String *free_list_before = string_free_list;

      next = b->next;

      for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
	{
	  struct Lisp_String *s = b->strings + i;

	  if (s->data)
	    {
	      /* String was not on free-list before.  */
	      if (STRING_MARKED_P (s))
		{
		  /* String is live; unmark it and its intervals.  */
		  UNMARK_STRING (s);
		  
		  if (!NULL_INTERVAL_P (s->intervals))
		    UNMARK_BALANCE_INTERVALS (s->intervals);

		  ++total_strings;
		  total_string_size += STRING_BYTES (s);
		}
	      else
		{
		  /* String is dead.  Put it on the free-list.  */
		  struct sdata *data = SDATA_OF_STRING (s);

		  /* Save the size of S in its sdata so that we know
		     how large that is.  Reset the sdata's string
		     back-pointer so that we know it's free.  */
		  data->u.nbytes = GC_STRING_BYTES (s);
		  data->string = NULL;

		  /* Reset the strings's `data' member so that we
		     know it's free.  */
		  s->data = NULL;

		  /* Put the string on the free-list.  */
		  NEXT_FREE_LISP_STRING (s) = string_free_list;
		  string_free_list = s;
		  ++nfree;
		}
	    }
	  else
	    {
	      /* S was on the free-list before.  Put it there again.  */
	      NEXT_FREE_LISP_STRING (s) = string_free_list;
	      string_free_list = s;
	      ++nfree;
	    }
	}

1153
      /* Free blocks that contain free Lisp_Strings only, except
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181