use xmalloc_unsafe in memory_full
[bpt/emacs.git] / src / alloc.c
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2014 Free Software
4 Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include <config.h>
22
23 #include <stdio.h>
24
25 #ifdef ENABLE_CHECKING
26 #include <signal.h> /* For SIGABRT. */
27 #endif
28
29 #ifdef HAVE_PTHREAD
30 #include <pthread.h>
31 #endif
32
33 #include <gc.h>
34
35 #include "lisp.h"
36 #include "process.h"
37 #include "intervals.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "window.h"
41 #include "keyboard.h"
42 #include "frame.h"
43 #include "termhooks.h" /* For struct terminal. */
44 #ifdef HAVE_WINDOW_SYSTEM
45 #include TERM_HEADER
46 #endif /* HAVE_WINDOW_SYSTEM */
47
48 #include <verify.h>
49 #include <execinfo.h> /* For backtrace. */
50
51 #if (defined ENABLE_CHECKING \
52 && defined HAVE_VALGRIND_VALGRIND_H \
53 && !defined USE_VALGRIND)
54 # define USE_VALGRIND 1
55 #endif
56
57 #if USE_VALGRIND
58 #include <valgrind/valgrind.h>
59 #include <valgrind/memcheck.h>
60 static bool valgrind_p;
61 #endif
62
63 #include <unistd.h>
64 #include <fcntl.h>
65
66 #ifdef USE_GTK
67 # include "gtkutil.h"
68 #endif
69 #ifdef WINDOWSNT
70 #include "w32.h"
71 #include "w32heap.h" /* for sbrk */
72 #endif
73
74 /* Default value of gc_cons_threshold (see below). */
75
76 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
77
78 /* Global variables. */
79 struct emacs_globals globals;
80
81 /* Number of bytes of consing done since the last gc. */
82
83 EMACS_INT consing_since_gc;
84
85 /* Similar minimum, computed from Vgc_cons_percentage. */
86
87 EMACS_INT gc_relative_threshold;
88
89 /* Minimum number of bytes of consing since GC before next GC,
90 when memory is full. */
91
92 EMACS_INT memory_full_cons_threshold = 1 << 10;
93
94 /* True during GC. */
95
96 bool gc_in_progress;
97
98 /* True means abort if try to GC.
99 This is for code which is written on the assumption that
100 no GC will happen, so as to verify that assumption. */
101
102 bool abort_on_gc;
103
104 /* Number of live and free conses etc. */
105
106 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
107 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
108 static EMACS_INT total_free_floats, total_floats;
109
110 /* Points to memory space allocated as "spare", to be freed if we run
111 out of memory. */
112
113 static void *spare_memory;
114
115 /* Amount of spare memory to keep in large reserve block, or to see
116 whether this much is available when malloc fails on a larger request. */
117
118 #define SPARE_MEMORY (1 << 15)
119
120 /* If nonzero, this is a warning delivered by malloc and not yet
121 displayed. */
122
123 const char *pending_malloc_warning;
124
125 static Lisp_Object Qgc_cons_threshold;
126 Lisp_Object Qchar_table_extra_slots;
127
128 /* Hook run after GC has finished. */
129
130 static Lisp_Object Qpost_gc_hook;
131
132 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
133 static void refill_memory_reserve (void);
134 #endif
135 static Lisp_Object make_empty_string (int);
136 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
137
138 #ifndef DEADP
139 # define DEADP(x) 0
140 #endif
141
142 /* Recording what needs to be marked for gc. */
143
144 struct gcpro *gcprolist;
145
146 static void
147 XFLOAT_INIT (Lisp_Object f, double n)
148 {
149 XFLOAT (f)->u.data = n;
150 }
151
152 \f
153 /************************************************************************
154 Malloc
155 ************************************************************************/
156
157 /* Function malloc calls this if it finds we are near exhausting storage. */
158
159 void
160 malloc_warning (const char *str)
161 {
162 pending_malloc_warning = str;
163 }
164
165
166 /* Display an already-pending malloc warning. */
167
168 void
169 display_malloc_warning (void)
170 {
171 call3 (intern ("display-warning"),
172 intern ("alloc"),
173 build_string (pending_malloc_warning),
174 intern ("emergency"));
175 pending_malloc_warning = 0;
176 }
177 \f
178 /* Called if we can't allocate relocatable space for a buffer. */
179
180 void
181 buffer_memory_full (ptrdiff_t nbytes)
182 {
183 /* If buffers use the relocating allocator, no need to free
184 spare_memory, because we may have plenty of malloc space left
185 that we could get, and if we don't, the malloc that fails will
186 itself cause spare_memory to be freed. If buffers don't use the
187 relocating allocator, treat this like any other failing
188 malloc. */
189
190 #ifndef REL_ALLOC
191 memory_full (nbytes);
192 #else
193 /* This used to call error, but if we've run out of memory, we could
194 get infinite recursion trying to build the string. */
195 xsignal (Qnil, Vmemory_signal_data);
196 #endif
197 }
198
199 /* Like GC_MALLOC but check for no memory. */
200
201 void *
202 xmalloc (size_t size)
203 {
204 void *val = GC_MALLOC (size);
205 if (!val && size)
206 memory_full (size);
207 return val;
208 }
209
210 /* Like the above, but zeroes out the memory just allocated. */
211
212 void *
213 xzalloc (size_t size)
214 {
215 return xmalloc (size);
216 }
217
218 /* Like GC_REALLOC but check for no memory. */
219
220 void *
221 xrealloc (void *block, size_t size)
222 {
223 void *val = GC_REALLOC (block, size);
224 if (!val && size)
225 memory_full (size);
226 return val;
227 }
228
229 void
230 xfree (void *block)
231 {
232 return;
233 }
234
235 /* Allocate memory, but if memory is exhausted, return NULL instead of
236 signalling an error. */
237
238 void *
239 xmalloc_unsafe (size_t size)
240 {
241 return GC_MALLOC (size);
242 }
243
244 /* Other parts of Emacs pass large int values to allocator functions
245 expecting ptrdiff_t. This is portable in practice, but check it to
246 be safe. */
247 verify (INT_MAX <= PTRDIFF_MAX);
248
249
250 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
251 Signal an error on memory exhaustion. */
252
253 void *
254 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
255 {
256 eassert (0 <= nitems && 0 < item_size);
257 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
258 memory_full (SIZE_MAX);
259 return xmalloc (nitems * item_size);
260 }
261
262
263 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
264 Signal an error on memory exhaustion. */
265
266 void *
267 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
268 {
269 eassert (0 <= nitems && 0 < item_size);
270 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
271 memory_full (SIZE_MAX);
272 return xrealloc (pa, nitems * item_size);
273 }
274
275
276 /* Grow PA, which points to an array of *NITEMS items, and return the
277 location of the reallocated array, updating *NITEMS to reflect its
278 new size. The new array will contain at least NITEMS_INCR_MIN more
279 items, but will not contain more than NITEMS_MAX items total.
280 ITEM_SIZE is the size of each item, in bytes.
281
282 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
283 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
284 infinity.
285
286 If PA is null, then allocate a new array instead of reallocating
287 the old one.
288
289 If memory exhaustion occurs, set *NITEMS to zero if PA is null, and
290 signal an error (i.e., do not return).
291
292 Thus, to grow an array A without saving its old contents, do
293 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
294 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
295 and signals an error, and later this code is reexecuted and
296 attempts to free A. */
297
298 void *
299 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
300 ptrdiff_t nitems_max, ptrdiff_t item_size)
301 {
302 /* The approximate size to use for initial small allocation
303 requests. This is the largest "small" request for the GNU C
304 library malloc. */
305 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
306
307 /* If the array is tiny, grow it to about (but no greater than)
308 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
309 ptrdiff_t n = *nitems;
310 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
311 ptrdiff_t half_again = n >> 1;
312 ptrdiff_t incr_estimate = max (tiny_max, half_again);
313
314 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
315 NITEMS_MAX, and what the C language can represent safely. */
316 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
317 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
318 ? nitems_max : C_language_max);
319 ptrdiff_t nitems_incr_max = n_max - n;
320 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
321
322 eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
323 if (! pa)
324 *nitems = 0;
325 if (nitems_incr_max < incr)
326 memory_full (SIZE_MAX);
327 n += incr;
328 pa = xrealloc (pa, n * item_size);
329 *nitems = n;
330 return pa;
331 }
332
333
334 /* Like strdup, but uses xmalloc. */
335
336 char *
337 xstrdup (const char *s)
338 {
339 ptrdiff_t size;
340 eassert (s);
341 size = strlen (s) + 1;
342 return memcpy (xmalloc (size), s, size);
343 }
344
345 /* Like above, but duplicates Lisp string to C string. */
346
347 char *
348 xlispstrdup (Lisp_Object string)
349 {
350 ptrdiff_t size = SBYTES (string) + 1;
351 return memcpy (xmalloc (size), SSDATA (string), size);
352 }
353
354 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
355 pointed to. If STRING is null, assign it without copying anything.
356 Allocate before freeing, to avoid a dangling pointer if allocation
357 fails. */
358
359 void
360 dupstring (char **ptr, char const *string)
361 {
362 char *old = *ptr;
363 *ptr = string ? xstrdup (string) : 0;
364 xfree (old);
365 }
366
367
368 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
369 argument is a const pointer. */
370
371 void
372 xputenv (char const *string)
373 {
374 if (putenv ((char *) string) != 0)
375 memory_full (0);
376 }
377
378 /* Return a newly allocated memory block of SIZE bytes, remembering
379 to free it when unwinding. */
380 void *
381 record_xmalloc (size_t size)
382 {
383 void *p = xmalloc (size);
384 record_unwind_protect_ptr (xfree, p);
385 return p;
386 }
387 \f
388 /***********************************************************************
389 Interval Allocation
390 ***********************************************************************/
391
392 /* Return a new interval. */
393
394 INTERVAL
395 make_interval (void)
396 {
397 INTERVAL val = xmalloc (sizeof (struct interval));
398 RESET_INTERVAL (val);
399 return val;
400 }
401
402 /***********************************************************************
403 String Allocation
404 ***********************************************************************/
405
406 /* Initialize string allocation. Called from init_alloc_once. */
407
408 static void
409 init_strings (void)
410 {
411 empty_unibyte_string = make_empty_string (0);
412 empty_multibyte_string = make_empty_string (1);
413 }
414
415 /* Return a new Lisp_String. */
416
417 static struct Lisp_String *
418 allocate_string (void)
419 {
420 return xmalloc (sizeof (struct Lisp_String));
421 }
422
423
424 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
425 plus a NUL byte at the end. Allocate an sdata structure for S, and
426 set S->data to its `u.data' member. Store a NUL byte at the end of
427 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
428 S->data if it was initially non-null. */
429
430 void
431 allocate_string_data (struct Lisp_String *s,
432 EMACS_INT nchars, EMACS_INT nbytes)
433 {
434 unsigned char *data;
435
436 if (STRING_BYTES_BOUND < nbytes)
437 string_overflow ();
438
439 data = GC_MALLOC_ATOMIC (nbytes + 1);
440 s->data = data;
441 s->size = nchars;
442 s->size_byte = nbytes;
443 s->data[nbytes] = '\0';
444 }
445
446 void
447 string_overflow (void)
448 {
449 error ("Maximum string size exceeded");
450 }
451
452 static Lisp_Object
453 make_empty_string (int multibyte)
454 {
455 Lisp_Object string;
456 struct Lisp_String *s;
457
458 s = allocate_string ();
459 allocate_string_data (s, 0, 0);
460 XSETSTRING (string, s);
461 if (! multibyte)
462 STRING_SET_UNIBYTE (string);
463
464 return string;
465 }
466
467 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
468 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
469 LENGTH must be an integer.
470 INIT must be an integer that represents a character. */)
471 (Lisp_Object length, Lisp_Object init)
472 {
473 register Lisp_Object val;
474 int c;
475 EMACS_INT nbytes;
476
477 CHECK_NATNUM (length);
478 CHECK_CHARACTER (init);
479
480 c = XFASTINT (init);
481 if (ASCII_CHAR_P (c))
482 {
483 nbytes = XINT (length);
484 val = make_uninit_string (nbytes);
485 memset (SDATA (val), c, nbytes);
486 SDATA (val)[nbytes] = 0;
487 }
488 else
489 {
490 unsigned char str[MAX_MULTIBYTE_LENGTH];
491 ptrdiff_t len = CHAR_STRING (c, str);
492 EMACS_INT string_len = XINT (length);
493 unsigned char *p, *beg, *end;
494
495 if (string_len > STRING_BYTES_BOUND / len)
496 string_overflow ();
497 nbytes = len * string_len;
498 val = make_uninit_multibyte_string (string_len, nbytes);
499 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
500 {
501 /* First time we just copy `str' to the data of `val'. */
502 if (p == beg)
503 memcpy (p, str, len);
504 else
505 {
506 /* Next time we copy largest possible chunk from
507 initialized to uninitialized part of `val'. */
508 len = min (p - beg, end - p);
509 memcpy (p, beg, len);
510 }
511 }
512 *p = 0;
513 }
514
515 return val;
516 }
517
518 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
519 Return A. */
520
521 Lisp_Object
522 bool_vector_fill (Lisp_Object a, Lisp_Object init)
523 {
524 EMACS_INT nbits = bool_vector_size (a);
525 if (0 < nbits)
526 {
527 unsigned char *data = bool_vector_uchar_data (a);
528 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
529 ptrdiff_t nbytes = bool_vector_bytes (nbits);
530 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
531 memset (data, pattern, nbytes - 1);
532 data[nbytes - 1] = pattern & last_mask;
533 }
534 return a;
535 }
536
537 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
538
539 Lisp_Object
540 make_uninit_bool_vector (EMACS_INT nbits)
541 {
542 Lisp_Object val;
543 EMACS_INT words = bool_vector_words (nbits);
544 EMACS_INT word_bytes = words * sizeof (bits_word);
545 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
546 + word_size - 1)
547 / word_size);
548 struct Lisp_Bool_Vector *p
549 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
550 XSETVECTOR (val, p);
551 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
552 p->size = nbits;
553
554 /* Clear padding at the end. */
555 if (words)
556 p->data[words - 1] = 0;
557
558 return val;
559 }
560
561 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
562 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
563 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
564 (Lisp_Object length, Lisp_Object init)
565 {
566 Lisp_Object val;
567
568 CHECK_NATNUM (length);
569 val = make_uninit_bool_vector (XFASTINT (length));
570 return bool_vector_fill (val, init);
571 }
572
573 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
574 doc: /* Return a new bool-vector with specified arguments as elements.
575 Any number of arguments, even zero arguments, are allowed.
576 usage: (bool-vector &rest OBJECTS) */)
577 (ptrdiff_t nargs, Lisp_Object *args)
578 {
579 ptrdiff_t i;
580 Lisp_Object vector;
581
582 vector = make_uninit_bool_vector (nargs);
583 for (i = 0; i < nargs; i++)
584 bool_vector_set (vector, i, !NILP (args[i]));
585
586 return vector;
587 }
588
589 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
590 of characters from the contents. This string may be unibyte or
591 multibyte, depending on the contents. */
592
593 Lisp_Object
594 make_string (const char *contents, ptrdiff_t nbytes)
595 {
596 register Lisp_Object val;
597 ptrdiff_t nchars, multibyte_nbytes;
598
599 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
600 &nchars, &multibyte_nbytes);
601 if (nbytes == nchars || nbytes != multibyte_nbytes)
602 /* CONTENTS contains no multibyte sequences or contains an invalid
603 multibyte sequence. We must make unibyte string. */
604 val = make_unibyte_string (contents, nbytes);
605 else
606 val = make_multibyte_string (contents, nchars, nbytes);
607 return val;
608 }
609
610
611 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
612
613 Lisp_Object
614 make_unibyte_string (const char *contents, ptrdiff_t length)
615 {
616 register Lisp_Object val;
617 val = make_uninit_string (length);
618 memcpy (SDATA (val), contents, length);
619 return val;
620 }
621
622
623 /* Make a multibyte string from NCHARS characters occupying NBYTES
624 bytes at CONTENTS. */
625
626 Lisp_Object
627 make_multibyte_string (const char *contents,
628 ptrdiff_t nchars, ptrdiff_t nbytes)
629 {
630 register Lisp_Object val;
631 val = make_uninit_multibyte_string (nchars, nbytes);
632 memcpy (SDATA (val), contents, nbytes);
633 return val;
634 }
635
636
637 /* Make a string from NCHARS characters occupying NBYTES bytes at
638 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
639
640 Lisp_Object
641 make_string_from_bytes (const char *contents,
642 ptrdiff_t nchars, ptrdiff_t nbytes)
643 {
644 register Lisp_Object val;
645 val = make_uninit_multibyte_string (nchars, nbytes);
646 memcpy (SDATA (val), contents, nbytes);
647 if (SBYTES (val) == SCHARS (val))
648 STRING_SET_UNIBYTE (val);
649 return val;
650 }
651
652
653 /* Make a string from NCHARS characters occupying NBYTES bytes at
654 CONTENTS. The argument MULTIBYTE controls whether to label the
655 string as multibyte. If NCHARS is negative, it counts the number of
656 characters by itself. */
657
658 Lisp_Object
659 make_specified_string (const char *contents,
660 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
661 {
662 Lisp_Object val;
663
664 if (nchars < 0)
665 {
666 if (multibyte)
667 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
668 nbytes);
669 else
670 nchars = nbytes;
671 }
672 val = make_uninit_multibyte_string (nchars, nbytes);
673 memcpy (SDATA (val), contents, nbytes);
674 if (!multibyte)
675 STRING_SET_UNIBYTE (val);
676 return val;
677 }
678
679
680 /* Return an unibyte Lisp_String set up to hold LENGTH characters
681 occupying LENGTH bytes. */
682
683 Lisp_Object
684 make_uninit_string (EMACS_INT length)
685 {
686 Lisp_Object val;
687
688 if (!length)
689 return empty_unibyte_string;
690 val = make_uninit_multibyte_string (length, length);
691 STRING_SET_UNIBYTE (val);
692 return val;
693 }
694
695
696 /* Return a multibyte Lisp_String set up to hold NCHARS characters
697 which occupy NBYTES bytes. */
698
699 Lisp_Object
700 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
701 {
702 Lisp_Object string;
703 struct Lisp_String *s;
704
705 if (nchars < 0)
706 emacs_abort ();
707 if (!nbytes)
708 return empty_multibyte_string;
709
710 s = allocate_string ();
711 s->intervals = NULL;
712 allocate_string_data (s, nchars, nbytes);
713 XSETSTRING (string, s);
714 return string;
715 }
716
717 /* Print arguments to BUF according to a FORMAT, then return
718 a Lisp_String initialized with the data from BUF. */
719
720 Lisp_Object
721 make_formatted_string (char *buf, const char *format, ...)
722 {
723 va_list ap;
724 int length;
725
726 va_start (ap, format);
727 length = vsprintf (buf, format, ap);
728 va_end (ap);
729 return make_string (buf, length);
730 }
731
732 \f
733 /***********************************************************************
734 Float Allocation
735 ***********************************************************************/
736
737 /* Return a new float object with value FLOAT_VALUE. */
738
739 Lisp_Object
740 make_float (double float_value)
741 {
742 register Lisp_Object val;
743 XSETFLOAT (val, xmalloc (sizeof (struct Lisp_Float)));
744 XFLOAT_INIT (val, float_value);
745 return val;
746 }
747
748
749 \f
750 /***********************************************************************
751 Cons Allocation
752 ***********************************************************************/
753
754 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
755 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
756 (Lisp_Object car, Lisp_Object cdr)
757 {
758 register Lisp_Object val;
759
760 XSETCONS (val, xmalloc (sizeof (struct Lisp_Cons)));
761 XSETCAR (val, car);
762 XSETCDR (val, cdr);
763 return val;
764 }
765
766 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
767
768 Lisp_Object
769 list1 (Lisp_Object arg1)
770 {
771 return Fcons (arg1, Qnil);
772 }
773
774 Lisp_Object
775 list2 (Lisp_Object arg1, Lisp_Object arg2)
776 {
777 return Fcons (arg1, Fcons (arg2, Qnil));
778 }
779
780
781 Lisp_Object
782 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
783 {
784 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
785 }
786
787
788 Lisp_Object
789 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
790 {
791 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
792 }
793
794
795 Lisp_Object
796 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
797 {
798 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
799 Fcons (arg5, Qnil)))));
800 }
801
802 /* Make a list of COUNT Lisp_Objects, where ARG is the
803 first one. Allocate conses from pure space if TYPE
804 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
805
806 Lisp_Object
807 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
808 {
809 va_list ap;
810 ptrdiff_t i;
811 Lisp_Object val, *objp;
812
813 /* Change to SAFE_ALLOCA if you hit this eassert. */
814 eassert (count <= MAX_ALLOCA / word_size);
815
816 objp = alloca (count * word_size);
817 objp[0] = arg;
818 va_start (ap, arg);
819 for (i = 1; i < count; i++)
820 objp[i] = va_arg (ap, Lisp_Object);
821 va_end (ap);
822
823 for (val = Qnil, i = count - 1; i >= 0; i--)
824 {
825 if (type == CONSTYPE_PURE)
826 val = pure_cons (objp[i], val);
827 else if (type == CONSTYPE_HEAP)
828 val = Fcons (objp[i], val);
829 else
830 emacs_abort ();
831 }
832 return val;
833 }
834
835 DEFUN ("list", Flist, Slist, 0, MANY, 0,
836 doc: /* Return a newly created list with specified arguments as elements.
837 Any number of arguments, even zero arguments, are allowed.
838 usage: (list &rest OBJECTS) */)
839 (ptrdiff_t nargs, Lisp_Object *args)
840 {
841 register Lisp_Object val;
842 val = Qnil;
843
844 while (nargs > 0)
845 {
846 nargs--;
847 val = Fcons (args[nargs], val);
848 }
849 return val;
850 }
851
852
853 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
854 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
855 (register Lisp_Object length, Lisp_Object init)
856 {
857 register Lisp_Object val;
858 register EMACS_INT size;
859
860 CHECK_NATNUM (length);
861 size = XFASTINT (length);
862
863 val = Qnil;
864 while (size > 0)
865 {
866 val = Fcons (init, val);
867 --size;
868
869 if (size > 0)
870 {
871 val = Fcons (init, val);
872 --size;
873
874 if (size > 0)
875 {
876 val = Fcons (init, val);
877 --size;
878
879 if (size > 0)
880 {
881 val = Fcons (init, val);
882 --size;
883
884 if (size > 0)
885 {
886 val = Fcons (init, val);
887 --size;
888 }
889 }
890 }
891 }
892
893 QUIT;
894 }
895
896 return val;
897 }
898
899
900 \f
901 /***********************************************************************
902 Vector Allocation
903 ***********************************************************************/
904
905 /* The only vector with 0 slots, allocated from pure space. */
906
907 Lisp_Object zero_vector;
908
909 /* Called once to initialize vector allocation. */
910
911 static void
912 init_vectors (void)
913 {
914 XSETVECTOR (zero_vector, xmalloc (header_size));
915 XVECTOR (zero_vector)->header.size = 0;
916 }
917
918 /* Value is a pointer to a newly allocated Lisp_Vector structure
919 with room for LEN Lisp_Objects. */
920
921 static struct Lisp_Vector *
922 allocate_vectorlike (ptrdiff_t len)
923 {
924 if (len == 0)
925 return XVECTOR (zero_vector);
926 else
927 return xmalloc (header_size + len * word_size);
928 }
929
930
931 /* Allocate a vector with LEN slots. */
932
933 struct Lisp_Vector *
934 allocate_vector (EMACS_INT len)
935 {
936 struct Lisp_Vector *v;
937 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
938
939 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
940 memory_full (SIZE_MAX);
941 v = allocate_vectorlike (len);
942 v->header.size = len;
943 return v;
944 }
945
946
947 /* Allocate other vector-like structures. */
948
949 struct Lisp_Vector *
950 allocate_pseudovector (int memlen, int lisplen, enum pvec_type tag)
951 {
952 struct Lisp_Vector *v = allocate_vectorlike (memlen);
953 int i;
954
955 /* Catch bogus values. */
956 eassert (tag <= PVEC_FONT);
957 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
958 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
959
960 /* Only the first lisplen slots will be traced normally by the GC. */
961 for (i = 0; i < lisplen; ++i)
962 v->contents[i] = Qnil;
963
964 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
965 return v;
966 }
967
968 struct buffer *
969 allocate_buffer (void)
970 {
971 struct buffer *b = xmalloc (sizeof *b);
972
973 BUFFER_PVEC_INIT (b);
974 /* Put B on the chain of all buffers including killed ones. */
975 b->next = all_buffers;
976 all_buffers = b;
977 /* Note that the rest fields of B are not initialized. */
978 return b;
979 }
980
981 struct Lisp_Hash_Table *
982 allocate_hash_table (void)
983 {
984 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
985 }
986
987 struct window *
988 allocate_window (void)
989 {
990 struct window *w;
991
992 w = ALLOCATE_PSEUDOVECTOR (struct window, current_matrix, PVEC_WINDOW);
993 /* Users assumes that non-Lisp data is zeroed. */
994 memset (&w->current_matrix, 0,
995 sizeof (*w) - offsetof (struct window, current_matrix));
996 return w;
997 }
998
999 struct terminal *
1000 allocate_terminal (void)
1001 {
1002 struct terminal *t;
1003
1004 t = ALLOCATE_PSEUDOVECTOR (struct terminal, next_terminal, PVEC_TERMINAL);
1005 /* Users assumes that non-Lisp data is zeroed. */
1006 memset (&t->next_terminal, 0,
1007 sizeof (*t) - offsetof (struct terminal, next_terminal));
1008 return t;
1009 }
1010
1011 struct frame *
1012 allocate_frame (void)
1013 {
1014 struct frame *f;
1015
1016 f = ALLOCATE_PSEUDOVECTOR (struct frame, face_cache, PVEC_FRAME);
1017 /* Users assumes that non-Lisp data is zeroed. */
1018 memset (&f->face_cache, 0,
1019 sizeof (*f) - offsetof (struct frame, face_cache));
1020 return f;
1021 }
1022
1023 struct Lisp_Process *
1024 allocate_process (void)
1025 {
1026 struct Lisp_Process *p;
1027
1028 p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
1029 /* Users assumes that non-Lisp data is zeroed. */
1030 memset (&p->pid, 0,
1031 sizeof (*p) - offsetof (struct Lisp_Process, pid));
1032 return p;
1033 }
1034
1035 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
1036 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
1037 See also the function `vector'. */)
1038 (register Lisp_Object length, Lisp_Object init)
1039 {
1040 Lisp_Object vector;
1041 register ptrdiff_t sizei;
1042 register ptrdiff_t i;
1043 register struct Lisp_Vector *p;
1044
1045 CHECK_NATNUM (length);
1046
1047 p = allocate_vector (XFASTINT (length));
1048 sizei = XFASTINT (length);
1049 for (i = 0; i < sizei; i++)
1050 p->contents[i] = init;
1051
1052 XSETVECTOR (vector, p);
1053 return vector;
1054 }
1055
1056
1057 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
1058 doc: /* Return a newly created vector with specified arguments as elements.
1059 Any number of arguments, even zero arguments, are allowed.
1060 usage: (vector &rest OBJECTS) */)
1061 (ptrdiff_t nargs, Lisp_Object *args)
1062 {
1063 ptrdiff_t i;
1064 register Lisp_Object val = make_uninit_vector (nargs);
1065 register struct Lisp_Vector *p = XVECTOR (val);
1066
1067 for (i = 0; i < nargs; i++)
1068 p->contents[i] = args[i];
1069 return val;
1070 }
1071
1072 void
1073 make_byte_code (struct Lisp_Vector *v)
1074 {
1075 /* Don't allow the global zero_vector to become a byte code object. */
1076 eassert (0 < v->header.size);
1077
1078 if (v->header.size > 1 && STRINGP (v->contents[1])
1079 && STRING_MULTIBYTE (v->contents[1]))
1080 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
1081 earlier because they produced a raw 8-bit string for byte-code
1082 and now such a byte-code string is loaded as multibyte while
1083 raw 8-bit characters converted to multibyte form. Thus, now we
1084 must convert them back to the original unibyte form. */
1085 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
1086 XSETPVECTYPE (v, PVEC_COMPILED);
1087 }
1088
1089 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
1090 doc: /* Create a byte-code object with specified arguments as elements.
1091 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
1092 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
1093 and (optional) INTERACTIVE-SPEC.
1094 The first four arguments are required; at most six have any
1095 significance.
1096 The ARGLIST can be either like the one of `lambda', in which case the arguments
1097 will be dynamically bound before executing the byte code, or it can be an
1098 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
1099 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
1100 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
1101 argument to catch the left-over arguments. If such an integer is used, the
1102 arguments will not be dynamically bound but will be instead pushed on the
1103 stack before executing the byte-code.
1104 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
1105 (ptrdiff_t nargs, Lisp_Object *args)
1106 {
1107 ptrdiff_t i;
1108 register Lisp_Object val = make_uninit_vector (nargs);
1109 register struct Lisp_Vector *p = XVECTOR (val);
1110
1111 /* We used to purecopy everything here, if purify-flag was set. This worked
1112 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
1113 dangerous, since make-byte-code is used during execution to build
1114 closures, so any closure built during the preload phase would end up
1115 copied into pure space, including its free variables, which is sometimes
1116 just wasteful and other times plainly wrong (e.g. those free vars may want
1117 to be setcar'd). */
1118
1119 for (i = 0; i < nargs; i++)
1120 p->contents[i] = args[i];
1121 make_byte_code (p);
1122 XSETCOMPILED (val, p);
1123 return val;
1124 }
1125
1126
1127 \f
1128 /***********************************************************************
1129 Symbol Allocation
1130 ***********************************************************************/
1131
1132 static void
1133 set_symbol_name (Lisp_Object sym, Lisp_Object name)
1134 {
1135 XSYMBOL (sym)->name = name;
1136 }
1137
1138 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
1139 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
1140 Its value is void, and its function definition and property list are nil. */)
1141 (Lisp_Object name)
1142 {
1143 register Lisp_Object val;
1144 register struct Lisp_Symbol *p;
1145
1146 CHECK_STRING (name);
1147
1148 XSETSYMBOL (val, xmalloc (sizeof (struct Lisp_Symbol)));
1149 p = XSYMBOL (val);
1150 set_symbol_name (val, name);
1151 set_symbol_plist (val, Qnil);
1152 p->redirect = SYMBOL_PLAINVAL;
1153 SET_SYMBOL_VAL (p, Qunbound);
1154 set_symbol_function (val, Qnil);
1155 set_symbol_next (val, NULL);
1156 p->gcmarkbit = false;
1157 p->interned = SYMBOL_UNINTERNED;
1158 p->constant = 0;
1159 p->declared_special = false;
1160 p->pinned = false;
1161 return val;
1162 }
1163
1164
1165 \f
1166 /***********************************************************************
1167 Marker (Misc) Allocation
1168 ***********************************************************************/
1169
1170 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
1171
1172 static Lisp_Object
1173 allocate_misc (enum Lisp_Misc_Type type)
1174 {
1175 Lisp_Object val;
1176
1177 XSETMISC (val, xmalloc (sizeof (union Lisp_Misc)));
1178 XMISCANY (val)->type = type;
1179 return val;
1180 }
1181
1182 /* Free a Lisp_Misc object. */
1183
1184 void
1185 free_misc (Lisp_Object misc)
1186 {
1187 return;
1188 }
1189
1190 /* Verify properties of Lisp_Save_Value's representation
1191 that are assumed here and elsewhere. */
1192
1193 verify (SAVE_UNUSED == 0);
1194 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
1195 >> SAVE_SLOT_BITS)
1196 == 0);
1197
1198 /* Return Lisp_Save_Value objects for the various combinations
1199 that callers need. */
1200
1201 Lisp_Object
1202 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
1203 {
1204 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1205 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1206 p->save_type = SAVE_TYPE_INT_INT_INT;
1207 p->data[0].integer = a;
1208 p->data[1].integer = b;
1209 p->data[2].integer = c;
1210 return val;
1211 }
1212
1213 Lisp_Object
1214 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
1215 Lisp_Object d)
1216 {
1217 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1218 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1219 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
1220 p->data[0].object = a;
1221 p->data[1].object = b;
1222 p->data[2].object = c;
1223 p->data[3].object = d;
1224 return val;
1225 }
1226
1227 Lisp_Object
1228 make_save_ptr (void *a)
1229 {
1230 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1231 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1232 p->save_type = SAVE_POINTER;
1233 p->data[0].pointer = a;
1234 return val;
1235 }
1236
1237 Lisp_Object
1238 make_save_ptr_int (void *a, ptrdiff_t b)
1239 {
1240 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1241 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1242 p->save_type = SAVE_TYPE_PTR_INT;
1243 p->data[0].pointer = a;
1244 p->data[1].integer = b;
1245 return val;
1246 }
1247
1248 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
1249 Lisp_Object
1250 make_save_ptr_ptr (void *a, void *b)
1251 {
1252 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1253 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1254 p->save_type = SAVE_TYPE_PTR_PTR;
1255 p->data[0].pointer = a;
1256 p->data[1].pointer = b;
1257 return val;
1258 }
1259 #endif
1260
1261 Lisp_Object
1262 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
1263 {
1264 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1265 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1266 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
1267 p->data[0].funcpointer = a;
1268 p->data[1].pointer = b;
1269 p->data[2].object = c;
1270 return val;
1271 }
1272
1273 /* Return a Lisp_Save_Value object that represents an array A
1274 of N Lisp objects. */
1275
1276 Lisp_Object
1277 make_save_memory (Lisp_Object *a, ptrdiff_t n)
1278 {
1279 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
1280 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
1281 p->save_type = SAVE_TYPE_MEMORY;
1282 p->data[0].pointer = a;
1283 p->data[1].integer = n;
1284 return val;
1285 }
1286
1287 /* Free a Lisp_Save_Value object. Do not use this function
1288 if SAVE contains pointer other than returned by xmalloc. */
1289
1290 void
1291 free_save_value (Lisp_Object save)
1292 {
1293 xfree (XSAVE_POINTER (save, 0));
1294 free_misc (save);
1295 }
1296
1297 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
1298
1299 Lisp_Object
1300 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
1301 {
1302 register Lisp_Object overlay;
1303
1304 overlay = allocate_misc (Lisp_Misc_Overlay);
1305 OVERLAY_START (overlay) = start;
1306 OVERLAY_END (overlay) = end;
1307 set_overlay_plist (overlay, plist);
1308 XOVERLAY (overlay)->next = NULL;
1309 return overlay;
1310 }
1311
1312 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
1313 doc: /* Return a newly allocated marker which does not point at any place. */)
1314 (void)
1315 {
1316 register Lisp_Object val;
1317 register struct Lisp_Marker *p;
1318
1319 val = allocate_misc (Lisp_Misc_Marker);
1320 p = XMARKER (val);
1321 p->buffer = 0;
1322 p->bytepos = 0;
1323 p->charpos = 0;
1324 p->next = NULL;
1325 p->insertion_type = 0;
1326 p->need_adjustment = 0;
1327 return val;
1328 }
1329
1330 /* Return a newly allocated marker which points into BUF
1331 at character position CHARPOS and byte position BYTEPOS. */
1332
1333 Lisp_Object
1334 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
1335 {
1336 Lisp_Object obj;
1337 struct Lisp_Marker *m;
1338
1339 /* No dead buffers here. */
1340 eassert (BUFFER_LIVE_P (buf));
1341
1342 /* Every character is at least one byte. */
1343 eassert (charpos <= bytepos);
1344
1345 obj = allocate_misc (Lisp_Misc_Marker);
1346 m = XMARKER (obj);
1347 m->buffer = buf;
1348 m->charpos = charpos;
1349 m->bytepos = bytepos;
1350 m->insertion_type = 0;
1351 m->need_adjustment = 0;
1352 m->next = BUF_MARKERS (buf);
1353 BUF_MARKERS (buf) = m;
1354 return obj;
1355 }
1356 \f
1357 /* Return a newly created vector or string with specified arguments as
1358 elements. If all the arguments are characters that can fit
1359 in a string of events, make a string; otherwise, make a vector.
1360
1361 Any number of arguments, even zero arguments, are allowed. */
1362
1363 Lisp_Object
1364 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
1365 {
1366 ptrdiff_t i;
1367
1368 for (i = 0; i < nargs; i++)
1369 /* The things that fit in a string
1370 are characters that are in 0...127,
1371 after discarding the meta bit and all the bits above it. */
1372 if (!INTEGERP (args[i])
1373 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
1374 return Fvector (nargs, args);
1375
1376 /* Since the loop exited, we know that all the things in it are
1377 characters, so we can make a string. */
1378 {
1379 Lisp_Object result;
1380
1381 result = Fmake_string (make_number (nargs), make_number (0));
1382 for (i = 0; i < nargs; i++)
1383 {
1384 SSET (result, i, XINT (args[i]));
1385 /* Move the meta bit to the right place for a string char. */
1386 if (XINT (args[i]) & CHAR_META)
1387 SSET (result, i, SREF (result, i) | 0x80);
1388 }
1389
1390 return result;
1391 }
1392 }
1393
1394
1395 \f
1396 /************************************************************************
1397 Memory Full Handling
1398 ************************************************************************/
1399
1400
1401 /* Called if xmalloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
1402 there may have been size_t overflow so that xmalloc was never
1403 called, or perhaps xmalloc was invoked successfully but the
1404 resulting pointer had problems fitting into a tagged EMACS_INT. In
1405 either case this counts as memory being full even though xmalloc
1406 did not fail. */
1407
1408 void
1409 memory_full (size_t nbytes)
1410 {
1411 /* Do not go into hysterics merely because a large request failed. */
1412 bool enough_free_memory = 0;
1413 if (SPARE_MEMORY < nbytes)
1414 {
1415 void *p = xmalloc_unsafe (SPARE_MEMORY);
1416 if (p)
1417 {
1418 xfree (p);
1419 enough_free_memory = 1;
1420 }
1421 }
1422
1423 if (! enough_free_memory)
1424 {
1425 Vmemory_full = Qt;
1426
1427 /* The first time we get here, free the spare memory. */
1428 if (spare_memory)
1429 {
1430 xfree (spare_memory);
1431 spare_memory = NULL;
1432 }
1433 }
1434
1435 /* This used to call error, but if we've run out of memory, we could
1436 get infinite recursion trying to build the string. */
1437 xsignal (Qnil, Vmemory_signal_data);
1438 }
1439
1440 /* If we released our reserve (due to running out of memory),
1441 and we have a fair amount free once again,
1442 try to set aside another reserve in case we run out once more.
1443
1444 This is called when a relocatable block is freed in ralloc.c,
1445 and also directly from this file, in case we're not using ralloc.c. */
1446
1447 void
1448 refill_memory_reserve (void)
1449 {
1450 if (spare_memory == NULL)
1451 spare_memory = GC_MALLOC (SPARE_MEMORY);
1452
1453 if (spare_memory)
1454 Vmemory_full = Qnil;
1455 }
1456 \f
1457 /* Determine whether it is safe to access memory at address P. */
1458 static int
1459 valid_pointer_p (void *p)
1460 {
1461 #ifdef WINDOWSNT
1462 return w32_valid_pointer_p (p, 16);
1463 #else
1464 int fd[2];
1465
1466 /* Obviously, we cannot just access it (we would SEGV trying), so we
1467 trick the o/s to tell us whether p is a valid pointer.
1468 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
1469 not validate p in that case. */
1470
1471 if (emacs_pipe (fd) == 0)
1472 {
1473 bool valid = emacs_write (fd[1], p, 16) == 16;
1474 emacs_close (fd[1]);
1475 emacs_close (fd[0]);
1476 return valid;
1477 }
1478
1479 return -1;
1480 #endif
1481 }
1482
1483 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
1484 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
1485 cannot validate OBJ. This function can be quite slow, so its primary
1486 use is the manual debugging. The only exception is print_object, where
1487 we use it to check whether the memory referenced by the pointer of
1488 Lisp_Save_Value object contains valid objects. */
1489
1490 int
1491 valid_lisp_object_p (Lisp_Object obj)
1492 {
1493 void *p;
1494
1495 if (INTEGERP (obj))
1496 return 1;
1497
1498 p = (void *) XPNTR (obj);
1499
1500 if (p == &buffer_defaults || p == &buffer_local_symbols)
1501 return 2;
1502
1503 return valid_pointer_p (p);
1504 }
1505
1506 /* If GC_MARK_STACK, return 1 if STR is a relocatable data of Lisp_String
1507 (i.e. there is a non-pure Lisp_Object X so that SDATA (X) == STR) and 0
1508 if not. Otherwise we can't rely on valid_lisp_object_p and return -1.
1509 This function is slow and should be used for debugging purposes. */
1510
1511 int
1512 relocatable_string_data_p (const char *str)
1513 {
1514 return -1;
1515 }
1516
1517 /***********************************************************************
1518 Pure Storage Compatibility Functions
1519 ***********************************************************************/
1520
1521 void
1522 check_pure_size (void)
1523 {
1524 return;
1525 }
1526
1527 Lisp_Object
1528 make_pure_string (const char *data,
1529 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
1530 {
1531 return make_specified_string (data, nchars, nbytes, multibyte);
1532 }
1533
1534 Lisp_Object
1535 make_pure_c_string (const char *data, ptrdiff_t nchars)
1536 {
1537 return build_string (data);
1538 }
1539
1540 Lisp_Object
1541 pure_cons (Lisp_Object car, Lisp_Object cdr)
1542 {
1543 return Fcons (car, cdr);
1544 }
1545
1546 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
1547 doc: /* Return OBJ. */)
1548 (register Lisp_Object obj)
1549 {
1550 return obj;
1551 }
1552 \f
1553 /***********************************************************************
1554 Protection from GC
1555 ***********************************************************************/
1556
1557 void
1558 staticpro (Lisp_Object *varaddress)
1559 {
1560 return;
1561 }
1562 \f
1563 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
1564 doc: /* Reclaim storage for Lisp objects no longer needed.
1565 Garbage collection happens automatically if you cons more than
1566 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
1567 `garbage-collect' normally returns a list with info on amount of space in use,
1568 where each entry has the form (NAME SIZE USED FREE), where:
1569 - NAME is a symbol describing the kind of objects this entry represents,
1570 - SIZE is the number of bytes used by each one,
1571 - USED is the number of those objects that were found live in the heap,
1572 - FREE is the number of those objects that are not live but that Emacs
1573 keeps around for future allocations (maybe because it does not know how
1574 to return them to the OS).
1575 However, if there was overflow in pure space, `garbage-collect'
1576 returns nil, because real GC can't be done.
1577 See Info node `(elisp)Garbage Collection'. */)
1578 (void)
1579 {
1580 GC_gcollect ();
1581 return Qt;
1582 }
1583 \f
1584 #ifdef ENABLE_CHECKING
1585
1586 bool suppress_checking;
1587
1588 void
1589 die (const char *msg, const char *file, int line)
1590 {
1591 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
1592 file, line, msg);
1593 terminate_due_to_signal (SIGABRT, INT_MAX);
1594 }
1595 #endif
1596 \f
1597 /* Initialization. */
1598
1599 void
1600 init_alloc_once (void)
1601 {
1602 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
1603
1604 init_strings ();
1605 init_vectors ();
1606
1607 refill_memory_reserve ();
1608 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
1609 }
1610
1611 void
1612 init_alloc (void)
1613 {
1614 gcprolist = 0;
1615 Vgc_elapsed = make_float (0.0);
1616 gcs_done = 0;
1617
1618 #if USE_VALGRIND
1619 valgrind_p = RUNNING_ON_VALGRIND != 0;
1620 #endif
1621 }
1622
1623 void
1624 syms_of_alloc (void)
1625 {
1626 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
1627 doc: /* Number of bytes of consing between garbage collections.
1628 Garbage collection can happen automatically once this many bytes have been
1629 allocated since the last garbage collection. All data types count.
1630
1631 Garbage collection happens automatically only when `eval' is called.
1632
1633 By binding this temporarily to a large number, you can effectively
1634 prevent garbage collection during a part of the program.
1635 See also `gc-cons-percentage'. */);
1636
1637 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
1638 doc: /* Portion of the heap used for allocation.
1639 Garbage collection can happen automatically once this portion of the heap
1640 has been allocated since the last garbage collection.
1641 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
1642 Vgc_cons_percentage = make_float (0.1);
1643
1644 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
1645 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
1646
1647 DEFVAR_LISP ("purify-flag", Vpurify_flag,
1648 doc: /* Non-nil means loading Lisp code in order to dump an executable.
1649 This means that certain objects should be allocated in shared (pure) space.
1650 It can also be set to a hash-table, in which case this table is used to
1651 do hash-consing of the objects allocated to pure space. */);
1652
1653 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
1654 doc: /* Non-nil means display messages at start and end of garbage collection. */);
1655 garbage_collection_messages = 0;
1656
1657 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
1658 doc: /* Hook run after garbage collection has finished. */);
1659 Vpost_gc_hook = Qnil;
1660 DEFSYM (Qpost_gc_hook, "post-gc-hook");
1661
1662 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
1663 doc: /* Precomputed `signal' argument for memory-full error. */);
1664 /* We build this in advance because if we wait until we need it, we might
1665 not be able to allocate the memory to hold it. */
1666 Vmemory_signal_data
1667 = listn (CONSTYPE_PURE, 2, Qerror,
1668 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
1669
1670 DEFVAR_LISP ("memory-full", Vmemory_full,
1671 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
1672 Vmemory_full = Qnil;
1673
1674 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
1675 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
1676
1677 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
1678 doc: /* Accumulated time elapsed in garbage collections.
1679 The time is in seconds as a floating point value. */);
1680 DEFVAR_INT ("gcs-done", gcs_done,
1681 doc: /* Accumulated number of garbage collections done. */);
1682
1683 defsubr (&Scons);
1684 defsubr (&Slist);
1685 defsubr (&Svector);
1686 defsubr (&Sbool_vector);
1687 defsubr (&Smake_byte_code);
1688 defsubr (&Smake_list);
1689 defsubr (&Smake_vector);
1690 defsubr (&Smake_string);
1691 defsubr (&Smake_bool_vector);
1692 defsubr (&Smake_symbol);
1693 defsubr (&Smake_marker);
1694 defsubr (&Spurecopy);
1695 defsubr (&Sgarbage_collect);
1696 }
1697
1698 /* When compiled with GCC, GDB might say "No enum type named
1699 pvec_type" if we don't have at least one symbol with that type, and
1700 then xbacktrace could fail. Similarly for the other enums and
1701 their values. Some non-GCC compilers don't like these constructs. */
1702 #ifdef __GNUC__
1703 union
1704 {
1705 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
1706 enum CHAR_TABLE_STANDARD_SLOTS CHAR_TABLE_STANDARD_SLOTS;
1707 enum char_bits char_bits;
1708 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
1709 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
1710 enum Lisp_Bits Lisp_Bits;
1711 enum Lisp_Compiled Lisp_Compiled;
1712 enum maxargs maxargs;
1713 enum MAX_ALLOCA MAX_ALLOCA;
1714 enum More_Lisp_Bits More_Lisp_Bits;
1715 enum pvec_type pvec_type;
1716 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
1717 #endif /* __GNUC__ */