]> code.delx.au - gnu-emacs/blobdiff - src/alloc.c
*** empty log message ***
[gnu-emacs] / src / alloc.c
index 0b80fd5d9e70dc5f673dcfe743605d83a121f1d8..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,01,02,03,2004
-      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,13 +16,17 @@ 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
 #endif
@@ -31,6 +35,10 @@ Boston, MA 02111-1307, USA.  */
 
 #include <signal.h>
 
+#ifdef HAVE_GTK_AND_PTHREAD
+#include <pthread.h>
+#endif
+
 /* This file is part of the core Lisp implementation, and thus must
    deal with the real data structures.  If the Lisp implementation is
    replaced, this file likely will not be used.  */
@@ -62,6 +70,14 @@ Boston, MA 02111-1307, USA.  */
 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>
@@ -85,20 +101,67 @@ 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 |= ARRAY_MARK_FLAG)
 #define UNMARK_STRING(S)       ((S)->size &= ~ARRAY_MARK_FLAG)
-#define STRING_MARKED_P(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)
+#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
@@ -123,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;
@@ -151,12 +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;
-EMACS_INT undo_outer_limit;
-
 /* Number of live and free conses etc.  */
 
 static int total_conses, total_markers, total_symbols, total_vector_size;
@@ -164,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)
 
@@ -186,8 +255,11 @@ Lisp_Object Vmemory_full;
 
 #ifndef HAVE_SHM
 
-/* Force it into data space!  Initialize it to a nonzero value;
-   otherwise some compilers put it into BSS.  */
+/* 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)] = {1,};
 #define PUREBEG (char *) pure
@@ -263,6 +335,7 @@ 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 */
@@ -297,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
@@ -397,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
@@ -457,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
@@ -504,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)
@@ -513,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 *
@@ -563,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.  */
 }
 
 
@@ -579,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)
@@ -647,6 +887,12 @@ lisp_free (block)
 /* 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.  */
 
+/* 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)
@@ -657,12 +903,13 @@ lisp_free (block)
    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.
-   But testing shows that those 1020 will most of the time be efficiently
-   used by malloc to place other objects, so a value of 0 is still preferable
-   unless you have a lot of cons&floats and virtually nothing else.  */
+   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 aligned_block *) - BLOCK_PADDING)
+  (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
 
 /* Internal data structures and constants.  */
 
@@ -711,7 +958,7 @@ struct ablocks
 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
 
 /* Pointer to the (not necessarily aligned) malloc block.  */
-#ifdef HAVE_POSIX_MEMALIGN
+#ifdef USE_POSIX_MEMALIGN
 #define ABLOCKS_BASE(abase) (abase)
 #else
 #define ABLOCKS_BASE(abase) \
@@ -752,7 +999,7 @@ lisp_align_malloc (nbytes, type)
       mallopt (M_MMAP_MAX, 0);
 #endif
 
-#ifdef HAVE_POSIX_MEMALIGN
+#ifdef USE_POSIX_MEMALIGN
       {
        int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
        if (err)
@@ -868,6 +1115,9 @@ lisp_align_free (block)
        }
       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;
@@ -886,34 +1136,40 @@ allocate_buffer ()
 }
 
 \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)
@@ -941,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);
@@ -1009,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;
@@ -1019,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
@@ -1070,17 +1315,43 @@ 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.  */
+
+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.  */
 
 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;
@@ -1094,6 +1365,7 @@ uninterrupt_malloc ()
   __realloc_hook = emacs_blocked_realloc;
 }
 
+#endif /* not SYNC_INPUT */
 #endif /* not SYSTEM_MALLOC */
 
 
@@ -1160,6 +1432,12 @@ make_interval ()
 {
   INTERVAL val;
 
+  /* eassert (!handling_signal); */
+
+#ifndef SYNC_INPUT
+  BLOCK_INPUT;
+#endif
+
   if (interval_free_list)
     {
       val = interval_free_list;
@@ -1181,6 +1459,11 @@ 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);
@@ -1238,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;
@@ -1409,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.  */
@@ -1432,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
@@ -1496,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);
     }
 }
 
@@ -1529,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.  */
 
@@ -1537,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)
@@ -1560,10 +1890,16 @@ allocate_string ()
       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);
 
@@ -1611,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)
     {
@@ -1626,14 +1968,18 @@ allocate_string_data (s, nchars, nbytes)
          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;
@@ -1644,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);
@@ -1661,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
@@ -1673,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
@@ -1778,9 +2130,13 @@ sweep_strings ()
        }
     }
 
+  check_string_free_list ();
+
   string_blocks = live_blocks;
   free_large_strings ();
   compact_small_strings ();
+
+  check_string_free_list ();
 }
 
 
@@ -1852,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);
                }
 
@@ -1943,7 +2309,7 @@ INIT must be an integer that represents a character.  */)
 
 
 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;
@@ -2215,7 +2581,7 @@ void
 free_float (ptr)
      struct Lisp_Float *ptr;
 {
-  *(struct Lisp_Float **)&ptr->data = float_free_list;
+  ptr->u.chain = float_free_list;
   float_free_list = ptr;
 }
 
@@ -2228,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
     {
@@ -2253,6 +2625,10 @@ make_float (float_value)
       float_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   XFLOAT_DATA (val) = float_value;
   eassert (!FLOAT_MARKED_P (XFLOAT (val)));
   consing_since_gc += sizeof (struct Lisp_Float);
@@ -2333,7 +2709,7 @@ 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
@@ -2347,12 +2723,18 @@ 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
     {
@@ -2371,6 +2753,10 @@ DEFUN ("cons", Fcons, Scons, 2, 2, 0,
       cons_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   XSETCAR (val, car);
   XSETCDR (val, cdr);
   eassert (!CONS_MARKED_P (XCONS (val)));
@@ -2379,6 +2765,17 @@ DEFUN ("cons", Fcons, Scons, 2, 2, 0,
   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.  */
 
@@ -2517,6 +2914,9 @@ allocate_vectorlike (len, type)
   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);
 
@@ -2530,8 +2930,17 @@ allocate_vectorlike (len, type)
   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;
 }
@@ -2598,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;
 }
@@ -2674,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;
 }
@@ -2810,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
     {
@@ -2831,6 +3250,10 @@ Its value and function definition are void, and its property list is nil.  */)
       symbol_block_index++;
     }
 
+#ifndef SYNC_INPUT
+  UNBLOCK_INPUT;
+#endif
+
   p = XSYMBOL (val);
   p->xname = name;
   p->plist = Qnil;
@@ -2890,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);
@@ -2906,17 +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]);
       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.  */
@@ -2934,6 +3382,7 @@ make_save_value (pointer, integer)
   p = XSAVE_VALUE (val);
   p->pointer = pointer;
   p->integer = integer;
+  p->dogc = 0;
   return val;
 }
 
@@ -2962,12 +3411,7 @@ free_marker (marker)
      Lisp_Object marker;
 {
   unchain_marker (XMARKER (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++;
+  free_misc (marker);
 }
 
 \f
@@ -3011,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
@@ -4058,16 +4579,107 @@ mark_stack ()
 #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;
+
+    case MEM_TYPE_BUFFER:
+      return live_buffer_p (m, p);
+
+    case MEM_TYPE_CONS:
+      return live_cons_p (m, p);
+
+    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
+}
+
+
+
 \f
 /***********************************************************************
                       Pure Storage Management
@@ -4126,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));
 }
 
@@ -4213,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)
@@ -4326,13 +4938,50 @@ returns nil, because real GC can't be done.  */)
   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;
@@ -4371,42 +5020,6 @@ returns nil, because real GC can't be done.  */)
 
   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, undo_outer_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 (); */
@@ -4416,6 +5029,20 @@ returns nil, because real GC can't be done.  */)
   for (i = 0; i < staticidx; 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)
   mark_stack ();
@@ -4429,11 +5056,6 @@ returns nil, because real GC can't be done.  */)
 #endif
 
   mark_byte_stack ();
-  for (bind = specpdl; bind != specpdl_ptr; bind++)
-    {
-      mark_object (bind->symbol);
-      mark_object (bind->old_value);
-    }
   for (catch = catchlist; catch; catch = catch->next)
     {
       mark_object (catch->tag);
@@ -4445,17 +5067,13 @@ returns nil, because real GC can't be done.  */)
       mark_object (handler->var);
     }
   mark_backtrace ();
-  mark_kboards ();
 
-#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
-  mark_stack ();
+#ifdef HAVE_WINDOW_SYSTEM
+  mark_fringe_data ();
 #endif
 
-#ifdef USE_GTK
-  {
-    extern void xg_mark_data ();
-    xg_mark_data ();
-  }
+#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
+  mark_stack ();
 #endif
 
   /* Everything is now marked, except for the things that require special
@@ -4520,6 +5138,8 @@ returns nil, because real GC can't be done.  */)
 
   UNBLOCK_INPUT;
 
+  CHECK_CONS_LIST ();
+
   /* clear_marks (); */
   gc_in_progress = 0;
 
@@ -4527,6 +5147,24 @@ returns nil, because real GC can't be done.  */)
   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)
@@ -4928,6 +5566,10 @@ mark_object (arg)
          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]);
        }
@@ -4967,6 +5609,7 @@ mark_object (arg)
       if (XMARKER (obj)->gcmarkbit)
        break;
       XMARKER (obj)->gcmarkbit = 1;
+
       switch (XMISCTYPE (obj))
        {
        case Lisp_Misc_Buffer_Local_Value:
@@ -4991,6 +5634,8 @@ mark_object (arg)
          /* 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:
@@ -5000,7 +5645,23 @@ mark_object (arg)
             since all markable slots in current buffer marked anyway.  */
          /* Don't need to do Lisp_Objfwd, since the places they point
             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:
@@ -5029,14 +5690,14 @@ mark_object (arg)
        CHECK_ALLOCATED_AND_LIVE (live_cons_p);
        CONS_MARK (ptr);
        /* If the cdr is nil, avoid recursion for the car.  */
-       if (EQ (ptr->cdr, Qnil))
+       if (EQ (ptr->u.cdr, Qnil))
          {
            obj = ptr->car;
            cdr_count = 0;
            goto loop;
          }
        mark_object (ptr->car);
-       obj = ptr->cdr;
+       obj = ptr->u.cdr;
        cdr_count++;
        if (cdr_count == mark_object_loop_halt)
          abort ();
@@ -5183,7 +5844,7 @@ gc_sweep ()
          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;
@@ -5202,7 +5863,7 @@ gc_sweep ()
          {
            *cprev = cblk->next;
            /* Unhook from the free list.  */
-           cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
+           cons_free_list = cblk->conses[0].u.chain;
            lisp_align_free (cblk);
            n_cons_blocks--;
          }
@@ -5233,7 +5894,7 @@ gc_sweep ()
          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];
            }
          else
@@ -5249,7 +5910,7 @@ gc_sweep ()
          {
            *fprev = fblk->next;
            /* Unhook from the free list.  */
-           float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
+           float_free_list = fblk->floats[0].u.chain;
            lisp_align_free (fblk);
            n_float_blocks--;
          }
@@ -5337,7 +5998,7 @@ gc_sweep ()
 
            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;
@@ -5361,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--;
          }
@@ -5589,7 +6250,7 @@ init_alloc_once ()
   malloc_hysteresis = 0;
 #endif
 
-  spare_memory = (char *) malloc (SPARE_MEMORY);
+  refill_memory_reserve ();
 
   ignore_warnings = 0;
   gcprolist = 0;
@@ -5597,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 */
@@ -5628,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.  */);
@@ -5661,29 +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 previous command which pushes the undo list past this size
-is entirely forgotten when GC happens.
-The size is counted as the number of bytes occupied,
-which includes both saved text and other data.  */);
-  undo_strong_limit = 30000;
-
-  DEFVAR_INT ("undo-outer-limit", &undo_outer_limit,
-             doc: /* Don't keep more than this much size of undo information.
-If the current command has produced more than this much undo information,
-GC discards it.  This is a last-ditch limit to prevent memory overflow.
-The size is counted as the number of bytes occupied,
-which includes both saved text and other data.  */);
-  undo_outer_limit = 300000;
-
   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;
@@ -5703,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);