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