]> code.delx.au - gnu-emacs/blobdiff - src/alloc.c
(lgrep, rgrep): Use add-to-history.
[gnu-emacs] / src / alloc.c
index c42453d90628e0326aa44ca3a037d11bce40e948..1d3dc10c411bd00863ec7bf99f9afd9df5fe835f 100644 (file)
@@ -1,6 +1,6 @@
 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
-   Copyright (C) 1985, 86, 88, 93, 94, 95, 97, 98, 1999, 2000, 2001, 2002, 2003
-      Free Software Foundation, Inc.
+   Copyright (C) 1985, 1986, 1988, 1993, 1994, 1995, 1997, 1998, 1999,
+      2000, 2001, 2002, 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
 
 This file is part of GNU Emacs.
 
@@ -16,11 +16,16 @@ 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
-the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-Boston, MA 02111-1307, USA.  */
+the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+Boston, MA 02110-1301, USA.  */
 
 #include <config.h>
 #include <stdio.h>
+#include <limits.h>            /* For CHAR_BIT.  */
+
+#ifdef STDC_HEADERS
+#include <stddef.h>            /* For offsetof, used by PSEUDOVECSIZE. */
+#endif
 
 #ifdef ALLOC_DEBUG
 #undef INLINE
@@ -30,11 +35,8 @@ Boston, MA 02111-1307, USA.  */
 
 #include <signal.h>
 
-/* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
-   memory.  Can do this only if using gmalloc.c.  */
-
-#if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
-#undef GC_MALLOC_CHECK
+#ifdef HAVE_GTK_AND_PTHREAD
+#include <pthread.h>
 #endif
 
 /* This file is part of the core Lisp implementation, and thus must
@@ -55,12 +57,27 @@ Boston, MA 02111-1307, USA.  */
 #include "syssignal.h"
 #include <setjmp.h>
 
+/* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
+   memory.  Can do this only if using gmalloc.c.  */
+
+#if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
+#undef GC_MALLOC_CHECK
+#endif
+
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #else
 extern POINTER_TYPE *sbrk ();
 #endif
 
+#ifdef HAVE_FCNTL_H
+#define INCLUDED_FCNTL
+#include <fcntl.h>
+#endif
+#ifndef O_WRONLY
+#define O_WRONLY 1
+#endif
+
 #ifdef DOUG_LEA_MALLOC
 
 #include <malloc.h>
@@ -84,24 +101,75 @@ extern __malloc_size_t __malloc_extra_blocks;
 
 #endif /* not DOUG_LEA_MALLOC */
 
+#if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
+
+/* When GTK uses the file chooser dialog, different backends can be loaded
+   dynamically.  One such a backend is the Gnome VFS backend that gets loaded
+   if you run Gnome.  That backend creates several threads and also allocates
+   memory with malloc.
+
+   If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
+   functions below are called from malloc, there is a chance that one
+   of these threads preempts the Emacs main thread and the hook variables
+   end up in an inconsistent state.  So we have a mutex to prevent that (note
+   that the backend handles concurrent access to malloc within its own threads
+   but Emacs code running in the main thread is not included in that control).
+
+   When UNBLOCK_INPUT is called, reinvoke_input_signal may be called.  If this
+   happens in one of the backend threads we will have two threads that tries
+   to run Emacs code at once, and the code is not prepared for that.
+   To prevent that, we only call BLOCK/UNBLOCK from the main thread.  */
+
+static pthread_mutex_t alloc_mutex;
+
+#define BLOCK_INPUT_ALLOC                       \
+  do                                            \
+    {                                           \
+      pthread_mutex_lock (&alloc_mutex);        \
+      if (pthread_self () == main_thread)       \
+        BLOCK_INPUT;                            \
+    }                                           \
+  while (0)
+#define UNBLOCK_INPUT_ALLOC                     \
+  do                                            \
+    {                                           \
+      if (pthread_self () == main_thread)       \
+        UNBLOCK_INPUT;                          \
+      pthread_mutex_unlock (&alloc_mutex);      \
+    }                                           \
+  while (0)
+
+#else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
+
+#define BLOCK_INPUT_ALLOC BLOCK_INPUT
+#define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
+
+#endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
+
 /* Value of _bytes_used, when spare_memory was freed.  */
 
 static __malloc_size_t bytes_used_when_full;
 
+static __malloc_size_t bytes_used_when_reconsidered;
+
 /* Mark, unmark, query mark bit of a Lisp string.  S must be a pointer
    to a struct Lisp_String.  */
 
-#define MARK_STRING(S)         ((S)->size |= MARKBIT)
-#define UNMARK_STRING(S)       ((S)->size &= ~MARKBIT)
-#define STRING_MARKED_P(S)     ((S)->size & MARKBIT)
+#define MARK_STRING(S)         ((S)->size |= ARRAY_MARK_FLAG)
+#define UNMARK_STRING(S)       ((S)->size &= ~ARRAY_MARK_FLAG)
+#define STRING_MARKED_P(S)     (((S)->size & ARRAY_MARK_FLAG) != 0)
+
+#define VECTOR_MARK(V)         ((V)->size |= ARRAY_MARK_FLAG)
+#define VECTOR_UNMARK(V)       ((V)->size &= ~ARRAY_MARK_FLAG)
+#define VECTOR_MARKED_P(V)     (((V)->size & ARRAY_MARK_FLAG) != 0)
 
 /* 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)
+#define GC_STRING_BYTES(S)     (STRING_BYTES (S))
+#define GC_STRING_CHARS(S)     ((S)->size & ~ARRAY_MARK_FLAG)
 
 /* Number of bytes of consing done since the last gc.  */
 
@@ -118,10 +186,21 @@ EMACS_INT misc_objects_consed;
 EMACS_INT intervals_consed;
 EMACS_INT strings_consed;
 
-/* Number of bytes of consing since GC before another GC should be done. */
+/* Minimum number of bytes of consing since GC before next GC. */
 
 EMACS_INT gc_cons_threshold;
 
+/* Similar minimum, computed from Vgc_cons_percentage.  */
+
+EMACS_INT gc_relative_threshold;
+
+static Lisp_Object Vgc_cons_percentage;
+
+/* Minimum number of bytes of consing since GC before next GC,
+   when memory is full.  */
+
+EMACS_INT memory_full_cons_threshold;
+
 /* Nonzero during GC.  */
 
 int gc_in_progress;
@@ -146,11 +225,6 @@ extern
 #endif /* VIRT_ADDR_VARIES */
 int malloc_sbrk_unused;
 
-/* Two limits controlling how much undo information to keep.  */
-
-EMACS_INT undo_limit;
-EMACS_INT undo_strong_limit;
-
 /* Number of live and free conses etc.  */
 
 static int total_conses, total_markers, total_symbols, total_vector_size;
@@ -158,11 +232,12 @@ static int total_free_conses, total_free_markers, total_free_symbols;
 static int total_free_floats, total_floats;
 
 /* Points to memory space allocated as "spare", to be freed if we run
-   out of memory.  */
+   out of memory.  We keep one large block, four cons-blocks, and
+   two string blocks.  */
 
-static char *spare_memory;
+char *spare_memory[7];
 
-/* Amount of spare memory to keep in reserve.  */
+/* Amount of spare memory to keep in large reserve block.  */
 
 #define SPARE_MEMORY (1 << 14)
 
@@ -180,9 +255,13 @@ Lisp_Object Vmemory_full;
 
 #ifndef HAVE_SHM
 
-/* Force it into data space! */
+/* 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.  */
 
-EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
+EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {1,};
 #define PUREBEG (char *) pure
 
 #else /* HAVE_SHM */
@@ -249,12 +328,14 @@ Lisp_Object Vgc_elapsed;  /* accumulated elapsed time in GC  */
 EMACS_INT gcs_done;            /* accumulated GCs  */
 
 static void mark_buffer P_ ((Lisp_Object));
-static void mark_kboards P_ ((void));
+extern void mark_kboards P_ ((void));
+extern void mark_backtrace P_ ((void));
 static void gc_sweep P_ ((void));
 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
 static void mark_face_cache P_ ((struct face_cache *));
 
 #ifdef HAVE_WINDOW_SYSTEM
+extern void mark_fringe_data P_ ((void));
 static void mark_image P_ ((struct image *));
 static void mark_image_cache P_ ((struct frame *));
 #endif /* HAVE_WINDOW_SYSTEM */
@@ -289,6 +370,11 @@ enum mem_type
   MEM_TYPE_WINDOW
 };
 
+static POINTER_TYPE *lisp_align_malloc P_ ((size_t, enum mem_type));
+static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
+void refill_memory_reserve ();
+
+
 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
 
 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
@@ -389,6 +475,7 @@ 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
@@ -399,10 +486,11 @@ static void check_gcpros P_ ((void));
 
 struct gcpro *gcprolist;
 
-/* Addresses of staticpro'd variables.  */
+/* Addresses of staticpro'd variables.  Initialize it to a nonzero
+   value; otherwise some compilers put it into BSS.  */
 
 #define NSTATICS 1280
-Lisp_Object *staticvec[NSTATICS] = {0};
+Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
 
 /* Index of next unused slot in staticvec.  */
 
@@ -414,8 +502,9 @@ static POINTER_TYPE *pure_alloc P_ ((size_t, int));
 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
    ALIGNMENT must be a power of 2.  */
 
-#define ALIGN(SZ, ALIGNMENT) \
-  (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
+#define ALIGN(ptr, ALIGNMENT) \
+  ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
+                    & ~((ALIGNMENT) - 1)))
 
 
 \f
@@ -447,37 +536,11 @@ display_malloc_warning ()
 
 
 #ifdef DOUG_LEA_MALLOC
-#  define BYTES_USED (mallinfo ().arena)
+#  define BYTES_USED (mallinfo ().uordblks)
 #else
 #  define BYTES_USED _bytes_used
 #endif
-
-
-/* Called if malloc returns zero.  */
-
-void
-memory_full ()
-{
-  Vmemory_full = Qt;
-
-#ifndef SYSTEM_MALLOC
-  bytes_used_when_full = BYTES_USED;
-#endif
-
-  /* The first time we get here, free the spare memory.  */
-  if (spare_memory)
-    {
-      free (spare_memory);
-      spare_memory = 0;
-    }
-
-  /* This used to call error, but if we've run out of memory, we could
-     get infinite recursion trying to build the string.  */
-  while (1)
-    Fsignal (Qnil, Vmemory_signal_data);
-}
-
-
+\f
 /* Called if we can't allocate relocatable space for a buffer.  */
 
 void
@@ -494,8 +557,6 @@ buffer_memory_full ()
   memory_full ();
 #endif
 
-  Vmemory_full = Qt;
-
   /* This used to call error, but if we've run out of memory, we could
      get infinite recursion trying to build the string.  */
   while (1)
@@ -503,6 +564,174 @@ buffer_memory_full ()
 }
 
 
+#ifdef XMALLOC_OVERRUN_CHECK
+
+/* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
+   and a 16 byte trailer around each block.
+
+   The header consists of 12 fixed bytes + a 4 byte integer contaning the
+   original block size, while the trailer consists of 16 fixed bytes.
+
+   The header is used to detect whether this block has been allocated
+   through these functions -- as it seems that some low-level libc
+   functions may bypass the malloc hooks.
+*/
+
+
+#define XMALLOC_OVERRUN_CHECK_SIZE 16
+
+static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
+  { 0x9a, 0x9b, 0xae, 0xaf,
+    0xbf, 0xbe, 0xce, 0xcf,
+    0xea, 0xeb, 0xec, 0xed };
+
+static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
+  { 0xaa, 0xab, 0xac, 0xad,
+    0xba, 0xbb, 0xbc, 0xbd,
+    0xca, 0xcb, 0xcc, 0xcd,
+    0xda, 0xdb, 0xdc, 0xdd };
+
+/* Macros to insert and extract the block size in the header.  */
+
+#define XMALLOC_PUT_SIZE(ptr, size)    \
+  (ptr[-1] = (size & 0xff),            \
+   ptr[-2] = ((size >> 8) & 0xff),     \
+   ptr[-3] = ((size >> 16) & 0xff),    \
+   ptr[-4] = ((size >> 24) & 0xff))
+
+#define XMALLOC_GET_SIZE(ptr)                  \
+  (size_t)((unsigned)(ptr[-1])         |       \
+          ((unsigned)(ptr[-2]) << 8)   |       \
+          ((unsigned)(ptr[-3]) << 16)  |       \
+          ((unsigned)(ptr[-4]) << 24))
+
+
+/* The call depth in overrun_check functions.  For example, this might happen:
+   xmalloc()
+     overrun_check_malloc()
+       -> malloc -> (via hook)_-> emacs_blocked_malloc
+          -> overrun_check_malloc
+             call malloc  (hooks are NULL, so real malloc is called).
+             malloc returns 10000.
+             add overhead, return 10016.
+      <- (back in overrun_check_malloc)
+      add overhead again, return 10032
+   xmalloc returns 10032.
+
+   (time passes).
+
+   xfree(10032)
+     overrun_check_free(10032)
+       decrease overhed
+       free(10016)  <-  crash, because 10000 is the original pointer.  */
+
+static int check_depth;
+
+/* Like malloc, but wraps allocated block with header and trailer.  */
+
+POINTER_TYPE *
+overrun_check_malloc (size)
+     size_t size;
+{
+  register unsigned char *val;
+  size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
+
+  val = (unsigned char *) malloc (size + overhead);
+  if (val && check_depth == 1)
+    {
+      bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
+      val += XMALLOC_OVERRUN_CHECK_SIZE;
+      XMALLOC_PUT_SIZE(val, size);
+      bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
+    }
+  --check_depth;
+  return (POINTER_TYPE *)val;
+}
+
+
+/* Like realloc, but checks old block for overrun, and wraps new block
+   with header and trailer.  */
+
+POINTER_TYPE *
+overrun_check_realloc (block, size)
+     POINTER_TYPE *block;
+     size_t size;
+{
+  register unsigned char *val = (unsigned char *)block;
+  size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
+
+  if (val
+      && check_depth == 1
+      && bcmp (xmalloc_overrun_check_header,
+              val - XMALLOC_OVERRUN_CHECK_SIZE,
+              XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
+    {
+      size_t osize = XMALLOC_GET_SIZE (val);
+      if (bcmp (xmalloc_overrun_check_trailer,
+               val + osize,
+               XMALLOC_OVERRUN_CHECK_SIZE))
+       abort ();
+      bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
+      val -= XMALLOC_OVERRUN_CHECK_SIZE;
+      bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
+    }
+
+  val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
+
+  if (val && check_depth == 1)
+    {
+      bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
+      val += XMALLOC_OVERRUN_CHECK_SIZE;
+      XMALLOC_PUT_SIZE(val, size);
+      bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
+    }
+  --check_depth;
+  return (POINTER_TYPE *)val;
+}
+
+/* Like free, but checks block for overrun.  */
+
+void
+overrun_check_free (block)
+     POINTER_TYPE *block;
+{
+  unsigned char *val = (unsigned char *)block;
+
+  ++check_depth;
+  if (val
+      && check_depth == 1
+      && bcmp (xmalloc_overrun_check_header,
+              val - XMALLOC_OVERRUN_CHECK_SIZE,
+              XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
+    {
+      size_t osize = XMALLOC_GET_SIZE (val);
+      if (bcmp (xmalloc_overrun_check_trailer,
+               val + osize,
+               XMALLOC_OVERRUN_CHECK_SIZE))
+       abort ();
+#ifdef XMALLOC_CLEAR_FREE_MEMORY
+      val -= XMALLOC_OVERRUN_CHECK_SIZE;
+      memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
+#else
+      bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
+      val -= XMALLOC_OVERRUN_CHECK_SIZE;
+      bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
+#endif
+    }
+
+  free (val);
+  --check_depth;
+}
+
+#undef malloc
+#undef realloc
+#undef free
+#define malloc overrun_check_malloc
+#define realloc overrun_check_realloc
+#define free overrun_check_free
+#endif
+
+
 /* Like malloc but check for no memory and block interrupt input..  */
 
 POINTER_TYPE *
@@ -544,7 +773,7 @@ xrealloc (block, size)
 }
 
 
-/* Like free but block interrupt input..  */
+/* Like free but block interrupt input.  */
 
 void
 xfree (block)
@@ -553,6 +782,9 @@ xfree (block)
   BLOCK_INPUT;
   free (block);
   UNBLOCK_INPUT;
+  /* We don't call refill_memory_reserve here
+     because that duplicates doing so in emacs_blocked_free
+     and the criterion should go there.  */
 }
 
 
@@ -569,11 +801,29 @@ xstrdup (s)
 }
 
 
+/* Unwind for SAFE_ALLOCA */
+
+Lisp_Object
+safe_alloca_unwind (arg)
+     Lisp_Object arg;
+{
+  register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
+
+  p->dogc = 0;
+  xfree (p->pointer);
+  p->pointer = 0;
+  free_misc (arg);
+  return Qnil;
+}
+
+
 /* 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, ...).  */
 
+#ifndef USE_LSB_TAG
 static void *lisp_malloc_loser;
+#endif
 
 static POINTER_TYPE *
 lisp_malloc (nbytes, type)
@@ -590,6 +840,7 @@ lisp_malloc (nbytes, type)
 
   val = (void *) malloc (nbytes);
 
+#ifndef USE_LSB_TAG
   /* If the memory just allocated cannot be addressed thru a Lisp
      object's pointer, and it needs to be,
      that's equivalent to running out of memory.  */
@@ -604,6 +855,7 @@ lisp_malloc (nbytes, type)
          val = 0;
        }
     }
+#endif
 
 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
   if (val && type != MEM_TYPE_NON_LISP)
@@ -616,64 +868,308 @@ lisp_malloc (nbytes, type)
   return val;
 }
 
+/* Free BLOCK.  This must be called to free memory allocated with a
+   call to lisp_malloc.  */
 
-/* Return a new buffer structure allocated from the heap with
-   a call to lisp_malloc.  */
-
-struct buffer *
-allocate_buffer ()
+static void
+lisp_free (block)
+     POINTER_TYPE *block;
 {
-  struct buffer *b
-    = (struct buffer *) lisp_malloc (sizeof (struct buffer),
-                                    MEM_TYPE_BUFFER);
-  return b;
+  BLOCK_INPUT;
+  free (block);
+#if GC_MARK_STACK && !defined GC_MALLOC_CHECK
+  mem_delete (mem_find (block));
+#endif
+  UNBLOCK_INPUT;
 }
 
+/* Allocation of aligned blocks of memory to store Lisp data.              */
+/* The entry point is lisp_align_malloc which returns blocks of at most    */
+/* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary.  */
 
-/* Free BLOCK.  This must be called to free memory allocated with a
-   call to lisp_malloc.  */
+/* Use posix_memalloc if the system has it and we're using the system's
+   malloc (because our gmalloc.c routines don't have posix_memalign although
+   its memalloc could be used).  */
+#if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
+#define USE_POSIX_MEMALIGN 1
+#endif
+
+/* BLOCK_ALIGN has to be a power of 2.  */
+#define BLOCK_ALIGN (1 << 10)
+
+/* Padding to leave at the end of a malloc'd block.  This is to give
+   malloc a chance to minimize the amount of memory wasted to alignment.
+   It should be tuned to the particular malloc library used.
+   On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
+   posix_memalign on the other hand would ideally prefer a value of 4
+   because otherwise, there's 1020 bytes wasted between each ablocks.
+   In Emacs, testing shows that those 1020 can most of the time be
+   efficiently used by malloc to place other objects, so a value of 0 can
+   still preferable unless you have a lot of aligned blocks and virtually
+   nothing else.  */
+#define BLOCK_PADDING 0
+#define BLOCK_BYTES \
+  (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
+
+/* Internal data structures and constants.  */
+
+#define ABLOCKS_SIZE 16
+
+/* An aligned block of memory.  */
+struct ablock
+{
+  union
+  {
+    char payload[BLOCK_BYTES];
+    struct ablock *next_free;
+  } x;
+  /* `abase' is the aligned base of the ablocks.  */
+  /* It is overloaded to hold the virtual `busy' field that counts
+     the number of used ablock in the parent ablocks.
+     The first ablock has the `busy' field, the others have the `abase'
+     field.  To tell the difference, we assume that pointers will have
+     integer values larger than 2 * ABLOCKS_SIZE.  The lowest bit of `busy'
+     is used to tell whether the real base of the parent ablocks is `abase'
+     (if not, the word before the first ablock holds a pointer to the
+     real base).  */
+  struct ablocks *abase;
+  /* The padding of all but the last ablock is unused.  The padding of
+     the last ablock in an ablocks is not allocated.  */
+#if BLOCK_PADDING
+  char padding[BLOCK_PADDING];
+#endif
+};
+
+/* A bunch of consecutive aligned blocks.  */
+struct ablocks
+{
+  struct ablock blocks[ABLOCKS_SIZE];
+};
+
+/* Size of the block requested from malloc or memalign.  */
+#define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
+
+#define ABLOCK_ABASE(block) \
+  (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE)   \
+   ? (struct ablocks *)(block)                                 \
+   : (block)->abase)
+
+/* Virtual `busy' field.  */
+#define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
+
+/* Pointer to the (not necessarily aligned) malloc block.  */
+#ifdef USE_POSIX_MEMALIGN
+#define ABLOCKS_BASE(abase) (abase)
+#else
+#define ABLOCKS_BASE(abase) \
+  (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
+#endif
+
+/* The list of free ablock.   */
+static struct ablock *free_ablock;
+
+/* Allocate an aligned block of nbytes.
+   Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
+   smaller or equal to BLOCK_BYTES.  */
+static POINTER_TYPE *
+lisp_align_malloc (nbytes, type)
+     size_t nbytes;
+     enum mem_type type;
+{
+  void *base, *val;
+  struct ablocks *abase;
+
+  eassert (nbytes <= BLOCK_BYTES);
+
+  BLOCK_INPUT;
+
+#ifdef GC_MALLOC_CHECK
+  allocated_mem_type = type;
+#endif
+
+  if (!free_ablock)
+    {
+      int i;
+      EMACS_INT aligned; /* int gets warning casting to 64-bit pointer.  */
+
+#ifdef DOUG_LEA_MALLOC
+      /* Prevent mmap'ing the chunk.  Lisp data may not be mmap'ed
+        because mapped region contents are not preserved in
+        a dumped Emacs.  */
+      mallopt (M_MMAP_MAX, 0);
+#endif
+
+#ifdef USE_POSIX_MEMALIGN
+      {
+       int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
+       if (err)
+         base = NULL;
+       abase = base;
+      }
+#else
+      base = malloc (ABLOCKS_BYTES);
+      abase = ALIGN (base, BLOCK_ALIGN);
+#endif
+
+      if (base == 0)
+       {
+         UNBLOCK_INPUT;
+         memory_full ();
+       }
+
+      aligned = (base == abase);
+      if (!aligned)
+       ((void**)abase)[-1] = base;
+
+#ifdef DOUG_LEA_MALLOC
+      /* Back to a reasonable maximum of mmap'ed areas.  */
+      mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
+#endif
+
+#ifndef USE_LSB_TAG
+      /* If the memory just allocated cannot be addressed thru a Lisp
+        object's pointer, and it needs to be, that's equivalent to
+        running out of memory.  */
+      if (type != MEM_TYPE_NON_LISP)
+       {
+         Lisp_Object tem;
+         char *end = (char *) base + ABLOCKS_BYTES - 1;
+         XSETCONS (tem, end);
+         if ((char *) XCONS (tem) != end)
+           {
+             lisp_malloc_loser = base;
+             free (base);
+             UNBLOCK_INPUT;
+             memory_full ();
+           }
+       }
+#endif
+
+      /* Initialize the blocks and put them on the free list.
+        Is `base' was not properly aligned, we can't use the last block.  */
+      for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
+       {
+         abase->blocks[i].abase = abase;
+         abase->blocks[i].x.next_free = free_ablock;
+         free_ablock = &abase->blocks[i];
+       }
+      ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
+
+      eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
+      eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
+      eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
+      eassert (ABLOCKS_BASE (abase) == base);
+      eassert (aligned == (long) ABLOCKS_BUSY (abase));
+    }
+
+  abase = ABLOCK_ABASE (free_ablock);
+  ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
+  val = free_ablock;
+  free_ablock = free_ablock->x.next_free;
+
+#if GC_MARK_STACK && !defined GC_MALLOC_CHECK
+  if (val && type != MEM_TYPE_NON_LISP)
+    mem_insert (val, (char *) val + nbytes, type);
+#endif
+
+  UNBLOCK_INPUT;
+  if (!val && nbytes)
+    memory_full ();
+
+  eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
+  return val;
+}
 
 static void
-lisp_free (block)
+lisp_align_free (block)
      POINTER_TYPE *block;
 {
+  struct ablock *ablock = block;
+  struct ablocks *abase = ABLOCK_ABASE (ablock);
+
   BLOCK_INPUT;
-  free (block);
 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
   mem_delete (mem_find (block));
 #endif
+  /* Put on free list.  */
+  ablock->x.next_free = free_ablock;
+  free_ablock = ablock;
+  /* Update busy count.  */
+  ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
+
+  if (2 > (long) ABLOCKS_BUSY (abase))
+    { /* All the blocks are free.  */
+      int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
+      struct ablock **tem = &free_ablock;
+      struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
+
+      while (*tem)
+       {
+         if (*tem >= (struct ablock *) abase && *tem < atop)
+           {
+             i++;
+             *tem = (*tem)->x.next_free;
+           }
+         else
+           tem = &(*tem)->x.next_free;
+       }
+      eassert ((aligned & 1) == aligned);
+      eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
+#ifdef USE_POSIX_MEMALIGN
+      eassert ((unsigned long)ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
+#endif
+      free (ABLOCKS_BASE (abase));
+    }
   UNBLOCK_INPUT;
 }
 
+/* Return a new buffer structure allocated from the heap with
+   a call to lisp_malloc.  */
+
+struct buffer *
+allocate_buffer ()
+{
+  struct buffer *b
+    = (struct buffer *) lisp_malloc (sizeof (struct buffer),
+                                    MEM_TYPE_BUFFER);
+  return b;
+}
+
 \f
+#ifndef SYSTEM_MALLOC
+
 /* 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
+   pair; 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 systems
    can use GNU malloc.  */
 
-#ifndef SYSTEM_MALLOC
+#ifndef SYNC_INPUT
+
 #ifndef DOUG_LEA_MALLOC
-extern void * (*__malloc_hook) P_ ((size_t));
-extern void * (*__realloc_hook) P_ ((void *, size_t));
-extern void (*__free_hook) P_ ((void *));
+extern void * (*__malloc_hook) P_ ((size_t, const void *));
+extern void * (*__realloc_hook) P_ ((void *, size_t, const void *));
+extern void (*__free_hook) P_ ((void *, const void *));
 /* Else declared in malloc.h, perhaps with an extra arg.  */
 #endif /* DOUG_LEA_MALLOC */
-static void * (*old_malloc_hook) ();
-static void * (*old_realloc_hook) ();
-static void (*old_free_hook) ();
+static void * (*old_malloc_hook) P_ ((size_t, const void *));
+static void * (*old_realloc_hook) P_ ((void *,  size_t, const void*));
+static void (*old_free_hook) P_ ((void*, const void*));
 
 /* This function is used as the hook for free to call.  */
 
 static void
-emacs_blocked_free (ptr)
+emacs_blocked_free (ptr, ptr2)
      void *ptr;
+     const void *ptr2;
 {
-  BLOCK_INPUT;
+  EMACS_INT bytes_used_now;
+
+  BLOCK_INPUT_ALLOC;
 
 #ifdef GC_MALLOC_CHECK
   if (ptr)
@@ -701,43 +1197,31 @@ emacs_blocked_free (ptr)
   /* 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
+  if (! NILP (Vmemory_full)
       /* 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
-         > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
-    spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
+         > ((bytes_used_when_reconsidered = BYTES_USED)
+            + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
+    refill_memory_reserve ();
 
   __free_hook = emacs_blocked_free;
-  UNBLOCK_INPUT;
-}
-
-
-/* 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 ((size_t) SPARE_MEMORY);
+  UNBLOCK_INPUT_ALLOC;
 }
 
 
 /* This function is the malloc hook that Emacs uses.  */
 
 static void *
-emacs_blocked_malloc (size)
+emacs_blocked_malloc (size, ptr)
      size_t size;
+     const void *ptr;
 {
   void *value;
 
-  BLOCK_INPUT;
+  BLOCK_INPUT_ALLOC;
   __malloc_hook = old_malloc_hook;
 #ifdef DOUG_LEA_MALLOC
     mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
@@ -769,7 +1253,7 @@ emacs_blocked_malloc (size)
 #endif /* GC_MALLOC_CHECK */
 
   __malloc_hook = emacs_blocked_malloc;
-  UNBLOCK_INPUT;
+  UNBLOCK_INPUT_ALLOC;
 
   /* fprintf (stderr, "%p malloc\n", value); */
   return value;
@@ -779,13 +1263,14 @@ emacs_blocked_malloc (size)
 /* This function is the realloc hook that Emacs uses.  */
 
 static void *
-emacs_blocked_realloc (ptr, size)
+emacs_blocked_realloc (ptr, size, ptr2)
      void *ptr;
      size_t size;
+     const void *ptr2;
 {
   void *value;
 
-  BLOCK_INPUT;
+  BLOCK_INPUT_ALLOC;
   __realloc_hook = old_realloc_hook;
 
 #ifdef GC_MALLOC_CHECK
@@ -830,10 +1315,26 @@ emacs_blocked_realloc (ptr, size)
 #endif /* GC_MALLOC_CHECK */
 
   __realloc_hook = emacs_blocked_realloc;
-  UNBLOCK_INPUT;
+  UNBLOCK_INPUT_ALLOC;
+
+  return value;
+}
+
+
+#ifdef HAVE_GTK_AND_PTHREAD
+/* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
+   normal malloc.  Some thread implementations need this as they call
+   malloc before main.  The pthread_self call in BLOCK_INPUT_ALLOC then
+   calls malloc because it is the first call, and we have an endless loop.  */
 
-  return value;
+void
+reset_malloc_hooks ()
+{
+  __free_hook = 0;
+  __malloc_hook = 0;
+  __realloc_hook = 0;
 }
+#endif /* HAVE_GTK_AND_PTHREAD */
 
 
 /* Called from main to set up malloc to use our hooks.  */
@@ -841,6 +1342,16 @@ emacs_blocked_realloc (ptr, size)
 void
 uninterrupt_malloc ()
 {
+#ifdef HAVE_GTK_AND_PTHREAD
+  pthread_mutexattr_t attr;
+
+  /*  GLIBC has a faster way to do this, but lets keep it portable.
+      This is according to the Single UNIX Specification.  */
+  pthread_mutexattr_init (&attr);
+  pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
+  pthread_mutex_init (&alloc_mutex, &attr);
+#endif /* HAVE_GTK_AND_PTHREAD */
+
   if (__free_hook != emacs_blocked_free)
     old_free_hook = __free_hook;
   __free_hook = emacs_blocked_free;
@@ -854,6 +1365,7 @@ uninterrupt_malloc ()
   __realloc_hook = emacs_blocked_realloc;
 }
 
+#endif /* not SYNC_INPUT */
 #endif /* not SYSTEM_MALLOC */
 
 
@@ -873,8 +1385,9 @@ uninterrupt_malloc ()
 
 struct interval_block
 {
-  struct interval_block *next;
+  /* Place `intervals' first, to preserve alignment.  */
   struct interval intervals[INTERVAL_BLOCK_SIZE];
+  struct interval_block *next;
 };
 
 /* Current interval block.  Its `next' pointer points to older
@@ -905,14 +1418,10 @@ int n_interval_blocks;
 static void
 init_intervals ()
 {
-  interval_block
-    = (struct interval_block *) lisp_malloc (sizeof *interval_block,
-                                            MEM_TYPE_NON_LISP);
-  interval_block->next = 0;
-  bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
-  interval_block_index = 0;
+  interval_block = NULL;
+  interval_block_index = INTERVAL_BLOCK_SIZE;
   interval_free_list = 0;
-  n_interval_blocks = 1;
+  n_interval_blocks = 0;
 }
 
 
@@ -923,6 +1432,12 @@ make_interval ()
 {
   INTERVAL val;
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   if (interval_free_list)
     {
       val = interval_free_list;
@@ -944,9 +1459,15 @@ make_interval ()
        }
       val = &interval_block->intervals[interval_block_index++];
     }
+
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   consing_since_gc += sizeof (struct interval);
   intervals_consed++;
   RESET_INTERVAL (val);
+  val->gcmarkbit = 0;
   return val;
 }
 
@@ -958,10 +1479,9 @@ mark_interval (i, dummy)
      register INTERVAL i;
      Lisp_Object dummy;
 {
-  if (XMARKBIT (i->plist))
-    abort ();
-  mark_object (&i->plist);
-  XMARK (i->plist);
+  eassert (!i->gcmarkbit);             /* Intervals are never shared.  */
+  i->gcmarkbit = 1;
+  mark_object (i->plist);
 }
 
 
@@ -976,10 +1496,6 @@ mark_interval_tree (tree)
      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 (tree->up.obj);
-
   traverse_intervals_noorder (tree, mark_interval, Qnil);
 }
 
@@ -988,23 +1504,15 @@ mark_interval_tree (tree)
 
 #define MARK_INTERVAL_TREE(i)                          \
   do {                                                 \
-    if (!NULL_INTERVAL_P (i)                           \
-       && ! XMARKBIT (i->up.obj))                      \
+    if (!NULL_INTERVAL_P (i) && !i->gcmarkbit)         \
       mark_interval_tree (i);                          \
   } while (0)
 
 
-/* The oddity in the call to XUNMARK is necessary because XUNMARK
-   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 ((i)->up.obj);                          \
-       (i) = balance_intervals (i);                    \
-     }                                                 \
+     (i) = balance_intervals (i);                      \
   } while (0)
 
 \f
@@ -1013,7 +1521,7 @@ mark_interval_tree (tree)
 #ifndef make_number
 Lisp_Object
 make_number (n)
-     int n;
+     EMACS_INT n;
 {
   Lisp_Object obj;
   obj.s.val = n;
@@ -1120,7 +1628,7 @@ struct sblock
 /* Number of Lisp strings in a string_block structure.  The 1020 is
    1024 minus malloc overhead.  */
 
-#define STRINGS_IN_STRING_BLOCK \
+#define STRING_BLOCK_SIZE \
   ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
 
 /* Structure describing a block from which Lisp_String structures
@@ -1128,8 +1636,9 @@ struct sblock
 
 struct string_block
 {
+  /* Place `strings' first, to preserve alignment.  */
+  struct Lisp_String strings[STRING_BLOCK_SIZE];
   struct string_block *next;
-  struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
 };
 
 /* Head and tail of the list of sblock structures holding Lisp string
@@ -1183,6 +1692,21 @@ static int total_string_size;
 
 #endif /* not GC_CHECK_STRING_BYTES */
 
+
+#ifdef GC_CHECK_STRING_OVERRUN
+
+/* We check for overrun in string data blocks by appending a small
+   "cookie" after each allocated string data block, and check for the
+   presence of this cookie during GC.  */
+
+#define GC_STRING_OVERRUN_COOKIE_SIZE  4
+static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
+  { 0xde, 0xad, 0xbe, 0xef };
+
+#else
+#define GC_STRING_OVERRUN_COOKIE_SIZE 0
+#endif
+
 /* 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.  */
@@ -1206,6 +1730,10 @@ static int total_string_size;
 
 #endif /* not GC_CHECK_STRING_BYTES */
 
+/* Extra bytes to allocate for each string.  */
+
+#define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
+
 /* Initialize string allocation.  Called from init_alloc_once.  */
 
 void
@@ -1235,7 +1763,7 @@ int
 string_bytes (s)
      struct Lisp_String *s;
 {
-  int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
+  int nbytes = (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
   if (!PURE_POINTER_P (s)
       && s->data
       && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
@@ -1270,7 +1798,7 @@ check_sblock (b)
        nbytes = SDATA_NBYTES (from);
 
       nbytes = SDATA_SIZE (nbytes);
-      from_end = (struct sdata *) ((char *) from + nbytes);
+      from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
     }
 }
 
@@ -1303,6 +1831,28 @@ check_string_bytes (all_p)
 
 #endif /* GC_CHECK_STRING_BYTES */
 
+#ifdef GC_CHECK_STRING_FREE_LIST
+
+/* Walk through the string free list looking for bogus next pointers.
+   This may catch buffer overrun from a previous string.  */
+
+static void
+check_string_free_list ()
+{
+  struct Lisp_String *s;
+
+  /* Pop a Lisp_String off the free-list.  */
+  s = string_free_list;
+  while (s != NULL)
+    {
+      if ((unsigned)s < 1024)
+       abort();
+      s = NEXT_FREE_LISP_STRING (s);
+    }
+}
+#else
+#define check_string_free_list()
+#endif
 
 /* Return a new Lisp_String.  */
 
@@ -1311,6 +1861,12 @@ allocate_string ()
 {
   struct Lisp_String *s;
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   /* 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)
@@ -1324,20 +1880,26 @@ allocate_string ()
       string_blocks = b;
       ++n_string_blocks;
 
-      for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
+      for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
        {
          s = b->strings + i;
          NEXT_FREE_LISP_STRING (s) = string_free_list;
          string_free_list = s;
        }
 
-      total_free_strings += STRINGS_IN_STRING_BLOCK;
+      total_free_strings += STRING_BLOCK_SIZE;
     }
 
+  check_string_free_list ();
+
   /* Pop a Lisp_String off the free-list.  */
   s = string_free_list;
   string_free_list = NEXT_FREE_LISP_STRING (s);
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   /* Probably not strictly necessary, but play it safe.  */
   bzero (s, sizeof *s);
 
@@ -1385,6 +1947,12 @@ allocate_string_data (s, nchars, nbytes)
   /* Determine the number of bytes needed to store NBYTES bytes
      of string data.  */
   needed = SDATA_SIZE (nbytes);
+  old_data = s->data ? SDATA_OF_STRING (s) : NULL;
+  old_nbytes = GC_STRING_BYTES (s);
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
 
   if (nbytes > LARGE_STRING_BYTES)
     {
@@ -1393,15 +1961,25 @@ allocate_string_data (s, nchars, nbytes)
 #ifdef DOUG_LEA_MALLOC
       /* Prevent mmap'ing the chunk.  Lisp data may not be mmap'ed
         because mapped region contents are not preserved in
-        a dumped Emacs.  */
+        a dumped Emacs.
+
+         In case you think of allowing it in a dumped Emacs at the
+         cost of not being able to re-dump, there's another reason:
+         mmap'ed data typically have an address towards the top of the
+         address space, which won't fit into an EMACS_INT (at least on
+         32-bit systems with the current tagging scheme).  --fx  */
+      BLOCK_INPUT;
       mallopt (M_MMAP_MAX, 0);
+      UNBLOCK_INPUT;
 #endif
 
-      b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
+      b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
 
 #ifdef DOUG_LEA_MALLOC
       /* Back to a reasonable maximum of mmap'ed areas. */
+      BLOCK_INPUT;
       mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
+      UNBLOCK_INPUT;
 #endif
 
       b->next_free = &b->first_data;
@@ -1412,7 +1990,7 @@ allocate_string_data (s, nchars, nbytes)
   else if (current_sblock == NULL
           || (((char *) current_sblock + SBLOCK_SIZE
                - (char *) current_sblock->next_free)
-              < needed))
+              < (needed + GC_STRING_EXTRA)))
     {
       /* Not enough room in the current sblock.  */
       b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
@@ -1429,10 +2007,13 @@ allocate_string_data (s, nchars, nbytes)
   else
     b = current_sblock;
 
-  old_data = s->data ? SDATA_OF_STRING (s) : NULL;
-  old_nbytes = GC_STRING_BYTES (s);
-
   data = b->next_free;
+  b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
+
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   data->string = s;
   s->data = SDATA_DATA (data);
 #ifdef GC_CHECK_STRING_BYTES
@@ -1441,7 +2022,10 @@ allocate_string_data (s, nchars, nbytes)
   s->size = nchars;
   s->size_byte = nbytes;
   s->data[nbytes] = '\0';
-  b->next_free = (struct sdata *) ((char *) data + needed);
+#ifdef GC_CHECK_STRING_OVERRUN
+  bcopy (string_overrun_cookie, (char *) data + needed,
+        GC_STRING_OVERRUN_COOKIE_SIZE);
+#endif
 
   /* 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
@@ -1476,7 +2060,7 @@ sweep_strings ()
 
       next = b->next;
 
-      for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
+      for (i = 0; i < STRING_BLOCK_SIZE; ++i)
        {
          struct Lisp_String *s = b->strings + i;
 
@@ -1531,8 +2115,8 @@ sweep_strings ()
 
       /* Free blocks that contain free Lisp_Strings only, except
         the first two of them.  */
-      if (nfree == STRINGS_IN_STRING_BLOCK
-         && total_free_strings > STRINGS_IN_STRING_BLOCK)
+      if (nfree == STRING_BLOCK_SIZE
+         && total_free_strings > STRING_BLOCK_SIZE)
        {
          lisp_free (b);
          --n_string_blocks;
@@ -1546,9 +2130,13 @@ sweep_strings ()
        }
     }
 
+  check_string_free_list ();
+
   string_blocks = live_blocks;
   free_large_strings ();
   compact_small_strings ();
+
+  check_string_free_list ();
 }
 
 
@@ -1620,28 +2208,38 @@ compact_small_strings ()
          else
            nbytes = SDATA_NBYTES (from);
 
+         if (nbytes > LARGE_STRING_BYTES)
+           abort ();
+
          nbytes = SDATA_SIZE (nbytes);
-         from_end = (struct sdata *) ((char *) from + nbytes);
+         from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
+
+#ifdef GC_CHECK_STRING_OVERRUN
+         if (bcmp (string_overrun_cookie,
+                   ((char *) from_end) - GC_STRING_OVERRUN_COOKIE_SIZE,
+                   GC_STRING_OVERRUN_COOKIE_SIZE))
+           abort ();
+#endif
 
          /* FROM->string non-null means it's alive.  Copy its data.  */
          if (from->string)
            {
              /* If TB is full, proceed with the next sblock.  */
-             to_end = (struct sdata *) ((char *) to + nbytes);
+             to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
              if (to_end > tb_end)
                {
                  tb->next_free = to;
                  tb = tb->next;
                  tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
                  to = &tb->first_data;
-                 to_end = (struct sdata *) ((char *) to + nbytes);
+                 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
                }
 
              /* Copy, and update the string's `data' pointer.  */
              if (from != to)
                {
                  xassert (tb != b || to <= from);
-                 safe_bcopy ((char *) from, (char *) to, nbytes);
+                 safe_bcopy ((char *) from, (char *) to, nbytes + GC_STRING_EXTRA);
                  to->string->data = SDATA_DATA (to);
                }
 
@@ -1666,8 +2264,9 @@ compact_small_strings ()
 
 
 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
-       doc: /* Return a newly created string of length LENGTH, with each element being INIT.
-Both LENGTH and INIT must be numbers.  */)
+       doc: /* Return a newly created string of length LENGTH, with INIT in each element.
+LENGTH must be an integer.
+INIT must be an integer that represents a character.  */)
      (length, init)
      Lisp_Object length, init;
 {
@@ -1710,7 +2309,7 @@ Both LENGTH and INIT must be numbers.  */)
 
 
 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
-       doc: /* Return a new bool-vector of length LENGTH, using INIT for as each element.
+       doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
 LENGTH must be a number.  INIT matters only in whether it is t or nil.  */)
      (length, init)
      Lisp_Object length, init;
@@ -1722,10 +2321,11 @@ LENGTH must be a number.  INIT matters only in whether it is t or nil.  */)
 
   CHECK_NATNUM (length);
 
-  bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
+  bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
 
   length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
-  length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
+  length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
+                    / BOOL_VECTOR_BITS_PER_CHAR);
 
   /* We must allocate one more elements than LENGTH_IN_ELTS for the
      slot `size' of the struct Lisp_Bool_Vector.  */
@@ -1742,9 +2342,9 @@ LENGTH must be a number.  INIT matters only in whether it is t or nil.  */)
     p->data[i] = real_init;
 
   /* Clear the extraneous bits in the last byte.  */
-  if (XINT (length) != length_in_chars * BITS_PER_CHAR)
+  if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
     XBOOL_VECTOR (val)->data[length_in_chars - 1]
-      &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
+      &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
 
   return val;
 }
@@ -1902,21 +2502,50 @@ make_uninit_multibyte_string (nchars, nbytes)
 /* We store float cells inside of float_blocks, allocating a new
    float_block with malloc whenever necessary.  Float cells reclaimed
    by GC are put on a free list to be reallocated before allocating
-   any new float cells from the latest float_block.
+   any new float cells from the latest float_block.  */
+
+#define FLOAT_BLOCK_SIZE                                       \
+  (((BLOCK_BYTES - sizeof (struct float_block *)               \
+     /* The compiler might add padding at the end.  */         \
+     - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
+   / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
+
+#define GETMARKBIT(block,n)                            \
+  (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)]        \
+    >> ((n) % (sizeof(int) * CHAR_BIT)))               \
+   & 1)
+
+#define SETMARKBIT(block,n)                            \
+  (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)]  \
+  |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
 
-   Each float_block is just under 1020 bytes long, since malloc really
-   allocates in units of powers of two and uses 4 bytes for its own
-   overhead. */
+#define UNSETMARKBIT(block,n)                          \
+  (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)]  \
+  &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
 
-#define FLOAT_BLOCK_SIZE \
-  ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
+#define FLOAT_BLOCK(fptr) \
+  ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
+
+#define FLOAT_INDEX(fptr) \
+  ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
 
 struct float_block
 {
-  struct float_block *next;
+  /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job.  */
   struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
+  int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
+  struct float_block *next;
 };
 
+#define FLOAT_MARKED_P(fptr) \
+  GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
+
+#define FLOAT_MARK(fptr) \
+  SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
+
+#define FLOAT_UNMARK(fptr) \
+  UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
+
 /* Current float_block.  */
 
 struct float_block *float_block;
@@ -1939,13 +2568,10 @@ struct Lisp_Float *float_free_list;
 void
 init_float ()
 {
-  float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
-                                                   MEM_TYPE_FLOAT);
-  float_block->next = 0;
-  bzero ((char *) float_block->floats, sizeof float_block->floats);
-  float_block_index = 0;
+  float_block = NULL;
+  float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block.   */
   float_free_list = 0;
-  n_float_blocks = 1;
+  n_float_blocks = 0;
 }
 
 
@@ -1955,10 +2581,7 @@ void
 free_float (ptr)
      struct Lisp_Float *ptr;
 {
-  *(struct Lisp_Float **)&ptr->data = float_free_list;
-#if GC_MARK_STACK
-  ptr->type = Vdead;
-#endif
+  ptr->u.chain = float_free_list;
   float_free_list = ptr;
 }
 
@@ -1971,12 +2594,18 @@ make_float (float_value)
 {
   register Lisp_Object val;
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   if (float_free_list)
     {
       /* We use the data field for chaining the free list
         so that we won't use the same field that has the mark bit.  */
       XSETFLOAT (val, float_free_list);
-      float_free_list = *(struct Lisp_Float **)&float_free_list->data;
+      float_free_list = float_free_list->u.chain;
     }
   else
     {
@@ -1984,18 +2613,24 @@ make_float (float_value)
        {
          register struct float_block *new;
 
-         new = (struct float_block *) lisp_malloc (sizeof *new,
-                                                   MEM_TYPE_FLOAT);
+         new = (struct float_block *) lisp_align_malloc (sizeof *new,
+                                                         MEM_TYPE_FLOAT);
          new->next = float_block;
+         bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
          float_block = new;
          float_block_index = 0;
          n_float_blocks++;
        }
-      XSETFLOAT (val, &float_block->floats[float_block_index++]);
+      XSETFLOAT (val, &float_block->floats[float_block_index]);
+      float_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   XFLOAT_DATA (val) = float_value;
-  XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
+  eassert (!FLOAT_MARKED_P (XFLOAT (val)));
   consing_since_gc += sizeof (struct Lisp_Float);
   floats_consed++;
   return val;
@@ -2010,21 +2645,35 @@ make_float (float_value)
 /* We store cons cells inside of cons_blocks, allocating a new
    cons_block with malloc whenever necessary.  Cons cells reclaimed by
    GC are put on a free list to be reallocated before allocating
-   any new cons cells from the latest cons_block.
-
-   Each cons_block is just under 1020 bytes long,
-   since malloc really allocates in units of powers of two
-   and uses 4 bytes for its own overhead. */
+   any new cons cells from the latest cons_block.  */
 
 #define CONS_BLOCK_SIZE \
-  ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
+  (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
+   / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
+
+#define CONS_BLOCK(fptr) \
+  ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
+
+#define CONS_INDEX(fptr) \
+  ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
 
 struct cons_block
 {
-  struct cons_block *next;
+  /* Place `conses' at the beginning, to ease up CONS_INDEX's job.  */
   struct Lisp_Cons conses[CONS_BLOCK_SIZE];
+  int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
+  struct cons_block *next;
 };
 
+#define CONS_MARKED_P(fptr) \
+  GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
+
+#define CONS_MARK(fptr) \
+  SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
+
+#define CONS_UNMARK(fptr) \
+  UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
+
 /* Current cons_block.  */
 
 struct cons_block *cons_block;
@@ -2047,13 +2696,10 @@ int n_cons_blocks;
 void
 init_cons ()
 {
-  cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
-                                                 MEM_TYPE_CONS);
-  cons_block->next = 0;
-  bzero ((char *) cons_block->conses, sizeof cons_block->conses);
-  cons_block_index = 0;
+  cons_block = NULL;
+  cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block.  */
   cons_free_list = 0;
-  n_cons_blocks = 1;
+  n_cons_blocks = 0;
 }
 
 
@@ -2063,14 +2709,13 @@ void
 free_cons (ptr)
      struct Lisp_Cons *ptr;
 {
-  *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
+  ptr->u.chain = cons_free_list;
 #if GC_MARK_STACK
   ptr->car = Vdead;
 #endif
   cons_free_list = ptr;
 }
 
-
 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
        doc: /* Create a new cons, give it CAR and CDR as components, and return it.  */)
      (car, cdr)
@@ -2078,35 +2723,59 @@ DEFUN ("cons", Fcons, Scons, 2, 2, 0,
 {
   register Lisp_Object val;
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   if (cons_free_list)
     {
       /* We use the cdr for chaining the free list
         so that we won't use the same field that has the mark bit.  */
       XSETCONS (val, cons_free_list);
-      cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
+      cons_free_list = cons_free_list->u.chain;
     }
   else
     {
       if (cons_block_index == CONS_BLOCK_SIZE)
        {
          register struct cons_block *new;
-         new = (struct cons_block *) lisp_malloc (sizeof *new,
-                                                  MEM_TYPE_CONS);
+         new = (struct cons_block *) lisp_align_malloc (sizeof *new,
+                                                        MEM_TYPE_CONS);
+         bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
          new->next = cons_block;
          cons_block = new;
          cons_block_index = 0;
          n_cons_blocks++;
        }
-      XSETCONS (val, &cons_block->conses[cons_block_index++]);
+      XSETCONS (val, &cons_block->conses[cons_block_index]);
+      cons_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   XSETCAR (val, car);
   XSETCDR (val, cdr);
+  eassert (!CONS_MARKED_P (XCONS (val)));
   consing_since_gc += sizeof (struct Lisp_Cons);
   cons_cells_consed++;
   return val;
 }
 
+/* Get an error now if there's any junk in the cons free list.  */
+void
+check_cons_list ()
+{
+#ifdef GC_CHECK_CONS_LIST
+  struct Lisp_Cons *tail = cons_free_list;
+
+  while (tail)
+    tail = tail->u.chain;
+#endif
+}
 
 /* Make a list of 2, 3, 4 or 5 specified objects.  */
 
@@ -2240,22 +2909,38 @@ allocate_vectorlike (len, type)
   /* Prevent mmap'ing the chunk.  Lisp data may not be mmap'ed
      because mapped region contents are not preserved in
      a dumped Emacs.  */
+  BLOCK_INPUT;
   mallopt (M_MMAP_MAX, 0);
+  UNBLOCK_INPUT;
 #endif
 
+  /* This gets triggered by code which I haven't bothered to fix.  --Stef  */
+  /* eassert (!handling_signal); */
+
   nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
   p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
 
 #ifdef DOUG_LEA_MALLOC
   /* Back to a reasonable maximum of mmap'ed areas.  */
+  BLOCK_INPUT;
   mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
+  UNBLOCK_INPUT;
 #endif
 
   consing_since_gc += nbytes;
   vector_cells_consed += len;
 
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   p->next = all_vectors;
   all_vectors = p;
+
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   ++n_vectors;
   return p;
 }
@@ -2322,13 +3007,17 @@ allocate_frame ()
 struct Lisp_Process *
 allocate_process ()
 {
-  EMACS_INT len = VECSIZE (struct Lisp_Process);
-  struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
+  /* Memory-footprint of the object in nb of Lisp_Object fields.  */
+  EMACS_INT memlen = VECSIZE (struct Lisp_Process);
+  /* Size if we only count the actual Lisp_Object fields (which need to be
+     traced by the GC).  */
+  EMACS_INT lisplen = PSEUDOVECSIZE (struct Lisp_Process, pid);
+  struct Lisp_Vector *v = allocate_vectorlike (memlen, MEM_TYPE_PROCESS);
   EMACS_INT i;
 
-  for (i = 0; i < len; ++i)
+  for (i = 0; i < lisplen; ++i)
     v->contents[i] = Qnil;
-  v->size = len;
+  v->size = lisplen;
 
   return (struct Lisp_Process *) v;
 }
@@ -2398,18 +3087,18 @@ The property's value should be an integer between 0 and 10.  */)
 }
 
 
-/* Return a newly created sub char table with default value DEFALT.
+/* Return a newly created sub char table with slots initialized by INIT.
    Since a sub char table does not appear as a top level Emacs Lisp
    object, we don't need a Lisp interface to make it.  */
 
 Lisp_Object
-make_sub_char_table (defalt)
-     Lisp_Object defalt;
+make_sub_char_table (init)
+     Lisp_Object init;
 {
   Lisp_Object vector
-    = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
+    = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), init);
   XCHAR_TABLE (vector)->top = Qnil;
-  XCHAR_TABLE (vector)->defalt = defalt;
+  XCHAR_TABLE (vector)->defalt = Qnil;
   XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
   return vector;
 }
@@ -2491,8 +3180,9 @@ usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INT
 
 struct symbol_block
 {
-  struct symbol_block *next;
+  /* Place `symbols' first, to preserve alignment.  */
   struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
+  struct symbol_block *next;
 };
 
 /* Current symbol block and index of first unused Lisp_Symbol
@@ -2515,13 +3205,10 @@ int n_symbol_blocks;
 void
 init_symbol ()
 {
-  symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
-                                                     MEM_TYPE_SYMBOL);
-  symbol_block->next = 0;
-  bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
-  symbol_block_index = 0;
+  symbol_block = NULL;
+  symbol_block_index = SYMBOL_BLOCK_SIZE;
   symbol_free_list = 0;
-  n_symbol_blocks = 1;
+  n_symbol_blocks = 0;
 }
 
 
@@ -2536,10 +3223,16 @@ Its value and function definition are void, and its property list is nil.  */)
 
   CHECK_STRING (name);
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   if (symbol_free_list)
     {
       XSETSYMBOL (val, symbol_free_list);
-      symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
+      symbol_free_list = symbol_free_list->next;
     }
   else
     {
@@ -2553,15 +3246,21 @@ Its value and function definition are void, and its property list is nil.  */)
          symbol_block_index = 0;
          n_symbol_blocks++;
        }
-      XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
+      XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
+      symbol_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   p = XSYMBOL (val);
   p->xname = name;
   p->plist = Qnil;
   p->value = Qunbound;
   p->function = Qunbound;
   p->next = NULL;
+  p->gcmarkbit = 0;
   p->interned = SYMBOL_UNINTERNED;
   p->constant = 0;
   p->indirect_variable = 0;
@@ -2584,8 +3283,9 @@ Its value and function definition are void, and its property list is nil.  */)
 
 struct marker_block
 {
-  struct marker_block *next;
+  /* Place `markers' first, to preserve alignment.  */
   union Lisp_Misc markers[MARKER_BLOCK_SIZE];
+  struct marker_block *next;
 };
 
 struct marker_block *marker_block;
@@ -2600,13 +3300,10 @@ int n_marker_blocks;
 void
 init_marker ()
 {
-  marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
-                                                     MEM_TYPE_MISC);
-  marker_block->next = 0;
-  bzero ((char *) marker_block->markers, sizeof marker_block->markers);
-  marker_block_index = 0;
+  marker_block = NULL;
+  marker_block_index = MARKER_BLOCK_SIZE;
   marker_free_list = 0;
-  n_marker_blocks = 1;
+  n_marker_blocks = 0;
 }
 
 /* Return a newly allocated Lisp_Misc object, with no substructure.  */
@@ -2616,6 +3313,12 @@ allocate_misc ()
 {
   Lisp_Object val;
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   if (marker_free_list)
     {
       XSETMISC (val, marker_free_list);
@@ -2632,15 +3335,36 @@ allocate_misc ()
          marker_block = new;
          marker_block_index = 0;
          n_marker_blocks++;
+         total_free_markers += MARKER_BLOCK_SIZE;
        }
-      XSETMISC (val, &marker_block->markers[marker_block_index++]);
+      XSETMISC (val, &marker_block->markers[marker_block_index]);
+      marker_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
+  --total_free_markers;
   consing_since_gc += sizeof (union Lisp_Misc);
   misc_objects_consed++;
+  XMARKER (val)->gcmarkbit = 0;
   return val;
 }
 
+/* Free a Lisp_Misc object */
+
+void
+free_misc (misc)
+     Lisp_Object misc;
+{
+  XMISC (misc)->u_marker.type = Lisp_Misc_Free;
+  XMISC (misc)->u_free.chain = marker_free_list;
+  marker_free_list = XMISC (misc);
+
+  total_free_markers++;
+}
+
 /* Return a Lisp_Misc_Save_Value object containing POINTER and
    INTEGER.  This is used to package C values to call record_unwind_protect.
    The unwind function can get the C values back using XSAVE_VALUE.  */
@@ -2658,6 +3382,7 @@ make_save_value (pointer, integer)
   p = XSAVE_VALUE (val);
   p->pointer = pointer;
   p->integer = integer;
+  p->dogc = 0;
   return val;
 }
 
@@ -2674,7 +3399,7 @@ DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
   p->buffer = 0;
   p->bytepos = 0;
   p->charpos = 0;
-  p->chain = Qnil;
+  p->next = NULL;
   p->insertion_type = 0;
   return val;
 }
@@ -2685,13 +3410,8 @@ void
 free_marker (marker)
      Lisp_Object marker;
 {
-  unchain_marker (marker);
-
-  XMISC (marker)->u_marker.type = Lisp_Misc_Free;
-  XMISC (marker)->u_free.chain = marker_free_list;
-  marker_free_list = XMISC (marker);
-
-  total_free_markers++;
+  unchain_marker (XMARKER (marker));
+  free_misc (marker);
 }
 
 \f
@@ -2735,6 +3455,83 @@ make_event_array (nargs, args)
 }
 
 
+\f
+/************************************************************************
+                          Memory Full Handling
+ ************************************************************************/
+
+
+/* Called if malloc returns zero.  */
+
+void
+memory_full ()
+{
+  int i;
+
+  Vmemory_full = Qt;
+
+  memory_full_cons_threshold = sizeof (struct cons_block);
+
+  /* The first time we get here, free the spare memory.  */
+  for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
+    if (spare_memory[i])
+      {
+       if (i == 0)
+         free (spare_memory[i]);
+       else if (i >= 1 && i <= 4)
+         lisp_align_free (spare_memory[i]);
+       else
+         lisp_free (spare_memory[i]);
+       spare_memory[i] = 0;
+      }
+
+  /* Record the space now used.  When it decreases substantially,
+     we can refill the memory reserve.  */
+#ifndef SYSTEM_MALLOC
+  bytes_used_when_full = BYTES_USED;
+#endif
+
+  /* This used to call error, but if we've run out of memory, we could
+     get infinite recursion trying to build the string.  */
+  while (1)
+    Fsignal (Qnil, Vmemory_signal_data);
+}
+
+/* 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,
+   and also directly from this file, in case we're not using ralloc.c.  */
+
+void
+refill_memory_reserve ()
+{
+#ifndef SYSTEM_MALLOC
+  if (spare_memory[0] == 0)
+    spare_memory[0] = (char *) malloc ((size_t) SPARE_MEMORY);
+  if (spare_memory[1] == 0)
+    spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
+                                                 MEM_TYPE_CONS);
+  if (spare_memory[2] == 0)
+    spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
+                                                 MEM_TYPE_CONS);
+  if (spare_memory[3] == 0)
+    spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
+                                                 MEM_TYPE_CONS);
+  if (spare_memory[4] == 0)
+    spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
+                                                 MEM_TYPE_CONS);
+  if (spare_memory[5] == 0)
+    spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
+                                           MEM_TYPE_STRING);
+  if (spare_memory[6] == 0)
+    spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
+                                           MEM_TYPE_STRING);
+  if (spare_memory[0] && spare_memory[1] && spare_memory[5])
+    Vmemory_full = Qnil;
+#endif
+}
 \f
 /************************************************************************
                           C Stack Marking
@@ -3167,6 +3964,7 @@ live_string_p (m, p)
         must not be on the free-list.  */
       return (offset >= 0
              && offset % sizeof b->strings[0] == 0
+             && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
              && ((struct Lisp_String *) p)->data != NULL);
     }
   else
@@ -3192,6 +3990,7 @@ live_cons_p (m, p)
         and not be on the free-list.  */
       return (offset >= 0
              && offset % sizeof b->conses[0] == 0
+             && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
              && (b != cons_block
                  || offset / sizeof b->conses[0] < cons_block_index)
              && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
@@ -3219,6 +4018,7 @@ live_symbol_p (m, p)
         and not be on the free-list.  */
       return (offset >= 0
              && offset % sizeof b->symbols[0] == 0
+             && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
              && (b != symbol_block
                  || offset / sizeof b->symbols[0] < symbol_block_index)
              && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
@@ -3241,14 +4041,13 @@ live_float_p (m, p)
       struct float_block *b = (struct float_block *) m->start;
       int offset = (char *) p - (char *) &b->floats[0];
 
-      /* P must point to the start of a Lisp_Float, not be
-        one of the unused cells in the current float block,
-        and not be on the free-list.  */
+      /* P must point to the start of a Lisp_Float and not be
+        one of the unused cells in the current float block.  */
       return (offset >= 0
              && offset % sizeof b->floats[0] == 0
+             && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
              && (b != float_block
-                 || offset / sizeof b->floats[0] < float_block_index)
-             && !EQ (((struct Lisp_Float *) p)->type, Vdead));
+                 || offset / sizeof b->floats[0] < float_block_index));
     }
   else
     return 0;
@@ -3273,6 +4072,7 @@ live_misc_p (m, p)
         and not be on the free-list.  */
       return (offset >= 0
              && offset % sizeof b->markers[0] == 0
+             && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
              && (b != marker_block
                  || offset / sizeof b->markers[0] < marker_block_index)
              && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
@@ -3296,7 +4096,7 @@ live_vector_p (m, p)
 }
 
 
-/* Value is non-zero of P is a pointer to a live buffer.  M is a
+/* Value is non-zero if P is a pointer to a live buffer.  M is a
    pointer to the mem_block for P.  */
 
 static INLINE int
@@ -3386,18 +4186,15 @@ mark_maybe_object (obj)
          break;
 
        case Lisp_Cons:
-         mark_p = (live_cons_p (m, po)
-                   && !XMARKBIT (XCONS (obj)->car));
+         mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
          break;
 
        case Lisp_Symbol:
-         mark_p = (live_symbol_p (m, po)
-                   && !XMARKBIT (XSYMBOL (obj)->plist));
+         mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
          break;
 
        case Lisp_Float:
-         mark_p = (live_float_p (m, po)
-                   && !XMARKBIT (XFLOAT (obj)->type));
+         mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
          break;
 
        case Lisp_Vectorlike:
@@ -3405,31 +4202,13 @@ mark_maybe_object (obj)
             buffer because checking that dereferences the pointer
             PO which might point anywhere.  */
          if (live_vector_p (m, po))
-           mark_p = (!GC_SUBRP (obj)
-                     && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
+           mark_p = !GC_SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
          else if (live_buffer_p (m, po))
-           mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
+           mark_p = GC_BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
          break;
 
        case Lisp_Misc:
-         if (live_misc_p (m, po))
-           {
-             switch (XMISCTYPE (obj))
-               {
-               case Lisp_Misc_Marker:
-                 mark_p = !XMARKBIT (XMARKER (obj)->chain);
-                 break;
-
-               case Lisp_Misc_Buffer_Local_Value:
-               case Lisp_Misc_Some_Buffer_Local_Value:
-                 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
-                 break;
-
-               case Lisp_Misc_Overlay:
-                 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
-                 break;
-               }
-           }
+         mark_p = (live_misc_p (m, po) && !XMARKER (obj)->gcmarkbit);
          break;
 
        case Lisp_Int:
@@ -3444,7 +4223,7 @@ mark_maybe_object (obj)
            zombies[nzombies] = obj;
          ++nzombies;
 #endif
-         mark_object (&obj);
+         mark_object (obj);
        }
     }
 }
@@ -3476,14 +4255,12 @@ mark_maybe_pointer (p)
          break;
 
        case MEM_TYPE_BUFFER:
-         if (live_buffer_p (m, p)
-             && !XMARKBIT (((struct buffer *) p)->name))
+         if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
            XSETVECTOR (obj, p);
          break;
 
        case MEM_TYPE_CONS:
-         if (live_cons_p (m, p)
-             && !XMARKBIT (((struct Lisp_Cons *) p)->car))
+         if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
            XSETCONS (obj, p);
          break;
 
@@ -3494,41 +4271,17 @@ mark_maybe_pointer (p)
          break;
 
        case MEM_TYPE_MISC:
-         if (live_misc_p (m, p))
-           {
-             Lisp_Object tem;
-             XSETMISC (tem, p);
-
-             switch (XMISCTYPE (tem))
-               {
-               case Lisp_Misc_Marker:
-                 if (!XMARKBIT (XMARKER (tem)->chain))
-                   obj = tem;
-                 break;
-
-               case Lisp_Misc_Buffer_Local_Value:
-               case Lisp_Misc_Some_Buffer_Local_Value:
-                 if (!XMARKBIT (XBUFFER_LOCAL_VALUE (tem)->realvalue))
-                   obj = tem;
-                 break;
-
-               case Lisp_Misc_Overlay:
-                 if (!XMARKBIT (XOVERLAY (tem)->plist))
-                   obj = tem;
-                 break;
-               }
-           }
+         if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
+           XSETMISC (obj, p);
          break;
 
        case MEM_TYPE_SYMBOL:
-         if (live_symbol_p (m, p)
-             && !XMARKBIT (((struct Lisp_Symbol *) p)->plist))
+         if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
            XSETSYMBOL (obj, p);
          break;
 
        case MEM_TYPE_FLOAT:
-         if (live_float_p (m, p)
-             && !XMARKBIT (((struct Lisp_Float *) p)->type))
+         if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
            XSETFLOAT (obj, p);
          break;
 
@@ -3541,8 +4294,7 @@ mark_maybe_pointer (p)
            {
              Lisp_Object tem;
              XSETVECTOR (tem, p);
-             if (!GC_SUBRP (tem)
-                 && !(XVECTOR (tem)->size & ARRAY_MARK_FLAG))
+             if (!GC_SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
                obj = tem;
            }
          break;
@@ -3552,7 +4304,7 @@ mark_maybe_pointer (p)
        }
 
       if (!GC_NILP (obj))
-       mark_object (&obj);
+       mark_object (obj);
     }
 }
 
@@ -3786,7 +4538,7 @@ mark_stack ()
 
   /* This trick flushes the register windows so that all the state of
      the process is contained in the stack.  */
-  /* Fixme: Code in the Boehm GC sugests flushing (with `flushrs') is
+  /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
      needed on ia64 too.  See mach_dep.c, where it also says inline
      assembler doesn't work with relevant proprietary compilers.  */
 #ifdef sparc
@@ -3806,36 +4558,127 @@ mark_stack ()
                            of the test.  */
   if (!setjmp_tested_p)
     {
-      setjmp_tested_p = 1;
-      test_setjmp ();
-    }
-#endif /* GC_SETJMP_WORKS */
+      setjmp_tested_p = 1;
+      test_setjmp ();
+    }
+#endif /* GC_SETJMP_WORKS */
+
+  setjmp (j);
+  end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
+#endif /* not GC_SAVE_REGISTERS_ON_STACK */
+
+  /* This assumes that the stack is a contiguous region in memory.  If
+     that's not the case, something has to be done here to iterate
+     over the stack segments.  */
+#ifndef GC_LISP_OBJECT_ALIGNMENT
+#ifdef __GNUC__
+#define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
+#else
+#define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
+#endif
+#endif
+  for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
+    mark_memory ((char *) stack_base + i, end);
+  /* Allow for marking a secondary stack, like the register stack on the
+     ia64.  */
+#ifdef GC_MARK_SECONDARY_STACK
+  GC_MARK_SECONDARY_STACK ();
+#endif
+
+#if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
+  check_gcpros ();
+#endif
+}
+
+#endif /* GC_MARK_STACK != 0 */
+
+
+
+/* Return 1 if OBJ is a valid lisp object.
+   Return 0 if OBJ is NOT a valid lisp object.
+   Return -1 if we cannot validate OBJ.
+   This function can be quite slow,
+   so it should only be used in code for manual debugging.  */
+
+int
+valid_lisp_object_p (obj)
+     Lisp_Object obj;
+{
+  void *p;
+#if !GC_MARK_STACK
+  int fd;
+#else
+  struct mem_node *m;
+#endif
+
+  if (INTEGERP (obj))
+    return 1;
+
+  p = (void *) XPNTR (obj);
+  if (PURE_POINTER_P (p))
+    return 1;
+
+#if !GC_MARK_STACK
+  /* We need to determine whether it is safe to access memory at
+     address P.  Obviously, we cannot just access it (we would SEGV
+     trying), so we trick the o/s to tell us whether p is a valid
+     pointer.  Unfortunately, we cannot use NULL_DEVICE here, as
+     emacs_write may not validate p in that case.  */
+  if ((fd = emacs_open ("__Valid__Lisp__Object__", O_CREAT | O_WRONLY | O_TRUNC, 0666)) >= 0)
+    {
+      int valid = (emacs_write (fd, (char *)p, 16) == 16);
+      emacs_close (fd);
+      unlink ("__Valid__Lisp__Object__");
+      return valid;
+    }
+
+    return -1;
+#else
+
+  m = mem_find (p);
+
+  if (m == MEM_NIL)
+    return 0;
+
+  switch (m->type)
+    {
+    case MEM_TYPE_NON_LISP:
+      return 0;
 
-  setjmp (j);
-  end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
-#endif /* not GC_SAVE_REGISTERS_ON_STACK */
+    case MEM_TYPE_BUFFER:
+      return live_buffer_p (m, p);
 
-  /* This assumes that the stack is a contiguous region in memory.  If
-     that's not the case, something has to be done here to iterate
-     over the stack segments.  */
-#ifndef GC_LISP_OBJECT_ALIGNMENT
-#ifdef __GNUC__
-#define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
-#else
-#define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
-#endif
-#endif
-  for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
-    mark_memory ((char *) stack_base + i, end);
+    case MEM_TYPE_CONS:
+      return live_cons_p (m, p);
 
-#if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
-  check_gcpros ();
+    case MEM_TYPE_STRING:
+      return live_string_p (m, p);
+
+    case MEM_TYPE_MISC:
+      return live_misc_p (m, p);
+
+    case MEM_TYPE_SYMBOL:
+      return live_symbol_p (m, p);
+
+    case MEM_TYPE_FLOAT:
+      return live_float_p (m, p);
+
+    case MEM_TYPE_VECTOR:
+    case MEM_TYPE_PROCESS:
+    case MEM_TYPE_HASH_TABLE:
+    case MEM_TYPE_FRAME:
+    case MEM_TYPE_WINDOW:
+      return live_vector_p (m, p);
+
+    default:
+      break;
+    }
+
+  return 0;
 #endif
 }
 
 
-#endif /* GC_MARK_STACK != 0 */
-
 
 \f
 /***********************************************************************
@@ -3855,6 +4698,9 @@ pure_alloc (size, type)
      int type;
 {
   POINTER_TYPE *result;
+#ifdef USE_LSB_TAG
+  size_t alignment = (1 << GCTYPEBITS);
+#else
   size_t alignment = sizeof (EMACS_INT);
 
   /* Give Lisp_Floats an extra alignment.  */
@@ -3866,9 +4712,10 @@ pure_alloc (size, type)
       alignment = sizeof (struct Lisp_Float);
 #endif
     }
+#endif
 
  again:
-  result = (POINTER_TYPE *) ALIGN ((EMACS_UINT)purebeg + pure_bytes_used, alignment);
+  result = ALIGN (purebeg + pure_bytes_used, alignment);
   pure_bytes_used = ((char *)result - (char *)purebeg) + size;
 
   if (pure_bytes_used <= pure_size)
@@ -3891,7 +4738,7 @@ void
 check_pure_size ()
 {
   if (pure_bytes_used_before_overflow)
-    message ("Pure Lisp storage overflow (approx. %d bytes needed)",
+    message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
             (int) (pure_bytes_used + pure_bytes_used_before_overflow));
 }
 
@@ -3978,7 +4825,7 @@ make_pure_vector (len)
 
 
 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
-       doc: /* Make a copy of OBJECT in pure storage.
+       doc: /* Make a copy of object OBJ in pure storage.
 Recursively copies contents of vectors and cons cells.
 Does not copy symbols.  Copies strings without text properties.  */)
      (obj)
@@ -4001,12 +4848,13 @@ Does not copy symbols.  Copies strings without text properties.  */)
   else if (COMPILEDP (obj) || VECTORP (obj))
     {
       register struct Lisp_Vector *vec;
-      register int i, size;
+      register int i;
+      EMACS_INT size;
 
       size = XVECTOR (obj)->size;
       if (size & PSEUDOVECTOR_FLAG)
        size &= PSEUDOVECTOR_SIZE_MASK;
-      vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
+      vec = XVECTOR (make_pure_vector (size));
       for (i = 0; i < size; i++)
        vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
       if (COMPILEDP (obj))
@@ -4046,18 +4894,6 @@ struct catchtag
     struct catchtag *next;
 };
 
-struct backtrace
-{
-  struct backtrace *next;
-  Lisp_Object *function;
-  Lisp_Object *args;   /* Points to vector of args.  */
-  int nargs;           /* Length of vector.  */
-  /* If nargs is UNEVALLED, args points to slot holding list of
-     unevalled args.  */
-  char evalargs;
-};
-
-
 \f
 /***********************************************************************
                          Protection from GC
@@ -4078,19 +4914,20 @@ inhibit_garbage_collection ()
 
 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
        doc: /* Reclaim storage for Lisp objects no longer needed.
-Returns info on amount of space in use:
+Garbage collection happens automatically if you cons more than
+`gc-cons-threshold' bytes of Lisp data since previous garbage collection.
+`garbage-collect' normally returns a list with info on amount of space in use:
  ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
   (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
   (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
   (USED-STRINGS . FREE-STRINGS))
-Garbage collection happens automatically if you cons more than
-`gc-cons-threshold' bytes of Lisp data since previous garbage collection.  */)
+However, if there was overflow in pure space, `garbage-collect'
+returns nil, because real GC can't be done.  */)
      ()
 {
   register struct specbinding *bind;
   struct catchtag *catch;
   struct handler *handler;
-  register struct backtrace *backlist;
   char stack_top_variable;
   register int i;
   int message_p;
@@ -4101,13 +4938,50 @@ Garbage collection happens automatically if you cons more than
   if (abort_on_gc)
     abort ();
 
-  EMACS_GET_TIME (t1);
-
   /* Can't GC if pure storage overflowed because we can't determine
      if something is a pure object or not.  */
   if (pure_bytes_used_before_overflow)
     return Qnil;
 
+  CHECK_CONS_LIST ();
+
+  /* Don't keep undo information around forever.
+     Do this early on, so it is no problem if the user quits.  */
+  {
+    register struct buffer *nextb = all_buffers;
+
+    while (nextb)
+      {
+       /* If a buffer's undo list is Qt, that means that undo is
+          turned off in that buffer.  Calling truncate_undo_list on
+          Qt tends to return NULL, which effectively turns undo back on.
+          So don't call truncate_undo_list if undo_list is Qt.  */
+       if (! NILP (nextb->name) && ! EQ (nextb->undo_list, Qt))
+         truncate_undo_list (nextb);
+
+       /* Shrink buffer gaps, but skip indirect and dead buffers.  */
+       if (nextb->base_buffer == 0 && !NILP (nextb->name))
+         {
+           /* If a buffer's gap size is more than 10% of the buffer
+              size, or larger than 2000 bytes, then shrink it
+              accordingly.  Keep a minimum size of 20 bytes.  */
+           int size = min (2000, max (20, (nextb->text->z_byte / 10)));
+
+           if (nextb->text->gap_size > size)
+             {
+               struct buffer *save_current = current_buffer;
+               current_buffer = nextb;
+               make_gap (-(nextb->text->gap_size - size));
+               current_buffer = save_current;
+             }
+         }
+
+       nextb = nextb->next;
+      }
+  }
+
+  EMACS_GET_TIME (t1);
+
   /* In case user calls debug_print during GC,
      don't let that cause a recursive GC.  */
   consing_since_gc = 0;
@@ -4146,55 +5020,28 @@ Garbage collection happens automatically if you cons more than
 
   shrink_regexp_cache ();
 
-  /* Don't keep undo information around forever.  */
-  {
-    register struct buffer *nextb = all_buffers;
-
-    while (nextb)
-      {
-       /* If a buffer's undo list is Qt, that means that undo is
-          turned off in that buffer.  Calling truncate_undo_list on
-          Qt tends to return NULL, which effectively turns undo back on.
-          So don't call truncate_undo_list if undo_list is Qt.  */
-       if (! EQ (nextb->undo_list, Qt))
-         nextb->undo_list
-           = truncate_undo_list (nextb->undo_list, undo_limit,
-                                 undo_strong_limit);
-
-       /* Shrink buffer gaps, but skip indirect and dead buffers.  */
-       if (nextb->base_buffer == 0 && !NILP (nextb->name))
-         {
-           /* If a buffer's gap size is more than 10% of the buffer
-              size, or larger than 2000 bytes, then shrink it
-              accordingly.  Keep a minimum size of 20 bytes.  */
-           int size = min (2000, max (20, (nextb->text->z_byte / 10)));
-
-           if (nextb->text->gap_size > size)
-             {
-               struct buffer *save_current = current_buffer;
-               current_buffer = nextb;
-               make_gap (-(nextb->text->gap_size - size));
-               current_buffer = save_current;
-             }
-         }
-
-       nextb = nextb->next;
-      }
-  }
-
   gc_in_progress = 1;
 
   /* clear_marks (); */
 
-  /* Mark all the special slots that serve as the roots of accessibility.
-
-     Usually the special slots to mark are contained in particular structures.
-     Then we know no slot is marked twice because the structures don't overlap.
-     In some cases, the structures point to the slots to be marked.
-     For these, we use MARKBIT to avoid double marking of the slot.  */
+  /* Mark all the special slots that serve as the roots of accessibility.  */
 
   for (i = 0; i < staticidx; i++)
-    mark_object (staticvec[i]);
+    mark_object (*staticvec[i]);
+
+  for (bind = specpdl; bind != specpdl_ptr; bind++)
+    {
+      mark_object (bind->symbol);
+      mark_object (bind->old_value);
+    }
+  mark_kboards ();
+
+#ifdef USE_GTK
+  {
+    extern void xg_mark_data ();
+    xg_mark_data ();
+  }
+#endif
 
 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
      || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
@@ -4204,54 +5051,34 @@ Garbage collection happens automatically if you cons more than
     register struct gcpro *tail;
     for (tail = gcprolist; tail; tail = tail->next)
       for (i = 0; i < tail->nvars; i++)
-       if (!XMARKBIT (tail->var[i]))
-         {
-           /* Explicit casting prevents compiler warning about
-              discarding the `volatile' qualifier.  */
-           mark_object ((Lisp_Object *)&tail->var[i]);
-           XMARK (tail->var[i]);
-         }
+       mark_object (tail->var[i]);
   }
 #endif
 
   mark_byte_stack ();
-  for (bind = specpdl; bind != specpdl_ptr; bind++)
-    {
-      /* These casts avoid a warning for discarding `volatile'.  */
-      mark_object ((Lisp_Object *) &bind->symbol);
-      mark_object ((Lisp_Object *) &bind->old_value);
-    }
   for (catch = catchlist; catch; catch = catch->next)
     {
-      mark_object (&catch->tag);
-      mark_object (&catch->val);
+      mark_object (catch->tag);
+      mark_object (catch->val);
     }
   for (handler = handlerlist; handler; handler = handler->next)
     {
-      mark_object (&handler->handler);
-      mark_object (&handler->var);
-    }
-  for (backlist = backtrace_list; backlist; backlist = backlist->next)
-    {
-      if (!XMARKBIT (*backlist->function))
-       {
-         mark_object (backlist->function);
-         XMARK (*backlist->function);
-       }
-      if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
-       i = 0;
-      else
-       i = backlist->nargs - 1;
-      for (; i >= 0; i--)
-       if (!XMARKBIT (backlist->args[i]))
-         {
-           mark_object (&backlist->args[i]);
-           XMARK (backlist->args[i]);
-         }
+      mark_object (handler->handler);
+      mark_object (handler->var);
     }
-  mark_kboards ();
+  mark_backtrace ();
+
+#ifdef HAVE_WINDOW_SYSTEM
+  mark_fringe_data ();
+#endif
+
+#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
+  mark_stack ();
+#endif
 
-  /* Look thru every buffer's undo list
+  /* Everything is now marked, except for the things that require special
+     finalization, i.e. the undo_list.
+     Look thru every buffer's undo list
      for elements that update markers that were not marked,
      and delete them.  */
   {
@@ -4272,7 +5099,7 @@ Garbage collection happens automatically if you cons more than
              {
                if (GC_CONSP (XCAR (tail))
                    && GC_MARKERP (XCAR (XCAR (tail)))
-                   && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
+                   && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
                  {
                    if (NILP (prev))
                      nextb->undo_list = tail = XCDR (tail);
@@ -4289,46 +5116,21 @@ Garbage collection happens automatically if you cons more than
                  }
              }
          }
+       /* Now that we have stripped the elements that need not be in the
+          undo_list any more, we can finally mark the list.  */
+       mark_object (nextb->undo_list);
 
        nextb = nextb->next;
       }
   }
 
-#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
-  mark_stack ();
-#endif
-
-#ifdef USE_GTK
-  {
-    extern void xg_mark_data ();
-    xg_mark_data ();
-  }
-#endif
-
   gc_sweep ();
 
   /* Clear the mark bits that we set in certain root slots.  */
 
-#if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
-     || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
-  for (tail = gcprolist; tail; tail = tail->next)
-    for (i = 0; i < tail->nvars; i++)
-      XUNMARK (tail->var[i]);
-#endif
-
   unmark_byte_stack ();
-  for (backlist = backtrace_list; backlist; backlist = backlist->next)
-    {
-      XUNMARK (*backlist->function);
-      if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
-       i = 0;
-      else
-       i = backlist->nargs - 1;
-      for (; i >= 0; i--)
-       XUNMARK (backlist->args[i]);
-    }
-  XUNMARK (buffer_defaults.name);
-  XUNMARK (buffer_local_symbols.name);
+  VECTOR_UNMARK (&buffer_defaults);
+  VECTOR_UNMARK (&buffer_local_symbols);
 
 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
   dump_zombies ();
@@ -4336,6 +5138,8 @@ Garbage collection happens automatically if you cons more than
 
   UNBLOCK_INPUT;
 
+  CHECK_CONS_LIST ();
+
   /* clear_marks (); */
   gc_in_progress = 0;
 
@@ -4343,6 +5147,24 @@ Garbage collection happens automatically if you cons more than
   if (gc_cons_threshold < 10000)
     gc_cons_threshold = 10000;
 
+  if (FLOATP (Vgc_cons_percentage))
+    { /* Set gc_cons_combined_threshold.  */
+      EMACS_INT total = 0;
+
+      total += total_conses  * sizeof (struct Lisp_Cons);
+      total += total_symbols * sizeof (struct Lisp_Symbol);
+      total += total_markers * sizeof (union Lisp_Misc);
+      total += total_string_size;
+      total += total_vector_size * sizeof (Lisp_Object);
+      total += total_floats  * sizeof (struct Lisp_Float);
+      total += total_intervals * sizeof (struct interval);
+      total += total_strings * sizeof (struct Lisp_String);
+
+      gc_relative_threshold = total * XFLOAT_DATA (Vgc_cons_percentage);
+    }
+  else
+    gc_relative_threshold = 0;
+
   if (garbage_collection_messages)
     {
       if (message_p || minibuf_level > 0)
@@ -4427,7 +5249,7 @@ mark_glyph_matrix (matrix)
            for (; glyph < end_glyph; ++glyph)
              if (GC_STRINGP (glyph->object)
                  && !STRING_MARKED_P (XSTRING (glyph->object)))
-               mark_object (&glyph->object);
+               mark_object (glyph->object);
          }
       }
 }
@@ -4449,7 +5271,7 @@ mark_face_cache (c)
          if (face)
            {
              for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
-               mark_object (&face->lface[j]);
+               mark_object (face->lface[j]);
            }
        }
     }
@@ -4464,10 +5286,10 @@ static void
 mark_image (img)
      struct image *img;
 {
-  mark_object (&img->spec);
+  mark_object (img->spec);
 
   if (!NILP (img->data.lisp_val))
-    mark_object (&img->data.lisp_val);
+    mark_object (img->data.lisp_val);
 }
 
 
@@ -4490,7 +5312,7 @@ mark_image_cache (f)
    all the references contained in it.  */
 
 #define LAST_MARKED_SIZE 500
-Lisp_Object *last_marked[LAST_MARKED_SIZE];
+Lisp_Object last_marked[LAST_MARKED_SIZE];
 int last_marked_index;
 
 /* For debugging--call abort when we cdr down this many
@@ -4500,11 +5322,10 @@ int last_marked_index;
 int mark_object_loop_halt;
 
 void
-mark_object (argptr)
-     Lisp_Object *argptr;
+mark_object (arg)
+     Lisp_Object arg;
 {
-  Lisp_Object *objptr = argptr;
-  register Lisp_Object obj;
+  register Lisp_Object obj = arg;
 #ifdef GC_CHECK_MARKED_OBJECTS
   void *po;
   struct mem_node *m;
@@ -4512,14 +5333,11 @@ mark_object (argptr)
   int cdr_count = 0;
 
  loop:
-  obj = *objptr;
- loop2:
-  XUNMARK (obj);
 
   if (PURE_POINTER_P (XPNTR (obj)))
     return;
 
-  last_marked[last_marked_index++] = objptr;
+  last_marked[last_marked_index++] = obj;
   if (last_marked_index == LAST_MARKED_SIZE)
     last_marked_index = 0;
 
@@ -4589,7 +5407,7 @@ mark_object (argptr)
 
       if (GC_BUFFERP (obj))
        {
-         if (!XMARKBIT (XBUFFER (obj)->name))
+         if (!VECTOR_MARKED_P (XBUFFER (obj)))
            {
 #ifdef GC_CHECK_MARKED_OBJECTS
              if (po != &buffer_defaults && po != &buffer_local_symbols)
@@ -4615,85 +5433,81 @@ mark_object (argptr)
          register EMACS_INT size = ptr->size;
          register int i;
 
-         if (size & ARRAY_MARK_FLAG)
+         if (VECTOR_MARKED_P (ptr))
            break;   /* Already marked */
 
          CHECK_LIVE (live_vector_p);
-         ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
+         VECTOR_MARK (ptr);    /* Else mark it */
          size &= PSEUDOVECTOR_SIZE_MASK;
          for (i = 0; i < size; i++) /* and then mark its elements */
            {
              if (i != COMPILED_CONSTANTS)
-               mark_object (&ptr->contents[i]);
+               mark_object (ptr->contents[i]);
            }
-         /* This cast should be unnecessary, but some Mips compiler complains
-            (MIPS-ABI + SysVR4, DC/OSx, etc).  */
-         objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
+         obj = ptr->contents[COMPILED_CONSTANTS];
          goto loop;
        }
       else if (GC_FRAMEP (obj))
        {
          register struct frame *ptr = XFRAME (obj);
-         register EMACS_INT size = ptr->size;
 
-         if (size & ARRAY_MARK_FLAG) break;   /* Already marked */
-         ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
+         if (VECTOR_MARKED_P (ptr)) break;   /* Already marked */
+         VECTOR_MARK (ptr);                  /* Else mark it */
 
          CHECK_LIVE (live_vector_p);
-         mark_object (&ptr->name);
-         mark_object (&ptr->icon_name);
-         mark_object (&ptr->title);
-         mark_object (&ptr->focus_frame);
-         mark_object (&ptr->selected_window);
-         mark_object (&ptr->minibuffer_window);
-         mark_object (&ptr->param_alist);
-         mark_object (&ptr->scroll_bars);
-         mark_object (&ptr->condemned_scroll_bars);
-         mark_object (&ptr->menu_bar_items);
-         mark_object (&ptr->face_alist);
-         mark_object (&ptr->menu_bar_vector);
-         mark_object (&ptr->buffer_predicate);
-         mark_object (&ptr->buffer_list);
-         mark_object (&ptr->menu_bar_window);
-         mark_object (&ptr->tool_bar_window);
+         mark_object (ptr->name);
+         mark_object (ptr->icon_name);
+         mark_object (ptr->title);
+         mark_object (ptr->focus_frame);
+         mark_object (ptr->selected_window);
+         mark_object (ptr->minibuffer_window);
+         mark_object (ptr->param_alist);
+         mark_object (ptr->scroll_bars);
+         mark_object (ptr->condemned_scroll_bars);
+         mark_object (ptr->menu_bar_items);
+         mark_object (ptr->face_alist);
+         mark_object (ptr->menu_bar_vector);
+         mark_object (ptr->buffer_predicate);
+         mark_object (ptr->buffer_list);
+         mark_object (ptr->menu_bar_window);
+         mark_object (ptr->tool_bar_window);
          mark_face_cache (ptr->face_cache);
 #ifdef HAVE_WINDOW_SYSTEM
          mark_image_cache (ptr);
-         mark_object (&ptr->tool_bar_items);
-         mark_object (&ptr->desired_tool_bar_string);
-         mark_object (&ptr->current_tool_bar_string);
+         mark_object (ptr->tool_bar_items);
+         mark_object (ptr->desired_tool_bar_string);
+         mark_object (ptr->current_tool_bar_string);
 #endif /* HAVE_WINDOW_SYSTEM */
        }
       else if (GC_BOOL_VECTOR_P (obj))
        {
          register struct Lisp_Vector *ptr = XVECTOR (obj);
 
-         if (ptr->size & ARRAY_MARK_FLAG)
+         if (VECTOR_MARKED_P (ptr))
            break;   /* Already marked */
          CHECK_LIVE (live_vector_p);
-         ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
+         VECTOR_MARK (ptr);    /* Else mark it */
        }
       else if (GC_WINDOWP (obj))
        {
          register struct Lisp_Vector *ptr = XVECTOR (obj);
          struct window *w = XWINDOW (obj);
-         register EMACS_INT size = ptr->size;
          register int i;
 
          /* Stop if already marked.  */
-         if (size & ARRAY_MARK_FLAG)
+         if (VECTOR_MARKED_P (ptr))
            break;
 
          /* Mark it.  */
          CHECK_LIVE (live_vector_p);
-         ptr->size |= ARRAY_MARK_FLAG;
+         VECTOR_MARK (ptr);
 
          /* There is no Lisp data above The member CURRENT_MATRIX in
             struct WINDOW.  Stop marking when that slot is reached.  */
          for (i = 0;
               (char *) &ptr->contents[i] < (char *) &w->current_matrix;
               i++)
-           mark_object (&ptr->contents[i]);
+           mark_object (ptr->contents[i]);
 
          /* Mark glyphs for leaf windows.  Marking window matrices is
             sufficient because frame matrices use the same glyph
@@ -4709,38 +5523,36 @@ mark_object (argptr)
       else if (GC_HASH_TABLE_P (obj))
        {
          struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
-         EMACS_INT size = h->size;
 
          /* Stop if already marked.  */
-         if (size & ARRAY_MARK_FLAG)
+         if (VECTOR_MARKED_P (h))
            break;
 
          /* Mark it.  */
          CHECK_LIVE (live_vector_p);
-         h->size |= ARRAY_MARK_FLAG;
+         VECTOR_MARK (h);
 
          /* Mark contents.  */
          /* Do not mark next_free or next_weak.
             Being in the next_weak chain
             should not keep the hash table alive.
             No need to mark `count' since it is an integer.  */
-         mark_object (&h->test);
-         mark_object (&h->weak);
-         mark_object (&h->rehash_size);
-         mark_object (&h->rehash_threshold);
-         mark_object (&h->hash);
-         mark_object (&h->next);
-         mark_object (&h->index);
-         mark_object (&h->user_hash_function);
-         mark_object (&h->user_cmp_function);
+         mark_object (h->test);
+         mark_object (h->weak);
+         mark_object (h->rehash_size);
+         mark_object (h->rehash_threshold);
+         mark_object (h->hash);
+         mark_object (h->next);
+         mark_object (h->index);
+         mark_object (h->user_hash_function);
+         mark_object (h->user_cmp_function);
 
          /* If hash table is not weak, mark all keys and values.
             For weak tables, mark only the vector.  */
          if (GC_NILP (h->weak))
-           mark_object (&h->key_and_value);
+           mark_object (h->key_and_value);
          else
-           XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
-
+           VECTOR_MARK (XVECTOR (h->key_and_value));
        }
       else
        {
@@ -4748,14 +5560,18 @@ mark_object (argptr)
          register EMACS_INT size = ptr->size;
          register int i;
 
-         if (size & ARRAY_MARK_FLAG) break; /* Already marked */
+         if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
          CHECK_LIVE (live_vector_p);
-         ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
+         VECTOR_MARK (ptr);    /* Else mark it */
          if (size & PSEUDOVECTOR_FLAG)
            size &= PSEUDOVECTOR_SIZE_MASK;
 
+         /* Note that this size is not the memory-footprint size, but only
+            the number of Lisp_Object fields that we should trace.
+            The distinction is used e.g. by Lisp_Process which places extra
+            non-Lisp_Object fields at the end of the structure.  */
          for (i = 0; i < size; i++) /* and then mark its elements */
-           mark_object (&ptr->contents[i]);
+           mark_object (ptr->contents[i]);
        }
       break;
 
@@ -4764,12 +5580,12 @@ mark_object (argptr)
        register struct Lisp_Symbol *ptr = XSYMBOL (obj);
        struct Lisp_Symbol *ptrx;
 
-       if (XMARKBIT (ptr->plist)) break;
+       if (ptr->gcmarkbit) break;
        CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
-       XMARK (ptr->plist);
-       mark_object ((Lisp_Object *) &ptr->value);
-       mark_object (&ptr->function);
-       mark_object (&ptr->plist);
+       ptr->gcmarkbit = 1;
+       mark_object (ptr->value);
+       mark_object (ptr->function);
+       mark_object (ptr->plist);
 
        if (!PURE_POINTER_P (XSTRING (ptr->xname)))
          MARK_STRING (XSTRING (ptr->xname));
@@ -4781,48 +5597,45 @@ mark_object (argptr)
        ptr = ptr->next;
        if (ptr)
          {
-           /* For the benefit of the last_marked log.  */
-           objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
            ptrx = ptr;         /* Use of ptrx avoids compiler bug on Sun */
            XSETSYMBOL (obj, ptrx);
-           /* We can't goto loop here because *objptr doesn't contain an
-              actual Lisp_Object with valid datatype field.  */
-           goto loop2;
+           goto loop;
          }
       }
       break;
 
     case Lisp_Misc:
       CHECK_ALLOCATED_AND_LIVE (live_misc_p);
+      if (XMARKER (obj)->gcmarkbit)
+       break;
+      XMARKER (obj)->gcmarkbit = 1;
+
       switch (XMISCTYPE (obj))
        {
-       case Lisp_Misc_Marker:
-         XMARK (XMARKER (obj)->chain);
-         /* DO NOT mark thru the marker's chain.
-            The buffer's markers chain does not preserve markers from gc;
-            instead, markers are removed from the chain when freed by gc.  */
-         break;
-
        case Lisp_Misc_Buffer_Local_Value:
        case Lisp_Misc_Some_Buffer_Local_Value:
          {
            register struct Lisp_Buffer_Local_Value *ptr
              = XBUFFER_LOCAL_VALUE (obj);
-           if (XMARKBIT (ptr->realvalue)) break;
-           XMARK (ptr->realvalue);
            /* If the cdr is nil, avoid recursion for the car.  */
            if (EQ (ptr->cdr, Qnil))
              {
-               objptr = &ptr->realvalue;
+               obj = ptr->realvalue;
                goto loop;
              }
-           mark_object (&ptr->realvalue);
-           mark_object (&ptr->buffer);
-           mark_object (&ptr->frame);
-           objptr = &ptr->cdr;
+           mark_object (ptr->realvalue);
+           mark_object (ptr->buffer);
+           mark_object (ptr->frame);
+           obj = ptr->cdr;
            goto loop;
          }
 
+       case Lisp_Misc_Marker:
+         /* DO NOT mark thru the marker's chain.
+            The buffer's markers chain does not preserve markers from gc;
+            instead, markers are removed from the chain when freed by gc.  */
+         break;
+
        case Lisp_Misc_Intfwd:
        case Lisp_Misc_Boolfwd:
        case Lisp_Misc_Objfwd:
@@ -4834,15 +5647,32 @@ mark_object (argptr)
             are protected with staticpro.  */
          break;
 
+       case Lisp_Misc_Save_Value:
+#if GC_MARK_STACK
+         {
+           register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
+           /* If DOGC is set, POINTER is the address of a memory
+              area containing INTEGER potential Lisp_Objects.  */
+           if (ptr->dogc)
+             {
+               Lisp_Object *p = (Lisp_Object *) ptr->pointer;
+               int nelt;
+               for (nelt = ptr->integer; nelt > 0; nelt--, p++)
+                 mark_maybe_object (*p);
+             }
+         }
+#endif
+         break;
+
        case Lisp_Misc_Overlay:
          {
            struct Lisp_Overlay *ptr = XOVERLAY (obj);
-           if (!XMARKBIT (ptr->plist))
+           mark_object (ptr->start);
+           mark_object (ptr->end);
+           mark_object (ptr->plist);
+           if (ptr->next)
              {
-               XMARK (ptr->plist);
-               mark_object (&ptr->start);
-               mark_object (&ptr->end);
-               objptr = &ptr->plist;
+               XSETMISC (obj, ptr->next);
                goto loop;
              }
          }
@@ -4856,18 +5686,18 @@ mark_object (argptr)
     case Lisp_Cons:
       {
        register struct Lisp_Cons *ptr = XCONS (obj);
-       if (XMARKBIT (ptr->car)) break;
+       if (CONS_MARKED_P (ptr)) break;
        CHECK_ALLOCATED_AND_LIVE (live_cons_p);
-       XMARK (ptr->car);
+       CONS_MARK (ptr);
        /* If the cdr is nil, avoid recursion for the car.  */
-       if (EQ (ptr->cdr, Qnil))
+       if (EQ (ptr->u.cdr, Qnil))
          {
-           objptr = &ptr->car;
+           obj = ptr->car;
            cdr_count = 0;
            goto loop;
          }
-       mark_object (&ptr->car);
-       objptr = &ptr->cdr;
+       mark_object (ptr->car);
+       obj = ptr->u.cdr;
        cdr_count++;
        if (cdr_count == mark_object_loop_halt)
          abort ();
@@ -4876,7 +5706,7 @@ mark_object (argptr)
 
     case Lisp_Float:
       CHECK_ALLOCATED_AND_LIVE (live_float_p);
-      XMARK (XFLOAT (obj)->type);
+      FLOAT_MARK (XFLOAT (obj));
       break;
 
     case Lisp_Int:
@@ -4898,55 +5728,35 @@ mark_buffer (buf)
      Lisp_Object buf;
 {
   register struct buffer *buffer = XBUFFER (buf);
-  register Lisp_Object *ptr;
+  register Lisp_Object *ptr, tmp;
   Lisp_Object base_buffer;
 
-  /* This is the buffer's markbit */
-  mark_object (&buffer->name);
-  XMARK (buffer->name);
+  VECTOR_MARK (buffer);
 
   MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
 
-  if (CONSP (buffer->undo_list))
-    {
-      Lisp_Object tail;
-      tail = buffer->undo_list;
-
-      while (CONSP (tail))
-       {
-         register struct Lisp_Cons *ptr = XCONS (tail);
-
-         if (XMARKBIT (ptr->car))
-           break;
-         XMARK (ptr->car);
-         if (GC_CONSP (ptr->car)
-             && ! XMARKBIT (XCAR (ptr->car))
-             && GC_MARKERP (XCAR (ptr->car)))
-           {
-             XMARK (XCAR_AS_LVALUE (ptr->car));
-             mark_object (&XCDR_AS_LVALUE (ptr->car));
-           }
-         else
-           mark_object (&ptr->car);
-
-         if (CONSP (ptr->cdr))
-           tail = ptr->cdr;
-         else
-           break;
-       }
+  /* For now, we just don't mark the undo_list.  It's done later in
+     a special way just before the sweep phase, and after stripping
+     some of its elements that are not needed any more.  */
 
-      mark_object (&XCDR_AS_LVALUE (tail));
+  if (buffer->overlays_before)
+    {
+      XSETMISC (tmp, buffer->overlays_before);
+      mark_object (tmp);
+    }
+  if (buffer->overlays_after)
+    {
+      XSETMISC (tmp, buffer->overlays_after);
+      mark_object (tmp);
     }
-  else
-    mark_object (&buffer->undo_list);
 
-  for (ptr = &buffer->name + 1;
+  for (ptr = &buffer->name;
        (char *)ptr < (char *)buffer + sizeof (struct buffer);
        ptr++)
-    mark_object (ptr);
+    mark_object (*ptr);
 
   /* If this is an indirect buffer, mark its base buffer.  */
-  if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
+  if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
     {
       XSETBUFFER (base_buffer, buffer->base_buffer);
       mark_buffer (base_buffer);
@@ -4954,34 +5764,6 @@ mark_buffer (buf)
 }
 
 
-/* Mark the pointers in the kboard objects.  */
-
-static void
-mark_kboards ()
-{
-  KBOARD *kb;
-  Lisp_Object *p;
-  for (kb = all_kboards; kb; kb = kb->next_kboard)
-    {
-      if (kb->kbd_macro_buffer)
-       for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
-         mark_object (p);
-      mark_object (&kb->Voverriding_terminal_local_map);
-      mark_object (&kb->Vlast_command);
-      mark_object (&kb->Vreal_last_command);
-      mark_object (&kb->Vprefix_arg);
-      mark_object (&kb->Vlast_prefix_arg);
-      mark_object (&kb->kbd_queue);
-      mark_object (&kb->defining_kbd_macro);
-      mark_object (&kb->Vlast_kbd_macro);
-      mark_object (&kb->Vsystem_key_alist);
-      mark_object (&kb->system_key_syms);
-      mark_object (&kb->Vdefault_minibuffer_frame);
-      mark_object (&kb->echo_string);
-    }
-}
-
-
 /* Value is non-zero if OBJ will survive the current GC because it's
    either marked or does not need to be marked to survive.  */
 
@@ -4998,60 +5780,27 @@ survives_gc_p (obj)
       break;
 
     case Lisp_Symbol:
-      survives_p = XMARKBIT (XSYMBOL (obj)->plist);
+      survives_p = XSYMBOL (obj)->gcmarkbit;
       break;
 
     case Lisp_Misc:
-      switch (XMISCTYPE (obj))
-       {
-       case Lisp_Misc_Marker:
-         survives_p = XMARKBIT (obj);
-         break;
-
-       case Lisp_Misc_Buffer_Local_Value:
-       case Lisp_Misc_Some_Buffer_Local_Value:
-         survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
-         break;
-
-       case Lisp_Misc_Intfwd:
-       case Lisp_Misc_Boolfwd:
-       case Lisp_Misc_Objfwd:
-       case Lisp_Misc_Buffer_Objfwd:
-       case Lisp_Misc_Kboard_Objfwd:
-         survives_p = 1;
-         break;
-
-       case Lisp_Misc_Overlay:
-         survives_p = XMARKBIT (XOVERLAY (obj)->plist);
-         break;
-
-       default:
-         abort ();
-       }
+      survives_p = XMARKER (obj)->gcmarkbit;
       break;
 
     case Lisp_String:
-      {
-       struct Lisp_String *s = XSTRING (obj);
-       survives_p = STRING_MARKED_P (s);
-      }
+      survives_p = STRING_MARKED_P (XSTRING (obj));
       break;
 
     case Lisp_Vectorlike:
-      if (GC_BUFFERP (obj))
-       survives_p = XMARKBIT (XBUFFER (obj)->name);
-      else if (GC_SUBRP (obj))
-       survives_p = 1;
-      else
-       survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
+      survives_p = GC_SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
       break;
 
     case Lisp_Cons:
-      survives_p = XMARKBIT (XCAR (obj));
+      survives_p = CONS_MARKED_P (XCONS (obj));
       break;
 
     case Lisp_Float:
-      survives_p = XMARKBIT (XFLOAT (obj)->type);
+      survives_p = FLOAT_MARKED_P (XFLOAT (obj));
       break;
 
     default:
@@ -5092,10 +5841,10 @@ gc_sweep ()
        register int i;
        int this_free = 0;
        for (i = 0; i < lim; i++)
-         if (!XMARKBIT (cblk->conses[i].car))
+         if (!CONS_MARKED_P (&cblk->conses[i]))
            {
              this_free++;
-             *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
+             cblk->conses[i].u.chain = cons_free_list;
              cons_free_list = &cblk->conses[i];
 #if GC_MARK_STACK
              cons_free_list->car = Vdead;
@@ -5104,7 +5853,7 @@ gc_sweep ()
          else
            {
              num_used++;
-             XUNMARK (cblk->conses[i].car);
+             CONS_UNMARK (&cblk->conses[i]);
            }
        lim = CONS_BLOCK_SIZE;
        /* If this block contains only free conses and we have already
@@ -5114,8 +5863,8 @@ gc_sweep ()
          {
            *cprev = cblk->next;
            /* Unhook from the free list.  */
-           cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
-           lisp_free (cblk);
+           cons_free_list = cblk->conses[0].u.chain;
+           lisp_align_free (cblk);
            n_cons_blocks--;
          }
        else
@@ -5142,19 +5891,16 @@ gc_sweep ()
        register int i;
        int this_free = 0;
        for (i = 0; i < lim; i++)
-         if (!XMARKBIT (fblk->floats[i].type))
+         if (!FLOAT_MARKED_P (&fblk->floats[i]))
            {
              this_free++;
-             *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
+             fblk->floats[i].u.chain = float_free_list;
              float_free_list = &fblk->floats[i];
-#if GC_MARK_STACK
-             float_free_list->type = Vdead;
-#endif
            }
          else
            {
              num_used++;
-             XUNMARK (fblk->floats[i].type);
+             FLOAT_UNMARK (&fblk->floats[i]);
            }
        lim = FLOAT_BLOCK_SIZE;
        /* If this block contains only free floats and we have already
@@ -5164,8 +5910,8 @@ gc_sweep ()
          {
            *fprev = fblk->next;
            /* Unhook from the free list.  */
-           float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
-           lisp_free (fblk);
+           float_free_list = fblk->floats[0].u.chain;
+           lisp_align_free (fblk);
            n_float_blocks--;
          }
        else
@@ -5194,7 +5940,7 @@ gc_sweep ()
 
        for (i = 0; i < lim; i++)
          {
-           if (! XMARKBIT (iblk->intervals[i].plist))
+           if (!iblk->intervals[i].gcmarkbit)
              {
                SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
                interval_free_list = &iblk->intervals[i];
@@ -5203,7 +5949,7 @@ gc_sweep ()
            else
              {
                num_used++;
-               XUNMARK (iblk->intervals[i].plist);
+               iblk->intervals[i].gcmarkbit = 0;
              }
          }
        lim = INTERVAL_BLOCK_SIZE;
@@ -5250,9 +5996,9 @@ gc_sweep ()
               so we conservatively assume that it is live.  */
            int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
 
-           if (!XMARKBIT (sym->plist) && !pure_p)
+           if (!sym->gcmarkbit && !pure_p)
              {
-               *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
+               sym->next = symbol_free_list;
                symbol_free_list = sym;
 #if GC_MARK_STACK
                symbol_free_list->function = Vdead;
@@ -5264,7 +6010,7 @@ gc_sweep ()
                ++num_used;
                if (!pure_p)
                  UNMARK_STRING (XSTRING (sym->xname));
-               XUNMARK (sym->plist);
+               sym->gcmarkbit = 0;
              }
          }
 
@@ -5276,7 +6022,7 @@ gc_sweep ()
          {
            *sprev = sblk->next;
            /* Unhook from the free list.  */
-           symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
+           symbol_free_list = sblk->symbols[0].next;
            lisp_free (sblk);
            n_symbol_blocks--;
          }
@@ -5304,42 +6050,13 @@ gc_sweep ()
       {
        register int i;
        int this_free = 0;
-       EMACS_INT already_free = -1;
 
        for (i = 0; i < lim; i++)
          {
-           Lisp_Object *markword;
-           switch (mblk->markers[i].u_marker.type)
-             {
-             case Lisp_Misc_Marker:
-               markword = &mblk->markers[i].u_marker.chain;
-               break;
-             case Lisp_Misc_Buffer_Local_Value:
-             case Lisp_Misc_Some_Buffer_Local_Value:
-               markword = &mblk->markers[i].u_buffer_local_value.realvalue;
-               break;
-             case Lisp_Misc_Overlay:
-               markword = &mblk->markers[i].u_overlay.plist;
-               break;
-             case Lisp_Misc_Free:
-               /* If the object was already free, keep it
-                  on the free list.  */
-               markword = (Lisp_Object *) &already_free;
-               break;
-             default:
-               markword = 0;
-               break;
-             }
-           if (markword && !XMARKBIT (*markword))
+           if (!mblk->markers[i].u_marker.gcmarkbit)
              {
-               Lisp_Object tem;
                if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
-                 {
-                   /* tem1 avoids Sun compiler bug */
-                   struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
-                   XSETMARKER (tem, tem1);
-                   unchain_marker (tem);
-                 }
+                 unchain_marker (&mblk->markers[i].u_marker);
                /* Set the type of the freed object to Lisp_Misc_Free.
                   We could leave the type alone, since nobody checks it,
                   but this might catch bugs faster.  */
@@ -5351,8 +6068,7 @@ gc_sweep ()
            else
              {
                num_used++;
-               if (markword)
-                 XUNMARK (*markword);
+               mblk->markers[i].u_marker.gcmarkbit = 0;
              }
          }
        lim = MARKER_BLOCK_SIZE;
@@ -5383,7 +6099,7 @@ gc_sweep ()
     register struct buffer *buffer = all_buffers, *prev = 0, *next;
 
     while (buffer)
-      if (!XMARKBIT (buffer->name))
+      if (!VECTOR_MARKED_P (buffer))
        {
          if (prev)
            prev->next = buffer->next;
@@ -5395,7 +6111,7 @@ gc_sweep ()
        }
       else
        {
-         XUNMARK (buffer->name);
+         VECTOR_UNMARK (buffer);
          UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
          prev = buffer, buffer = buffer->next;
        }
@@ -5407,7 +6123,7 @@ gc_sweep ()
     total_vector_size = 0;
 
     while (vector)
-      if (!(vector->size & ARRAY_MARK_FLAG))
+      if (!VECTOR_MARKED_P (vector))
        {
          if (prev)
            prev->next = vector->next;
@@ -5421,7 +6137,7 @@ gc_sweep ()
        }
       else
        {
-         vector->size &= ~ARRAY_MARK_FLAG;
+         VECTOR_UNMARK (vector);
          if (vector->size & PSEUDOVECTOR_FLAG)
            total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
          else
@@ -5506,6 +6222,9 @@ init_alloc_once ()
   pure_bytes_used = 0;
   pure_bytes_used_before_overflow = 0;
 
+  /* Initialize the list of free aligned blocks.  */
+  free_ablock = NULL;
+
 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
   mem_init ();
   Vdead = make_pure_string ("DEAD", 4, 4, 0);
@@ -5531,7 +6250,7 @@ init_alloc_once ()
   malloc_hysteresis = 0;
 #endif
 
-  spare_memory = (char *) malloc (SPARE_MEMORY);
+  refill_memory_reserve ();
 
   ignore_warnings = 0;
   gcprolist = 0;
@@ -5539,6 +6258,8 @@ init_alloc_once ()
   staticidx = 0;
   consing_since_gc = 0;
   gc_cons_threshold = 100000 * sizeof (Lisp_Object);
+  gc_relative_threshold = 0;
+
 #ifdef VIRT_ADDR_VARIES
   malloc_sbrk_unused = 1<<22;  /* A large number */
   malloc_sbrk_used = 100000;   /* as reasonable as any number */
@@ -5570,7 +6291,15 @@ allocated since the last garbage collection.  All data types count.
 Garbage collection happens automatically only when `eval' is called.
 
 By binding this temporarily to a large number, you can effectively
-prevent garbage collection during a part of the program.  */);
+prevent garbage collection during a part of the program.
+See also `gc-cons-percentage'.  */);
+
+  DEFVAR_LISP ("gc-cons-percentage", &Vgc_cons_percentage,
+              doc: /* *Portion of the heap used for allocation.
+Garbage collection can happen automatically once this portion of the heap
+has been allocated since the last garbage collection.
+If this portion is smaller than `gc-cons-threshold', this is ignored.  */);
+  Vgc_cons_percentage = make_float (0.1);
 
   DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
              doc: /* Number of bytes of sharable Lisp data allocated so far.  */);
@@ -5603,21 +6332,6 @@ prevent garbage collection during a part of the program.  */);
               doc: /* Non-nil means loading Lisp code in order to dump an executable.
 This means that certain objects should be allocated in shared (pure) space.  */);
 
-  DEFVAR_INT ("undo-limit", &undo_limit,
-             doc: /* Keep no more undo information once it exceeds this size.
-This limit is applied when garbage collection happens.
-The size is counted as the number of bytes occupied,
-which includes both saved text and other data.  */);
-  undo_limit = 20000;
-
-  DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
-             doc: /* Don't keep more than this much size of undo information.
-A command which pushes past this size is itself forgotten.
-This limit is applied when garbage collection happens.
-The size is counted as the number of bytes occupied,
-which includes both saved text and other data.  */);
-  undo_strong_limit = 30000;
-
   DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
               doc: /* Non-nil means display messages at start and end of garbage collection.  */);
   garbage_collection_messages = 0;
@@ -5637,7 +6351,7 @@ which includes both saved text and other data.  */);
             build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
 
   DEFVAR_LISP ("memory-full", &Vmemory_full,
-              doc: /* Non-nil means we are handling a memory-full error.  */);
+              doc: /* Non-nil means Emacs cannot get much more Lisp memory.  */);
   Vmemory_full = Qnil;
 
   staticpro (&Qgc_cons_threshold);
@@ -5648,11 +6362,9 @@ which includes both saved text and other data.  */);
 
   DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
               doc: /* Accumulated time elapsed in garbage collections.
-The time is in seconds as a floating point value.
-Programs may reset this to get statistics in a specific period.  */);
+The time is in seconds as a floating point value.  */);
   DEFVAR_INT ("gcs-done", &gcs_done,
-             doc: /* Accumulated number of garbage collections done.
-Programs may reset this to get statistics in a specific period.  */);
+             doc: /* Accumulated number of garbage collections done.  */);
 
   defsubr (&Scons);
   defsubr (&Slist);
@@ -5674,3 +6386,6 @@ Programs may reset this to get statistics in a specific period.  */);
   defsubr (&Sgc_status);
 #endif
 }
+
+/* arch-tag: 6695ca10-e3c5-4c2c-8bc3-ed26a7dda857
+   (do not change this comment) */