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