Sync up with r21-4-14-chise-0_21-22.
[chise/xemacs-chise.git-] / info / internals.info-4
1 This is ../info/internals.info, produced by makeinfo version 4.0b from
2 internals/internals.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Internals: (internals).       XEmacs Internals Manual.
7 END-INFO-DIR-ENTRY
8
9    Copyright (C) 1992 - 1996 Ben Wing.  Copyright (C) 1996, 1997 Sun
10 Microsystems.  Copyright (C) 1994 - 1998 Free Software Foundation.
11 Copyright (C) 1994, 1995 Board of Trustees, University of Illinois.
12
13    Permission is granted to make and distribute verbatim copies of this
14 manual provided the copyright notice and this permission notice are
15 preserved on all copies.
16
17    Permission is granted to copy and distribute modified versions of
18 this manual under the conditions for verbatim copying, provided that the
19 entire resulting derived work is distributed under the terms of a
20 permission notice identical to this one.
21
22    Permission is granted to copy and distribute translations of this
23 manual into another language, under the above conditions for modified
24 versions, except that this permission notice may be stated in a
25 translation approved by the Foundation.
26
27    Permission is granted to copy and distribute modified versions of
28 this manual under the conditions for verbatim copying, provided also
29 that the section entitled "GNU General Public License" is included
30 exactly as in the original, and provided that the entire resulting
31 derived work is distributed under the terms of a permission notice
32 identical to this one.
33
34    Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that the section entitled "GNU General Public License"
37 may be included in a translation approved by the Free Software
38 Foundation instead of in the original English.
39
40 \1f
41 File: internals.info,  Node: Modules for Interfacing with the File System,  Next: Modules for Other Aspects of the Lisp Interpreter and Object System,  Prev: Modules for the Redisplay Mechanism,  Up: A Summary of the Various XEmacs Modules
42
43 Modules for Interfacing with the File System
44 ============================================
45
46      lstream.c
47      lstream.h
48
49    These modules implement the "stream" Lisp object type.  This is an
50 internal-only Lisp object that implements a generic buffering stream.
51 The idea is to provide a uniform interface onto all sources and sinks of
52 data, including file descriptors, stdio streams, chunks of memory, Lisp
53 buffers, Lisp strings, etc.  That way, I/O functions can be written to
54 the stream interface and can transparently handle all possible sources
55 and sinks.  (For example, the `read' function can read data from a
56 file, a string, a buffer, or even a function that is called repeatedly
57 to return data, without worrying about where the data is coming from or
58 what-size chunks it is returned in.)
59
60    Note that in the C code, streams are called "lstreams" (for "Lisp
61 streams") to distinguish them from other kinds of streams, e.g. stdio
62 streams and C++ I/O streams.
63
64    Similar to other subsystems in XEmacs, lstreams are separated into
65 generic functions and a set of methods for the different types of
66 lstreams.  `lstream.c' provides implementations of many different types
67 of streams; others are provided, e.g., in `file-coding.c'.
68
69      fileio.c
70
71    This implements the basic primitives for interfacing with the file
72 system.  This includes primitives for reading files into buffers,
73 writing buffers into files, checking for the presence or accessibility
74 of files, canonicalizing file names, etc.  Note that these primitives
75 are usually not invoked directly by the user: There is a great deal of
76 higher-level Lisp code that implements the user commands such as
77 `find-file' and `save-buffer'.  This is similar to the distinction
78 between the lower-level primitives in `editfns.c' and the higher-level
79 user commands in `commands.c' and `simple.el'.
80
81      filelock.c
82
83    This file provides functions for detecting clashes between different
84 processes (e.g. XEmacs and some external process, or two different
85 XEmacs processes) modifying the same file.  (XEmacs can optionally use
86 the `lock/' subdirectory to provide a form of "locking" between
87 different XEmacs processes.)  This module is also used by the low-level
88 functions in `insdel.c' to ensure that, if the first modification is
89 being made to a buffer whose corresponding file has been externally
90 modified, the user is made aware of this so that the buffer can be
91 synched up with the external changes if necessary.
92
93      filemode.c
94
95    This file provides some miscellaneous functions that construct a
96 `rwxr-xr-x'-type permissions string (as might appear in an `ls'-style
97 directory listing) given the information returned by the `stat()'
98 system call.
99
100      dired.c
101      ndir.h
102
103    These files implement the XEmacs interface to directory searching.
104 This includes a number of primitives for determining the files in a
105 directory and for doing filename completion. (Remember that generic
106 completion is handled by a different mechanism, in `minibuf.c'.)
107
108    `ndir.h' is a header file used for the directory-searching emulation
109 functions provided in `sysdep.c' (see section J below), for systems
110 that don't provide any directory-searching functions. (On those
111 systems, directories can be read directly as files, and parsed.)
112
113      realpath.c
114
115    This file provides an implementation of the `realpath()' function
116 for expanding symbolic links, on systems that don't implement it or have
117 a broken implementation.
118
119 \1f
120 File: internals.info,  Node: Modules for Other Aspects of the Lisp Interpreter and Object System,  Next: Modules for Interfacing with the Operating System,  Prev: Modules for Interfacing with the File System,  Up: A Summary of the Various XEmacs Modules
121
122 Modules for Other Aspects of the Lisp Interpreter and Object System
123 ===================================================================
124
125      elhash.c
126      elhash.h
127      hash.c
128      hash.h
129
130    These files provide two implementations of hash tables.  Files
131 `hash.c' and `hash.h' provide a generic C implementation of hash tables
132 which can stand independently of XEmacs.  Files `elhash.c' and
133 `elhash.h' provide a separate implementation of hash tables that can
134 store only Lisp objects, and knows about Lispy things like garbage
135 collection, and implement the "hash-table" Lisp object type.
136
137      specifier.c
138      specifier.h
139
140    This module implements the "specifier" Lisp object type.  This is
141 primarily used for displayable properties, and allows for values that
142 are specific to a particular buffer, window, frame, device, or device
143 class, as well as a default value existing.  This is used, for example,
144 to control the height of the horizontal scrollbar or the appearance of
145 the `default', `bold', or other faces.  The specifier object consists
146 of a number of specifications, each of which maps from a buffer,
147 window, etc. to a value.  The function `specifier-instance' looks up a
148 value given a window (from which a buffer, frame, and device can be
149 derived).
150
151      chartab.c
152      chartab.h
153      casetab.c
154
155    `chartab.c' and `chartab.h' implement the "char table" Lisp object
156 type, which maps from characters or certain sorts of character ranges
157 to Lisp objects.  The implementation of this object type is optimized
158 for the internal representation of characters.  Char tables come in
159 different types, which affect the allowed object types to which a
160 character can be mapped and also dictate certain other properties of
161 the char table.
162
163    `casetab.c' implements one sort of char table, the "case table",
164 which maps characters to other characters of possibly different case.
165 These are used by XEmacs to implement case-changing primitives and to
166 do case-insensitive searching.
167
168      syntax.c
169      syntax.h
170
171    This module implements "syntax tables", another sort of char table
172 that maps characters into syntax classes that define the syntax of these
173 characters (e.g. a parenthesis belongs to a class of `open' characters
174 that have corresponding `close' characters and can be nested).  This
175 module also implements the Lisp "scanner", a set of primitives for
176 scanning over text based on syntax tables.  This is used, for example,
177 to find the matching parenthesis in a command such as `forward-sexp',
178 and by `font-lock.c' to locate quoted strings, comments, etc.
179
180      casefiddle.c
181
182    This module implements various Lisp primitives for upcasing,
183 downcasing and capitalizing strings or regions of buffers.
184
185      rangetab.c
186
187    This module implements the "range table" Lisp object type, which
188 provides for a mapping from ranges of integers to arbitrary Lisp
189 objects.
190
191      opaque.c
192      opaque.h
193
194    This module implements the "opaque" Lisp object type, an
195 internal-only Lisp object that encapsulates an arbitrary block of memory
196 so that it can be managed by the Lisp allocation system.  To create an
197 opaque object, you call `make_opaque()', passing a pointer to a block
198 of memory.  An object is created that is big enough to hold the memory,
199 which is copied into the object's storage.  The object will then stick
200 around as long as you keep pointers to it, after which it will be
201 automatically reclaimed.
202
203    Opaque objects can also have an arbitrary "mark method" associated
204 with them, in case the block of memory contains other Lisp objects that
205 need to be marked for garbage-collection purposes. (If you need other
206 object methods, such as a finalize method, you should just go ahead and
207 create a new Lisp object type--it's not hard.)
208
209      abbrev.c
210
211    This function provides a few primitives for doing dynamic
212 abbreviation expansion.  In XEmacs, most of the code for this has been
213 moved into Lisp.  Some C code remains for speed and because the
214 primitive `self-insert-command' (which is executed for all
215 self-inserting characters) hooks into the abbrev mechanism.
216 (`self-insert-command' is itself in C only for speed.)
217
218      doc.c
219
220    This function provides primitives for retrieving the documentation
221 strings of functions and variables.  These documentation strings contain
222 certain special markers that get dynamically expanded (e.g. a
223 reverse-lookup is performed on some named functions to retrieve their
224 current key bindings).  Some documentation strings (in particular, for
225 the built-in primitives and pre-loaded Lisp functions) are stored
226 externally in a file `DOC' in the `lib-src/' directory and need to be
227 fetched from that file. (Part of the build stage involves building this
228 file, and another part involves constructing an index for this file and
229 embedding it into the executable, so that the functions in `doc.c' do
230 not have to search the entire `DOC' file to find the appropriate
231 documentation string.)
232
233      md5.c
234
235    This function provides a Lisp primitive that implements the MD5
236 secure hashing scheme, used to create a large hash value of a string of
237 data such that the data cannot be derived from the hash value.  This is
238 used for various security applications on the Internet.
239
240 \1f
241 File: internals.info,  Node: Modules for Interfacing with the Operating System,  Next: Modules for Interfacing with X Windows,  Prev: Modules for Other Aspects of the Lisp Interpreter and Object System,  Up: A Summary of the Various XEmacs Modules
242
243 Modules for Interfacing with the Operating System
244 =================================================
245
246      callproc.c
247      process.c
248      process.h
249
250    These modules allow XEmacs to spawn and communicate with subprocesses
251 and network connections.
252
253    `callproc.c' implements (through the `call-process' primitive) what
254 are called "synchronous subprocesses".  This means that XEmacs runs a
255 program, waits till it's done, and retrieves its output.  A typical
256 example might be calling the `ls' program to get a directory listing.
257
258    `process.c' and `process.h' implement "asynchronous subprocesses".
259 This means that XEmacs starts a program and then continues normally,
260 not waiting for the process to finish.  Data can be sent to the process
261 or retrieved from it as it's running.  This is used for the `shell'
262 command (which provides a front end onto a shell program such as
263 `csh'), the mail and news readers implemented in XEmacs, etc.  The
264 result of calling `start-process' to start a subprocess is a process
265 object, a particular kind of object used to communicate with the
266 subprocess.  You can send data to the process by passing the process
267 object and the data to `send-process', and you can specify what happens
268 to data retrieved from the process by setting properties of the process
269 object. (When the process sends data, XEmacs receives a process event,
270 which says that there is data ready.  When `dispatch-event' is called
271 on this event, it reads the data from the process and does something
272 with it, as specified by the process object's properties.  Typically,
273 this means inserting the data into a buffer or calling a function.)
274 Another property of the process object is called the "sentinel", which
275 is a function that is called when the process terminates.
276
277    Process objects are also used for network connections (connections
278 to a process running on another machine).  Network connections are
279 started with `open-network-stream' but otherwise work just like
280 subprocesses.
281
282      sysdep.c
283      sysdep.h
284
285    These modules implement most of the low-level, messy operating-system
286 interface code.  This includes various device control (ioctl) operations
287 for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
288 is fairly system-dependent; thus the name of this module), and emulation
289 of standard library functions and system calls on systems that don't
290 provide them or have broken versions.
291
292      sysdir.h
293      sysfile.h
294      sysfloat.h
295      sysproc.h
296      syspwd.h
297      syssignal.h
298      systime.h
299      systty.h
300      syswait.h
301
302    These header files provide consistent interfaces onto
303 system-dependent header files and system calls.  The idea is that,
304 instead of including a standard header file like `<sys/param.h>' (which
305 may or may not exist on various systems) or having to worry about
306 whether all system provide a particular preprocessor constant, or
307 having to deal with the four different paradigms for manipulating
308 signals, you just include the appropriate `sys*.h' header file, which
309 includes all the right system header files, defines and missing
310 preprocessor constants, provides a uniform interface onto system calls,
311 etc.
312
313    `sysdir.h' provides a uniform interface onto directory-querying
314 functions. (In some cases, this is in conjunction with emulation
315 functions in `sysdep.c'.)
316
317    `sysfile.h' includes all the necessary header files for standard
318 system calls (e.g. `read()'), ensures that all necessary `open()' and
319 `stat()' preprocessor constants are defined, and possibly (usually)
320 substitutes sugared versions of `read()', `write()', etc. that
321 automatically restart interrupted I/O operations.
322
323    `sysfloat.h' includes the necessary header files for floating-point
324 operations.
325
326    `sysproc.h' includes the necessary header files for calling
327 `select()', `fork()', `execve()', socket operations, and the like, and
328 ensures that the `FD_*()' macros for descriptor-set manipulations are
329 available.
330
331    `syspwd.h' includes the necessary header files for obtaining
332 information from `/etc/passwd' (the functions are emulated under VMS).
333
334    `syssignal.h' includes the necessary header files for
335 signal-handling and provides a uniform interface onto the different
336 signal-handling and signal-blocking paradigms.
337
338    `systime.h' includes the necessary header files and provides uniform
339 interfaces for retrieving the time of day, setting file
340 access/modification times, getting the amount of time used by the XEmacs
341 process, etc.
342
343    `systty.h' buffers against the infinitude of different ways of
344 controlling TTY's.
345
346    `syswait.h' provides a uniform way of retrieving the exit status
347 from a `wait()'ed-on process (some systems use a union, others use an
348 int).
349
350      hpplay.c
351      libsst.c
352      libsst.h
353      libst.h
354      linuxplay.c
355      nas.c
356      sgiplay.c
357      sound.c
358      sunplay.c
359
360    These files implement the ability to play various sounds on some
361 types of computers.  You have to configure your XEmacs with sound
362 support in order to get this capability.
363
364    `sound.c' provides the generic interface.  It implements various
365 Lisp primitives and variables that let you specify which sounds should
366 be played in certain conditions. (The conditions are identified by
367 symbols, which are passed to `ding' to make a sound.  Various standard
368 functions call this function at certain times; if sound support does
369 not exist, a simple beep results.
370
371    `sgiplay.c', `sunplay.c', `hpplay.c', and `linuxplay.c' interface to
372 the machine's speaker for various different kind of machines.  This is
373 called "native" sound.
374
375    `nas.c' interfaces to a computer somewhere else on the network using
376 the NAS (Network Audio Server) protocol, playing sounds on that
377 machine.  This allows you to run XEmacs on a remote machine, with its
378 display set to your local machine, and have the sounds be made on your
379 local machine, provided that you have a NAS server running on your local
380 machine.
381
382    `libsst.c', `libsst.h', and `libst.h' provide some additional
383 functions for playing sound on a Sun SPARC but are not currently in use.
384
385      tooltalk.c
386      tooltalk.h
387
388    These two modules implement an interface to the ToolTalk protocol,
389 which is an interprocess communication protocol implemented on some
390 versions of Unix.  ToolTalk is a high-level protocol that allows
391 processes to register themselves as providers of particular services;
392 other processes can then request a service without knowing or caring
393 exactly who is providing the service.  It is similar in spirit to the
394 DDE protocol provided under Microsoft Windows.  ToolTalk is a part of
395 the new CDE (Common Desktop Environment) specification and is used to
396 connect the parts of the SPARCWorks development environment.
397
398      getloadavg.c
399
400    This module provides the ability to retrieve the system's current
401 load average. (The way to do this is highly system-specific,
402 unfortunately, and requires a lot of special-case code.)
403
404      sunpro.c
405
406    This module provides a small amount of code used internally at Sun to
407 keep statistics on the usage of XEmacs.
408
409      broken-sun.h
410      strcmp.c
411      strcpy.c
412      sunOS-fix.c
413
414    These files provide replacement functions and prototypes to fix
415 numerous bugs in early releases of SunOS 4.1.
416
417      hftctl.c
418
419    This module provides some terminal-control code necessary on
420 versions of AIX prior to 4.1.
421
422 \1f
423 File: internals.info,  Node: Modules for Interfacing with X Windows,  Next: Modules for Internationalization,  Prev: Modules for Interfacing with the Operating System,  Up: A Summary of the Various XEmacs Modules
424
425 Modules for Interfacing with X Windows
426 ======================================
427
428      Emacs.ad.h
429
430    A file generated from `Emacs.ad', which contains XEmacs-supplied
431 fallback resources (so that XEmacs has pretty defaults).
432
433      EmacsFrame.c
434      EmacsFrame.h
435      EmacsFrameP.h
436
437    These modules implement an Xt widget class that encapsulates a frame.
438 This is for ease in integrating with Xt.  The EmacsFrame widget covers
439 the entire X window except for the menubar; the scrollbars are
440 positioned on top of the EmacsFrame widget.
441
442    *Warning:* Abandon hope, all ye who enter here.  This code took an
443 ungodly amount of time to get right, and is likely to fall apart
444 mercilessly at the slightest change.  Such is life under Xt.
445
446      EmacsManager.c
447      EmacsManager.h
448      EmacsManagerP.h
449
450    These modules implement a simple Xt manager (i.e. composite) widget
451 class that simply lets its children set whatever geometry they want.
452 It's amazing that Xt doesn't provide this standardly, but on second
453 thought, it makes sense, considering how amazingly broken Xt is.
454
455      EmacsShell-sub.c
456      EmacsShell.c
457      EmacsShell.h
458      EmacsShellP.h
459
460    These modules implement two Xt widget classes that are subclasses of
461 the TopLevelShell and TransientShell classes.  This is necessary to deal
462 with more brokenness that Xt has sadistically thrust onto the backs of
463 developers.
464
465      xgccache.c
466      xgccache.h
467
468    These modules provide functions for maintenance and caching of GC's
469 (graphics contexts) under the X Window System.  This code is junky and
470 needs to be rewritten.
471
472      select-msw.c
473      select-x.c
474      select.c
475      select.h
476
477    This module provides an interface to the X Window System's concept of
478 "selections", the standard way for X applications to communicate with
479 each other.
480
481      xintrinsic.h
482      xintrinsicp.h
483      xmmanagerp.h
484      xmprimitivep.h
485
486    These header files are similar in spirit to the `sys*.h' files and
487 buffer against different implementations of Xt and Motif.
488
489    * `xintrinsic.h' should be included in place of `<Intrinsic.h>'.
490
491    * `xintrinsicp.h' should be included in place of `<IntrinsicP.h>'.
492
493    * `xmmanagerp.h' should be included in place of `<XmManagerP.h>'.
494
495    * `xmprimitivep.h' should be included in place of `<XmPrimitiveP.h>'.
496
497      xmu.c
498      xmu.h
499
500    These files provide an emulation of the Xmu library for those systems
501 (i.e. HPUX) that don't provide it as a standard part of X.
502
503      ExternalClient-Xlib.c
504      ExternalClient.c
505      ExternalClient.h
506      ExternalClientP.h
507      ExternalShell.c
508      ExternalShell.h
509      ExternalShellP.h
510      extw-Xlib.c
511      extw-Xlib.h
512      extw-Xt.c
513      extw-Xt.h
514
515    These files provide the "external widget" interface, which allows an
516 XEmacs frame to appear as a widget in another application.  To do this,
517 you have to configure with `--external-widget'.
518
519    `ExternalShell*' provides the server (XEmacs) side of the connection.
520
521    `ExternalClient*' provides the client (other application) side of
522 the connection.  These files are not compiled into XEmacs but are
523 compiled into libraries that are then linked into your application.
524
525    `extw-*' is common code that is used for both the client and server.
526
527    Don't touch this code; something is liable to break if you do.
528
529 \1f
530 File: internals.info,  Node: Modules for Internationalization,  Prev: Modules for Interfacing with X Windows,  Up: A Summary of the Various XEmacs Modules
531
532 Modules for Internationalization
533 ================================
534
535      mule-canna.c
536      mule-ccl.c
537      mule-charset.c
538      mule-charset.h
539      file-coding.c
540      file-coding.h
541      mule-mcpath.c
542      mule-mcpath.h
543      mule-wnnfns.c
544      mule.c
545
546    These files implement the MULE (Asian-language) support.  Note that
547 MULE actually provides a general interface for all sorts of languages,
548 not just Asian languages (although they are generally the most
549 complicated to support).  This code is still in beta.
550
551    `mule-charset.*' and `file-coding.*' provide the heart of the XEmacs
552 MULE support.  `mule-charset.*' implements the "charset" Lisp object
553 type, which encapsulates a character set (an ordered one- or
554 two-dimensional set of characters, such as US ASCII or JISX0208 Japanese
555 Kanji).
556
557    `file-coding.*' implements the "coding-system" Lisp object type,
558 which encapsulates a method of converting between different encodings.
559 An encoding is a representation of a stream of characters, possibly
560 from multiple character sets, using a stream of bytes or words, and
561 defines (e.g.) which escape sequences are used to specify particular
562 character sets, how the indices for a character are converted into bytes
563 (sometimes this involves setting the high bit; sometimes complicated
564 rearranging of the values takes place, as in the Shift-JIS encoding),
565 etc.
566
567    `mule-ccl.c' provides the CCL (Code Conversion Language)
568 interpreter.  CCL is similar in spirit to Lisp byte code and is used to
569 implement converters for custom encodings.
570
571    `mule-canna.c' and `mule-wnnfns.c' implement interfaces to external
572 programs used to implement the Canna and WNN input methods,
573 respectively.  This is currently in beta.
574
575    `mule-mcpath.c' provides some functions to allow for pathnames
576 containing extended characters.  This code is fragmentary, obsolete, and
577 completely non-working.  Instead, PATHNAME-CODING-SYSTEM is used to
578 specify conversions of names of files and directories.  The standard C
579 I/O functions like `open()' are wrapped so that conversion occurs
580 automatically.
581
582    `mule.c' provides a few miscellaneous things that should probably be
583 elsewhere.
584
585      intl.c
586
587    This provides some miscellaneous internationalization code for
588 implementing message translation and interfacing to the Ximp input
589 method.  None of this code is currently working.
590
591      iso-wide.h
592
593    This contains leftover code from an earlier implementation of
594 Asian-language support, and is not currently used.
595
596 \1f
597 File: internals.info,  Node: Allocation of Objects in XEmacs Lisp,  Next: Dumping,  Prev: A Summary of the Various XEmacs Modules,  Up: Top
598
599 Allocation of Objects in XEmacs Lisp
600 ************************************
601
602 * Menu:
603
604 * Introduction to Allocation::
605 * Garbage Collection::
606 * GCPROing::
607 * Garbage Collection - Step by Step::
608 * Integers and Characters::
609 * Allocation from Frob Blocks::
610 * lrecords::
611 * Low-level allocation::
612 * Cons::
613 * Vector::
614 * Bit Vector::
615 * Symbol::
616 * Marker::
617 * String::
618 * Compiled Function::
619
620 \1f
621 File: internals.info,  Node: Introduction to Allocation,  Next: Garbage Collection,  Prev: Allocation of Objects in XEmacs Lisp,  Up: Allocation of Objects in XEmacs Lisp
622
623 Introduction to Allocation
624 ==========================
625
626    Emacs Lisp, like all Lisps, has garbage collection.  This means that
627 the programmer never has to explicitly free (destroy) an object; it
628 happens automatically when the object becomes inaccessible.  Most
629 experts agree that garbage collection is a necessity in a modern,
630 high-level language.  Its omission from C stems from the fact that C was
631 originally designed to be a nice abstract layer on top of assembly
632 language, for writing kernels and basic system utilities rather than
633 large applications.
634
635    Lisp objects can be created by any of a number of Lisp primitives.
636 Most object types have one or a small number of basic primitives for
637 creating objects.  For conses, the basic primitive is `cons'; for
638 vectors, the primitives are `make-vector' and `vector'; for symbols,
639 the primitives are `make-symbol' and `intern'; etc.  Some Lisp objects,
640 especially those that are primarily used internally, have no
641 corresponding Lisp primitives.  Every Lisp object, though, has at least
642 one C primitive for creating it.
643
644    Recall from section (VII) that a Lisp object, as stored in a 32-bit
645 or 64-bit word, has a few tag bits, and a "value" that occupies the
646 remainder of the bits.  We can separate the different Lisp object types
647 into three broad categories:
648
649    * (a) Those for whom the value directly represents the contents of
650      the Lisp object.  Only two types are in this category: integers and
651      characters.  No special allocation or garbage collection is
652      necessary for such objects.  Lisp objects of these types do not
653      need to be `GCPRO'ed.
654
655    In the remaining two categories, the type is stored in the object
656 itself.  The tag for all such objects is the generic "lrecord"
657 (Lisp_Type_Record) tag.  The first bytes of the object's structure are
658 an integer (actually a char) characterising the object's type and some
659 flags, in particular the mark bit used for garbage collection.  A
660 structure describing the type is accessible thru the
661 lrecord_implementation_table indexed with said integer.  This structure
662 includes the method pointers and a pointer to a string naming the type.
663
664    * (b) Those lrecords that are allocated in frob blocks (see above).
665      This includes the objects that are most common and relatively
666      small, and includes conses, strings, subrs, floats, compiled
667      functions, symbols, extents, events, and markers.  With the
668      cleanup of frob blocks done in 19.12, it's not terribly hard to
669      add more objects to this category, but it's a bit trickier than
670      adding an object type to type (c) (esp. if the object needs a
671      finalization method), and is not likely to save much space unless
672      the object is small and there are many of them. (In fact, if there
673      are very few of them, it might actually waste space.)
674
675    * (c) Those lrecords that are individually `malloc()'ed.  These are
676      called "lcrecords".  All other types are in this category.  Adding
677      a new type to this category is comparatively easy, and all types
678      added since 19.8 (when the current allocation scheme was devised,
679      by Richard Mlynarik), with the exception of the character type,
680      have been in this category.
681
682    Note that bit vectors are a bit of a special case.  They are simple
683 lrecords as in category (b), but are individually `malloc()'ed like
684 vectors.  You can basically view them as exactly like vectors except
685 that their type is stored in lrecord fashion rather than in
686 directly-tagged fashion.
687
688 \1f
689 File: internals.info,  Node: Garbage Collection,  Next: GCPROing,  Prev: Introduction to Allocation,  Up: Allocation of Objects in XEmacs Lisp
690
691 Garbage Collection
692 ==================
693
694    Garbage collection is simple in theory but tricky to implement.
695 Emacs Lisp uses the oldest garbage collection method, called "mark and
696 sweep".  Garbage collection begins by starting with all accessible
697 locations (i.e. all variables and other slots where Lisp objects might
698 occur) and recursively traversing all objects accessible from those
699 slots, marking each one that is found.  We then go through all of
700 memory and free each object that is not marked, and unmarking each
701 object that is marked.  Note that "all of memory" means all currently
702 allocated objects.  Traversing all these objects means traversing all
703 frob blocks, all vectors (which are chained in one big list), and all
704 lcrecords (which are likewise chained).
705
706    Garbage collection can be invoked explicitly by calling
707 `garbage-collect' but is also called automatically by `eval', once a
708 certain amount of memory has been allocated since the last garbage
709 collection (according to `gc-cons-threshold').
710
711 \1f
712 File: internals.info,  Node: GCPROing,  Next: Garbage Collection - Step by Step,  Prev: Garbage Collection,  Up: Allocation of Objects in XEmacs Lisp
713
714 `GCPRO'ing
715 ==========
716
717    `GCPRO'ing is one of the ugliest and trickiest parts of Emacs
718 internals.  The basic idea is that whenever garbage collection occurs,
719 all in-use objects must be reachable somehow or other from one of the
720 roots of accessibility.  The roots of accessibility are:
721
722   1. All objects that have been `staticpro()'d or
723      `staticpro_nodump()'ed.  This is used for any global C variables
724      that hold Lisp objects.  A call to `staticpro()' happens implicitly
725      as a result of any symbols declared with `defsymbol()' and any
726      variables declared with `DEFVAR_FOO()'.  You need to explicitly
727      call `staticpro()' (in the `vars_of_foo()' method of a module) for
728      other global C variables holding Lisp objects. (This typically
729      includes internal lists and such things.).  Use
730      `staticpro_nodump()' only in the rare cases when you do not want
731      the pointed variable to be saved at dump time but rather recompute
732      it at startup.
733
734      Note that `obarray' is one of the `staticpro()'d things.
735      Therefore, all functions and variables get marked through this.
736
737   2. Any shadowed bindings that are sitting on the `specpdl' stack.
738
739   3. Any objects sitting in currently active (Lisp) stack frames,
740      catches, and condition cases.
741
742   4. A couple of special-case places where active objects are located.
743
744   5. Anything currently marked with `GCPRO'.
745
746    Marking with `GCPRO' is necessary because some C functions (quite a
747 lot, in fact), allocate objects during their operation.  Quite
748 frequently, there will be no other pointer to the object while the
749 function is running, and if a garbage collection occurs and the object
750 needs to be referenced again, bad things will happen.  The solution is
751 to mark those objects with `GCPRO'.  Unfortunately this is easy to
752 forget, and there is basically no way around this problem.  Here are
753 some rules, though:
754
755   1. For every `GCPRON', there have to be declarations of `struct gcpro
756      gcpro1, gcpro2', etc.
757
758   2. You _must_ `UNGCPRO' anything that's `GCPRO'ed, and you _must not_
759      `UNGCPRO' if you haven't `GCPRO'ed.  Getting either of these wrong
760      will lead to crashes, often in completely random places unrelated
761      to where the problem lies.
762
763   3. The way this actually works is that all currently active `GCPRO's
764      are chained through the `struct gcpro' local variables, with the
765      variable `gcprolist' pointing to the head of the list and the nth
766      local `gcpro' variable pointing to the first `gcpro' variable in
767      the next enclosing stack frame.  Each `GCPRO'ed thing is an
768      lvalue, and the `struct gcpro' local variable contains a pointer to
769      this lvalue.  This is why things will mess up badly if you don't
770      pair up the `GCPRO's and `UNGCPRO's--you will end up with
771      `gcprolist's containing pointers to `struct gcpro's or local
772      `Lisp_Object' variables in no-longer-active stack frames.
773
774   4. It is actually possible for a single `struct gcpro' to protect a
775      contiguous array of any number of values, rather than just a
776      single lvalue.  To effect this, call `GCPRON' as usual on the
777      first object in the array and then set `gcproN.nvars'.
778
779   5. *Strings are relocated.*  What this means in practice is that the
780      pointer obtained using `XSTRING_DATA()' is liable to change at any
781      time, and you should never keep it around past any function call,
782      or pass it as an argument to any function that might cause a
783      garbage collection.  This is why a number of functions accept
784      either a "non-relocatable" `char *' pointer or a relocatable Lisp
785      string, and only access the Lisp string's data at the very last
786      minute.  In some cases, you may end up having to `alloca()' some
787      space and copy the string's data into it.
788
789   6. By convention, if you have to nest `GCPRO''s, use `NGCPRON' (along
790      with `struct gcpro ngcpro1, ngcpro2', etc.), `NNGCPRON', etc.
791      This avoids compiler warnings about shadowed locals.
792
793   7. It is _always_ better to err on the side of extra `GCPRO's rather
794      than too few.  The extra cycles spent on this are almost never
795      going to make a whit of difference in the speed of anything.
796
797   8. The general rule to follow is that caller, not callee, `GCPRO's.
798      That is, you should not have to explicitly `GCPRO' any Lisp objects
799      that are passed in as parameters.
800
801      One exception from this rule is if you ever plan to change the
802      parameter value, and store a new object in it.  In that case, you
803      _must_ `GCPRO' the parameter, because otherwise the new object
804      will not be protected.
805
806      So, if you create any Lisp objects (remember, this happens in all
807      sorts of circumstances, e.g. with `Fcons()', etc.), you are
808      responsible for `GCPRO'ing them, unless you are _absolutely sure_
809      that there's no possibility that a garbage-collection can occur
810      while you need to use the object.  Even then, consider `GCPRO'ing.
811
812   9. A garbage collection can occur whenever anything calls `Feval', or
813      whenever a QUIT can occur where execution can continue past this.
814      (Remember, this is almost anywhere.)
815
816  10. If you have the _least smidgeon of doubt_ about whether you need
817      to `GCPRO', you should `GCPRO'.
818
819  11. Beware of `GCPRO'ing something that is uninitialized.  If you have
820      any shade of doubt about this, initialize all your variables to
821      `Qnil'.
822
823  12. Be careful of traps, like calling `Fcons()' in the argument to
824      another function.  By the "caller protects" law, you should be
825      `GCPRO'ing the newly-created cons, but you aren't.  A certain
826      number of functions that are commonly called on freshly created
827      stuff (e.g. `nconc2()', `Fsignal()'), break the "caller protects"
828      law and go ahead and `GCPRO' their arguments so as to simplify
829      things, but make sure and check if it's OK whenever doing
830      something like this.
831
832  13. Once again, remember to `GCPRO'!  Bugs resulting from insufficient
833      `GCPRO'ing are intermittent and extremely difficult to track down,
834      often showing up in crashes inside of `garbage-collect' or in
835      weirdly corrupted objects or even in incorrect values in a totally
836      different section of code.
837
838    Given the extremely error-prone nature of the `GCPRO' scheme, and
839 the difficulties in tracking down, it should be considered a deficiency
840 in the XEmacs code.  A solution to this problem would involve
841 implementing so-called "conservative" garbage collection for the C
842 stack.  That involves looking through all of stack memory and treating
843 anything that looks like a reference to an object as a reference.  This
844 will result in a few objects not getting collected when they should, but
845 it obviates the need for `GCPRO'ing, and allows garbage collection to
846 happen at any point at all, such as during object allocation.
847
848 \1f
849 File: internals.info,  Node: Garbage Collection - Step by Step,  Next: Integers and Characters,  Prev: GCPROing,  Up: Allocation of Objects in XEmacs Lisp
850
851 Garbage Collection - Step by Step
852 =================================
853
854 * Menu:
855
856 * Invocation::
857 * garbage_collect_1::
858 * mark_object::
859 * gc_sweep::
860 * sweep_lcrecords_1::
861 * compact_string_chars::
862 * sweep_strings::
863 * sweep_bit_vectors_1::
864
865 \1f
866 File: internals.info,  Node: Invocation,  Next: garbage_collect_1,  Prev: Garbage Collection - Step by Step,  Up: Garbage Collection - Step by Step
867
868 Invocation
869 ----------
870
871    The first thing that anyone should know about garbage collection is:
872 when and how the garbage collector is invoked. One might think that this
873 could happen every time new memory is allocated, e.g. new objects are
874 created, but this is _not_ the case. Instead, we have the following
875 situation:
876
877    The entry point of any process of garbage collection is an invocation
878 of the function `garbage_collect_1' in file `alloc.c'. The invocation
879 can occur _explicitly_ by calling the function `Fgarbage_collect' (in
880 addition this function provides information about the freed memory), or
881 can occur _implicitly_ in four different situations:
882   1. In function `main_1' in file `emacs.c'. This function is called at
883      each startup of xemacs. The garbage collection is invoked after all
884      initial creations are completed, but only if a special internal
885      error checking-constant `ERROR_CHECK_GC' is defined.
886
887   2. In function `disksave_object_finalization' in file `alloc.c'. The
888      only purpose of this function is to clear the objects from memory
889      which need not be stored with xemacs when we dump out an
890      executable. This is only done by `Fdump_emacs' or by
891      `Fdump_emacs_data' respectively (both in `emacs.c'). The actual
892      clearing is accomplished by making these objects unreachable and
893      starting a garbage collection. The function is only used while
894      building xemacs.
895
896   3. In function `Feval / eval' in file `eval.c'. Each time the well
897      known and often used function eval is called to evaluate a form,
898      one of the first things that could happen, is a potential call of
899      `garbage_collect_1'. There exist three global variables,
900      `consing_since_gc' (counts the created cons-cells since the last
901      garbage collection), `gc_cons_threshold' (a specified threshold
902      after which a garbage collection occurs) and `always_gc'. If
903      `always_gc' is set or if the threshold is exceeded, the garbage
904      collection will start.
905
906   4. In function `Ffuncall / funcall' in file `eval.c'. This function
907      evaluates calls of elisp functions and works according to `Feval'.
908
909    The upshot is that garbage collection can basically occur everywhere
910 `Feval', respectively `Ffuncall', is used - either directly or through
911 another function. Since calls to these two functions are hidden in
912 various other functions, many calls to `garbage_collect_1' are not
913 obviously foreseeable, and therefore unexpected. Instances where they
914 are used that are worth remembering are various elisp commands, as for
915 example `or', `and', `if', `cond', `while', `setq', etc., miscellaneous
916 `gui_item_...' functions, everything related to `eval' (`Feval_buffer',
917 `call0', ...) and inside `Fsignal'. The latter is used to handle
918 signals, as for example the ones raised by every `QUIT'-macro triggered
919 after pressing Ctrl-g.
920
921 \1f
922 File: internals.info,  Node: garbage_collect_1,  Next: mark_object,  Prev: Invocation,  Up: Garbage Collection - Step by Step
923
924 `garbage_collect_1'
925 -------------------
926
927    We can now describe exactly what happens after the invocation takes
928 place.
929   1. There are several cases in which the garbage collector is left
930      immediately: when we are already garbage collecting
931      (`gc_in_progress'), when the garbage collection is somehow
932      forbidden (`gc_currently_forbidden'), when we are currently
933      displaying something (`in_display') or when we are preparing for
934      the armageddon of the whole system (`preparing_for_armageddon').
935
936   2. Next the correct frame in which to put all the output occurring
937      during garbage collecting is determined. In order to be able to
938      restore the old display's state after displaying the message, some
939      data about the current cursor position has to be saved. The
940      variables `pre_gc_cursor' and `cursor_changed' take care of that.
941
942   3. The state of `gc_currently_forbidden' must be restored after the
943      garbage collection, no matter what happens during the process. We
944      accomplish this by `record_unwind_protect'ing the suitable function
945      `restore_gc_inhibit' together with the current value of
946      `gc_currently_forbidden'.
947
948   4. If we are concurrently running an interactive xemacs session, the
949      next step is simply to show the garbage collector's cursor/message.
950
951   5. The following steps are the intrinsic steps of the garbage
952      collector, therefore `gc_in_progress' is set.
953
954   6. For debugging purposes, it is possible to copy the current C stack
955      frame. However, this seems to be a currently unused feature.
956
957   7. Before actually starting to go over all live objects, references to
958      objects that are no longer used are pruned. We only have to do
959      this for events (`clear_event_resource') and for specifiers
960      (`cleanup_specifiers').
961
962   8. Now the mark phase begins and marks all accessible elements. In
963      order to start from all slots that serve as roots of
964      accessibility, the function `mark_object' is called for each root
965      individually to go out from there to mark all reachable objects.
966      All roots that are traversed are shown in their processed order:
967         * all constant symbols and static variables that are registered
968           via `staticpro' in the dynarr `staticpros'.  *Note Adding
969           Global Lisp Variables::.
970
971         * all Lisp objects that are created in C functions and that
972           must be protected from freeing them. They are registered in
973           the global list `gcprolist'.  *Note GCPROing::.
974
975         * all local variables (i.e. their name fields `symbol' and old
976           values `old_values') that are bound during the evaluation by
977           the Lisp engine. They are stored in `specbinding' structs
978           pushed on a stack called `specpdl'.  *Note Dynamic Binding;
979           The specbinding Stack; Unwind-Protects::.
980
981         * all catch blocks that the Lisp engine encounters during the
982           evaluation cause the creation of structs `catchtag' inserted
983           in the list `catchlist'. Their tag (`tag') and value (`val'
984           fields are freshly created objects and therefore have to be
985           marked.  *Note Catch and Throw::.
986
987         * every function application pushes new structs `backtrace' on
988           the call stack of the Lisp engine (`backtrace_list'). The
989           unique parts that have to be marked are the fields for each
990           function (`function') and all their arguments (`args').
991           *Note Evaluation::.
992
993         * all objects that are used by the redisplay engine that must
994           not be freed are marked by a special function called
995           `mark_redisplay' (in `redisplay.c').
996
997         * all objects created for profiling purposes are allocated by C
998           functions instead of using the lisp allocation mechanisms. In
999           order to receive the right ones during the sweep phase, they
1000           also have to be marked manually. That is done by the function
1001           `mark_profiling_info'
1002
1003   9. Hash tables in XEmacs belong to a kind of special objects that
1004      make use of a concept often called 'weak pointers'.  To make a
1005      long story short, these kind of pointers are not followed during
1006      the estimation of the live objects during garbage collection.  Any
1007      object referenced only by weak pointers is collected anyway, and
1008      the reference to it is cleared. In hash tables there are different
1009      usage patterns of them, manifesting in different types of hash
1010      tables, namely 'non-weak', 'weak', 'key-weak' and 'value-weak'
1011      (internally also 'key-car-weak' and 'value-car-weak') hash tables,
1012      each clearing entries depending on different conditions. More
1013      information can be found in the documentation to the function
1014      `make-hash-table'.
1015
1016      Because there are complicated dependency rules about when and what
1017      to mark while processing weak hash tables, the standard `marker'
1018      method is only active if it is marking non-weak hash tables. As
1019      soon as a weak component is in the table, the hash table entries
1020      are ignored while marking. Instead their marking is done each
1021      separately by the function `finish_marking_weak_hash_tables'. This
1022      function iterates over each hash table entry `hentries' for each
1023      weak hash table in `Vall_weak_hash_tables'. Depending on the type
1024      of a table, the appropriate action is performed.  If a table is
1025      acting as `HASH_TABLE_KEY_WEAK', and a key already marked,
1026      everything reachable from the `value' component is marked. If it is
1027      acting as a `HASH_TABLE_VALUE_WEAK' and the value component is
1028      already marked, the marking starts beginning only from the `key'
1029      component.  If it is a `HASH_TABLE_KEY_CAR_WEAK' and the car of
1030      the key entry is already marked, we mark both the `key' and
1031      `value' components.  Finally, if the table is of the type
1032      `HASH_TABLE_VALUE_CAR_WEAK' and the car of the value components is
1033      already marked, again both the `key' and the `value' components
1034      get marked.
1035
1036      Again, there are lists with comparable properties called weak
1037      lists. There exist different peculiarities of their types called
1038      `simple', `assoc', `key-assoc' and `value-assoc'. You can find
1039      further details about them in the description to the function
1040      `make-weak-list'. The scheme of their marking is similar: all weak
1041      lists are listed in `Qall_weak_lists', therefore we iterate over
1042      them. The marking is advanced until we hit an already marked pair.
1043      Then we know that during a former run all the rest has been marked
1044      completely. Again, depending on the special type of the weak list,
1045      our jobs differ. If it is a `WEAK_LIST_SIMPLE' and the elem is
1046      marked, we mark the `cons' part. If it is a `WEAK_LIST_ASSOC' and
1047      not a pair or a pair with both marked car and cdr, we mark the
1048      `cons' and the `elem'. If it is a `WEAK_LIST_KEY_ASSOC' and not a
1049      pair or a pair with a marked car of the elem, we mark the `cons'
1050      and the `elem'. Finally, if it is a `WEAK_LIST_VALUE_ASSOC' and
1051      not a pair or a pair with a marked cdr of the elem, we mark both
1052      the `cons' and the `elem'.
1053
1054      Since, by marking objects in reach from weak hash tables and weak
1055      lists, other objects could get marked, this perhaps implies
1056      further marking of other weak objects, both finishing functions
1057      are redone as long as yet unmarked objects get freshly marked.
1058
1059  10. After completing the special marking for the weak hash tables and
1060      for the weak lists, all entries that point to objects that are
1061      going to be swept in the further process are useless, and
1062      therefore have to be removed from the table or the list.
1063
1064      The function `prune_weak_hash_tables' does the job for weak hash
1065      tables. Totally unmarked hash tables are removed from the list
1066      `Vall_weak_hash_tables'. The other ones are treated more carefully
1067      by scanning over all entries and removing one as soon as one of
1068      the components `key' and `value' is unmarked.
1069
1070      The same idea applies to the weak lists. It is accomplished by
1071      `prune_weak_lists': An unmarked list is pruned from
1072      `Vall_weak_lists' immediately. A marked list is treated more
1073      carefully by going over it and removing just the unmarked pairs.
1074
1075  11. The function `prune_specifiers' checks all listed specifiers held
1076      in `Vall_specifiers' and removes the ones from the lists that are
1077      unmarked.
1078
1079  12. All syntax tables are stored in a list called
1080      `Vall_syntax_tables'. The function `prune_syntax_tables' walks
1081      through it and unlinks the tables that are unmarked.
1082
1083  13. Next, we will attack the complete sweeping - the function
1084      `gc_sweep' which holds the predominance.
1085
1086  14. First, all the variables with respect to garbage collection are
1087      reset. `consing_since_gc' - the counter of the created cells since
1088      the last garbage collection - is set back to 0, and
1089      `gc_in_progress' is not `true' anymore.
1090
1091  15. In case the session is interactive, the displayed cursor and
1092      message are removed again.
1093
1094  16. The state of `gc_inhibit' is restored to the former value by
1095      unwinding the stack.
1096
1097  17. A small memory reserve is always held back that can be reached by
1098      `breathing_space'. If nothing more is left, we create a new reserve
1099      and exit.
1100
1101 \1f
1102 File: internals.info,  Node: mark_object,  Next: gc_sweep,  Prev: garbage_collect_1,  Up: Garbage Collection - Step by Step
1103
1104 `mark_object'
1105 -------------
1106
1107    The first thing that is checked while marking an object is whether
1108 the object is a real Lisp object `Lisp_Type_Record' or just an integer
1109 or a character. Integers and characters are the only two types that are
1110 stored directly - without another level of indirection, and therefore
1111 they don't have to be marked and collected.  *Note How Lisp Objects Are
1112 Represented in C::.
1113
1114    The second case is the one we have to handle. It is the one when we
1115 are dealing with a pointer to a Lisp object. But, there exist also three
1116 possibilities, that prevent us from doing anything while marking: The
1117 object is read only which prevents it from being garbage collected,
1118 i.e. marked (`C_READONLY_RECORD_HEADER'). The object in question is
1119 already marked, and need not be marked for the second time (checked by
1120 `MARKED_RECORD_HEADER_P'). If it is a special, unmarkable object
1121 (`UNMARKABLE_RECORD_HEADER_P', apparently, these are objects that sit
1122 in some const space, and can therefore not be marked, see
1123 `this_one_is_unmarkable' in `alloc.c').
1124
1125    Now, the actual marking is feasible. We do so by once using the macro
1126 `MARK_RECORD_HEADER' to mark the object itself (actually the special
1127 flag in the lrecord header), and calling its special marker "method"
1128 `marker' if available. The marker method marks every other object that
1129 is in reach from our current object. Note, that these marker methods
1130 should not call `mark_object' recursively, but instead should return
1131 the next object from where further marking has to be performed.
1132
1133    In case another object was returned, as mentioned before, we
1134 reiterate the whole `mark_object' process beginning with this next
1135 object.
1136