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