# SBCL Manual
###### [in package SB-MANUAL]
This is an unofficial rendering of the SBCL Manual
using MGL-PAX with the same content as the
official version at but with heavy linking
internally, to the HyperSpec, and to the source code on
[GitHub](https://github.com/sbcl/sbcl).
The output is for SBCL version 2.6.10.172-0763357, generated 2026-11-13 07:28:04. See
for this document in other formats.
This manual is part of the SBCL software system. See the
README file for more information. The manual is largely
derived from the manual for the [CMUCL](https://cmucl.org/) system,
which was produced at Carnegie Mellon University and later released
into the public domain. The manual is in the public domain and is
provided with absolutely no warranty. See the COPYING and
CREDITS files for more information.
## Introduction
Steel Bank Common Lisp (SBCL) is a free and open-source ANSI Common
Lisp implementation with a high-performance native Compiler. In
addition, it provides Unicode Support, Threading, an interactive
environment including a Debugger, a Statistical Profiler, a code
coverage tool, and many other extensions.
- Homepage:
- Reporting Bugs:
- Mailing lists:
- Repository:
- GitHub mirror:
- Supported platforms:
This manual focuses on behavior specific to SBCL, not on behavior
common to all implementations of ANSI Common Lisp. See
Further Resources for information about The SBCL Project and
Common Lisp.
### Beyond this Manual
Documentation for non-ANSI extensions for various commands is
available interactively. Tools that have their own command
prompts (e.g. the Debugger, and inspect) provide a help command.
Extensions without a command prompt (such as trace) are described in
their documentation strings, unless your SBCL was compiled with the
--without-sb-doc option to omit them (see Customizing the Build),
in which case they are only readable in the source code.
This manual itself is available interactively via the sb-manual
module.
Besides this user manual, the following files are included in
Source Distributions, Binary Distributions and the
SBCL Repository. When SBCL is installed, they
may be found in e.g. /usr/local/share/doc/sbcl/ or
/usr/share/doc/sbcl/.
- COPYING: License and copyright summary
- CREDITS: Authorship information on various parts of SBCL
- NEWS: Summaries of changes between various SBCL versions
And, of course, don't forget the Language Reference.
### Highlights
SBCL comes with numerous extensions, some in core and some in modules
loadable with require. We only list some of the highlights here.
Unfortunately, not all of these extensions have proper documentation
yet.
- Foreign Function Interface: The sb-alien package allows
interfacing with C-code, loading shared object files, etc. See
Foreign Function Interface.
sb-grovel can be used to partially automate generation of
foreign function interface definitions.
- Native Threads: SBCL has native threads on numerous platforms,
capable of taking advantage of SMP on multiprocessor machines. See
Threading.
- Network Interface: The sb-bsd-sockets module is a low-level
networking interface, providing both TCP and UDP sockets. See
Networking.
- Operating System Interface: The sb-ext package contains a
number of functions for running external processes, accessing
environment variables, etc.
The sb-posix module provides a lispy interface to standard
POSIX facilities.
- Profiling: The sb-profile package provides an exact,
per-function Deterministic Profiler, while the sb-sprof module
is SBCL's Statistical Profiler, capable of call-graph generation
and instruction level profiling, which also supports allocation
profiling.
- Executable Delivery: The :executable argument to
sb-ext:save-lisp-and-die can produce a stand-alone executable
containing both an image of the current Lisp session and an SBCL
runtime.
- Timeouts and Deadlines: SBCL allows restricting the execution
time of individual operations or parts of a computation using
:timeout arguments to certain blocking operations, synchronous
timeouts and asynchronous timeouts. The latter two affect operations
without explicit timeout support (such as standard functions and
macros). See Timeouts and Deadlines.
- Metaobject Protocol: The sb-mop package provides an
implementation of the metaobject protocol for the Common Lisp
Object System as described in The Art of the Metaobject Protocol
by Kiczales et al.
- Extensible Sequences: SBCL allows users to define subclasses
of the sequence class. See Extensible Sequences.
- Extensible Streams: The package sb-gray provides an
implementation of Gray Streams.
The Simple Streams module is an implementation of the Simple
Streams API proposed by Franz Inc.
- CLTL2 Compatibility Layer: The sb-cltl2 module provides
sb-cltl2:compiler-let and environment access functionality
described in Common Lisp The Language, 2nd Edition which were
removed from the language during the ANSI standardization process.
- Recursive Event Loop: SBCL provides a recursive event
loop (serve-event) for doing non-blocking IO on multiple streams
without using threads.
- System Definition Tool:
[ASDF](https://www.sbcl.org/manual/asdf.html) is a flexible and
popular protocol-oriented system definition tool by Daniel Barlow.
It is bundled with SBCL. Load it with (require :asdf).
## Getting Started
### Supported Platforms
See for the list of supported
operating systems and architectures.
Some operating systems are more equal than others: most of the
development and testing is done on x86-64 Linux and x86-64/arm64 Mac
OS X.
If an underprivileged platform is important to you, you can help by
e.g. testing during the monthly freeze periods and, most
importantly, by Reporting Bugs.
### Obtaining SBCL
Your package manager may provide prepackaged binaries. On Debian, for
example, you can install a stable, though possibly older, version of
SBCL with apt install sbcl. The exact details vary depending on
your system.
#### Binary Distribution
The latest official binary distributions (tar and zip archives of
pre-compiled SBCL and its documentation) for selected platforms can
be downloaded from
-
Some older binaries are available at
-
Note that many platforms do not have recent binaries released. In
that case, get a Source Distribution or check out the
SBCL Repository, and build SBCL.
If you were lucky enough to have new enough binary distributions,
unpack the archive with
bzip2 -cd sbcl-2.6.9-x86-linux-binary.tar.bz2 | tar xvf -
replacing sbcl-2.6.9-x86-linux-binary.tar.bz2 with the name of the
tarball you downloaded. Now, you can immediately try
Running without Installation.
Then, enter the directory which was unpacked and skip ahead to
Installing SBCL to put SBCL in its proper place.
On Windows, you may want to use the MSI installer to unpack and
install in one step:
msiexec /i sbcl-2.6.9-x86-64-windows.msi
#### Source Distribution
If there is no suitable Binary Distribution for your platform,
your next choice is to download a source distribution (a tar or zip
file with the SBCL sources) from
- or
- .
See Building SBCL for the next steps.
#### SBCL Repository
If you want to be on the bleeding edge, you can check out the sources
of the latest development version (or any previous development
version, for that matter) by using anonymous GIT to SourceForge:
$ git clone git://git.code.sf.net/p/sbcl/sbcl sbcl
See for
instructions.
Alternatively, check out the official GitHub mirror at
:
$ git clone https://github.com/sbcl/sbcl.git
See Building SBCL for the next steps.
> Note: Tracking the repository is not recommended if you're just
> using SBCL as a tool for other work, but if you're interested in
> working on SBCL itself, it's a good idea.
### Building SBCL
To build SBCL, you need a Source Distribution or the SBCL Repository
checked out. In any case, the instructions are the same.
You also need a working C toolchain and a Common Lisp system
(see Build Prerequisites). You also need approximately 128 MB of
free RAM+swap.
To build SBCL using another, already installed SBCL version:
$ sh make.sh
To configure SBCL to install to a non-standard
location, you can use the --prefix option:
$ sh make.sh --prefix=/opt/mysbcl
To configure SBCL with a non-standard default dynamic-space size,
use the --dynamic-space-size option:
$ sh make.sh --dynamic-space-size=4gb
$ sh make.sh --dynamic-space-size=800mb
If mega- or gigabytes are not specified, the number is taken to be
in megabytes. The standard default is 512Mb for 32-bit systems, and
1GB for 64-bit systems (with the exception of OpenBSD where 444MB
are used to fit under default ulimits.)
If you don't already have an SBCL binary installed as sbcl on your
system, you'll need to tell make.sh what Lisp to use as the
cross-compilation host (cf. make.sh for detailed instructions on how
to cross compile). For example, to use CMUCL (assuming it has been
installed under its default name lisp) as the
cross-compilation host:
$ sh make.sh --xc-host='lisp -batch -noinit'
The build may take a long time, especially on older hardware. A
successful build ends with a message beginning: "The build seems to
have finished successfully...".
To run the regression tests:
$ cd ./tests && sh run-tests.sh
To build documentation:
$ cd ./doc/manual && make
This builds the Info, HTML and PDF documentation from the sb-manual
contrib. The manual includes documentation strings from the built
SBCL. If SBCL itself has not been built yet, but an installed one is
found, documentation strings from the installed version are used.
Now you should have the same src/runtime/sbcl and
obj/sbcl-home/sbcl.core files that come with the binary
distribution, the next thing is Installing SBCL.
#### Customizing the Build
You can tweak the build options, enabling or disabling things like
documentation strings, thread support, or extra debugging code.
The preferred way to do this is using command-line arguments to
make.sh:
--fancy Enables a curated set of features.
--with- Enables a known feature.
--without- Disables a known feature.
--with%- Enables a known or unknown feature.
--without%- Disables a known or unknown feature.
It is an error if the feature in the --with- and
--without- options is not one of Build Options. Use the
% variants to disable this check.
When tracking the SBCL Repository, it may be annoying having to
supply the same arguments to make.sh over and over again. You can
avoid this by creating a file named customize-target-features.lisp
in the base directory of the SBCL tree and putting a single lambda
expression like this in it:
(lambda (list)
(flet ((enable (x) (pushnew x list))
(disable (x) (setf list (remove x list))))
#+nil (enable (feature :sb-show))
(enable (feature :sb-after-xc-core))
#+nil (disable (feature :sb-doc))
list))
This function gets a list of features from make.sh and returns the
transformed list to be used for the build. The feature function
returns its argument after performing the same check that
--with- does.
> Note: There is no direct correspondance between Build Options
> and *features* in the compiled SBCL. Some build options do make it
> to *features*, while others are dropped, and there are features
> such as :ansi-cl and :sbcl with no corresponding build option.
#### Build Options
The following is a list is build option with the default value and
whether they are retained in cl:*features* in the built SBCL in
parentheses.
- :ansi-compliant-load-truename (on)
clhs says that *load-truename* has to be bound whenever
*load-pathname* is because obviously the spec wanted to mandate that
one system call turn into an unlimited number. At least you're
correct in saying "it's not my code, it's the OS that's slow".
Remove this feature if you want to ignore the technical requirement
that *load-truename* be a variable (as opposed to a symbol-macro).
- :aslr (off)
Allow Lisp spaces to be randomly allocated anywhere in virtual address
space, i.e. the behavior of passing mmap an address of zero.
Requires all spaces to be relocatable on start-up.
- :compact-instance-header (dynamic)
Combine the layout pointer, instance-length, and widetag of
an instance into a single machine word. This represents a space
saving of anywhere from 4% to 8% in typical applications. (Your
mileage may vary.)
Needs :immobile-space. Enabled by default on x86-64 if :immobile-space.
- :cycle-counter (off)
Enabled automatically by make-config.sh for platforms which
implement the %read-cycle-counter VOP. Can be disabled manually:
affects time.
- :immobile-code (dynamic)
Allocate most functions in the immobile space.
Needs :immobile-space. Enabled by default if :immobile-space.
The down-side of this feature is that the allocator is significantly
slower than the allocator for movable code. If a particular
application is performance-constrained by speed of creation of
compiled functions (not including closures), the feature can be
disabled.
- :immobile-space (off)
Build with support for an additional dynamic heap differing from
the main dynamic heap in two ways:
1. It is guaranteed to reside below 4GB so that all pointers into it
fit in 32 bits. (Only an issue for >32 bit address space)
2. All objects therein are immovable, and space is reclaimed by a
mark-and-sweep collector.
That combination of aspects potentially allows various efficiencies
in code generation, especially for the x86-64 backend. The extra
space has a fixed size which can only be changed by a rebuild, and
out-of-space conditions are not easily preventable, so the space is
sized rather generously to sidestep the issue. Additionally, it is
assumed that for all objects in the immobile heap, speed of
allocation of those objects is relatively unimportant. If unexpected
performance regressions are observed, consider disabling this
feature and reporting a bug.
- :largefile (off)
Some platforms don't use a 32-bit off_t by default, and thus can't
handle files larger than 2GB. This feature will control whether
we'll try to use platform-specific compilation options to enable a
64-bit off_t. The intent is for this feature to be automatically
enabled by make-config.sh on platforms where it's needed and known
to work, you shouldn't be enabling it manually. You might however
want to disable it, if you need to pass file descriptors to foreign
code that uses a 32-bit off_t.
- :relocatable-static-space (off)
Allow static space to be relocatable on start-up.
- :sb-after-xc-core (off)
This isn't really a target Lisp feature at all but controls
whether the build process produces an after-xc.core file. This can
be useful for shortening the edit/compile/debug cycle when you
modify SBCL's own source code, as in slam.sh. Otherwise you don't
need it.
- :sb-core-compression (off, in *features*)
Support zstd-based compressed core files. Enable this feature to
compile it in. Obviously, doing so adds a dependency on zstd.
- :sb-cover-for-internals (off)
Build the SBCL system itself with code coverage data marks (and
sequences in the compiled code to set those marks). Inevitably,
this makes the system as a whole slower, but allows coverage of
tests to be measured.
- :sb-doc (on)
Retain documentation strings found in the system sources in the
target SBCL executable. Traditional Common Lisp folk will want this
option set.
- :sb-dyncount (off)
Enable code for collecting statistics on usage of various
operations, useful for performance tuning of the SBCL system itself.
This code is probably pretty stale (having not been tested since the
fork from base CMUCL) but might nonetheless be a useful starting
point for anyone who wants to collect such statistics in the future.
- :sb-eval (on)
Support for a full evaluator that can execute all the CL special
forms, as opposed to the traditional SBCL evaluator, which called
compile for everything complicated. See Interpreter.
- :sb-fasteval (off)
Support for a different evaluator (interpreter) with improved
performance. You can have only one of :sb-eval and :sb-fasteval. See
Interpreter.
- :sb-futex (dynamic)
Use futexes as our locking primitive for lower-overhead
synchronization. Available on Linux, FreeBSD, OpenBSD, Darwin ARM64,
and Windows under various names.
- :sb-ldb (on, in *features*)
Enable the LDB, the low-level debugger. In the ideal world you
would not need this unless you are messing with SBCL at a very low
level (e.g. trying to diagnose GC problems, or trying to debug
assembly code for a port to a new CPU). However, experience shows
that sooner or later everyone lose()s, in which case sb-ldb can
at least provide an informative backtrace.
- :sb-package-locks (on, in *features*)
Enable detection of unportable code (when applied to the
common-lisp package or SBCL-internal packages) or bad-neighbourly
code (when applied to user-level packages), relating to material
alteration to packages or to bindings in symbols in packages. See
Package Locks.
- :sb-safepoint (dynamic, in *features*)
On certain thread-enabled platforms, synchronization between
threads for the purpose of stopping and starting the world around GC
can be performed using safepoints instead of signals. Enable this
feature to compile with safepoints and to use them for GC. This is
always enabled on :win32. Not enabled elsewhere by default.
- :sb-show (off)
Make more debugging information available (for debugging SBCL
itself). If you aren't hacking or troubleshooting SBCL itself, you
probably don't want this set.
At least two varieties of debugging information are enabled by this
option:
- SBCL is compiled with a higher level of optimize debug, so that
the debugger can tell more about the state of the system.
- Various code to print debugging messages, and similar debugging
code, is compiled only when this feature is present.
Note that the extra information recorded by the compiler at this
higher level of optimize debug includes the source location forms.
In order for the debugger to use this information, it has to re-read
the source file. In an ordinary installation of SBCL, this
re-reading may not work very well, for either of two reasons:
- The sources aren't present on the system in the same location that
they were on the system where SBCL was compiled.
- SBCL is using the standard readtable, without the added hackage
which allows it to handle things like target features.
If you want to be able to use the extra debugging information,
therefore, be sure to keep the sources around, and run with the
readtable configured so that the system sources can be read.
- :sb-show-assem (off)
Enable extra debugging output in the assem.lisp assembler /
scheduler code.
- :sb-simd-pack (off)
Enabled automatically by make-config.sh for platforms which
implement short vector SIMD intrinsics.
- :sb-source-locations (on)
Record source location information for variables, classes,
conditions, packages, etc. Gives much better information on
M-. in Slime but increases core size by about 100kB.
- :sb-thread (dynamic, in *features*)
Enable low-level thread primitives support. See Threading
for the list of supported platforms.
Threads are on by default on
- x86 / x86-64 Linux, Darwin, and Windows,
- ARM64, RISC-V, and LoongArch64.
In fact, threads are mandatory on Windows.
- :sb-unicode (on, in *features*)
Support for the entirety of the 21-bit character space defined by
the Unicode consortium, rather than the classical 8-bit ISO-8859-1
character set. See Unicode Support.
- :sb-xref-for-internals (off)
Record xref data for SBCL internals. This can be rather useful for
people who want to develop on SBCL itself because it will make
M-? (slime-edit-uses) work, which lists call/expansion/etc.
sites. It will increase the core size by major 5-6MB, though.
#### Troubleshooting the Build
- "GNU Make not found"
If the GNU make command is not available under the names make,
gmake, or gnumake, then define the environment variable
GNUMAKE to a name where it can be found.
- Segfaults on Linux with ASLR
If SBCL segfaults immediately upon startup due to Address Space
Layout Randomization (ASLR), you can bypass it by executing the
host compiler binary via setarch:
setarch x86_64 -R sbcl
See also :aslr in Build Options.
- Build crashes mysteriously, machine becomes unstable, etc
You may be running out of memory. Try increasing swap, or
building SBCL with fewer other programs running simultaneously.
- Other
- Check that the host lisp you're building with is known to work
as an SBCL build host, and that your operating system is
supported.
- Try to do a build without loading any initialization files for
the cross-compilation host (for example
sh make.sh 'sbcl --userinit /dev/null --sysinit /dev/null').
- Some GCC versions are known to have bugs that affect SBCL
compilation: if the error you're encountering seems related to
files under src/runtime, down- or upgrading GCC may help.
- Ask for help on the mailing lists referenced in
Volunteer Support.
#### Build Prerequisites
All of the following platforms are supported in the sense of
"should work", but some things like loading foreign object files
may lag behind on less-used operating systems.
Supported toolchains:
- GNU toolchain
- Sun toolchain with GCC
SBCL can be compiled from source code using (as the host compiler)
another ANSI-compliant Common Lisp implementation such as
- SBCL
- CMUCL
- CCL (formerly known as OpenMCL)
- CLISP (only some versions: 2.44.1 is OK, 2.47 is not)
- ECL
- XCL
- ABCL (recent versions only, very slow)
Often, it is most convenient to install an SBCL with your system's
package manager to use as the host.
Note that not every release is tested with every possible host
compiler. You're most likely to get a clean build with SBCL itself
as host, otherwise CCL on a PPC and CMUCL elsewhere.
### Installing SBCL
The installation instructions are the same whether you are have
downloaded a Binary Distribution or built SBCL
yourself.
The following command installs SBCL and related documentation under
the /usr/local directory (typically run as root):
# INSTALL_ROOT=/usr/local sh install.sh
You can also install SBCL as a user, under your home directory:
$ INSTALL_ROOT=/home/me sh install.sh
That is, install.sh installs SBCL under the directory named by the
environment variable INSTALL_ROOT.
If INSTALL_ROOT is not specified, SBCL is installed into
location configured when Building SBCL with the --prefix argument
of make.sh: for official binary distributions, this is the
/usr/local directory.
The standard installation procedure, outlined above, is to run
install.sh, which copies all the files to right places, including
documentation and contrib modules that have passed their tests. If
you need to install by hand, see install.sh for details.
Documentation consists of a man page, the SBCL Manual (in info, pdf
and html formats), and a few additional text files.
## Starting and Stopping
### Starting SBCL
If SBCL is installed properly and it is in your path, you can simply
type sbcl at the command line. You should end up in the toplevel
REPL (read-eval-print loop), where you can interact with SBCL by
typing expressions.
$ sbcl
This is SBCL 0.8.13.60, an implementation of ANSI Common Lisp.
More information about SBCL is available at .
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (+ 2 2)
4
* (exit)
$
See also Command-line Options and Stopping SBCL.
#### Running without Installation
You can quickly run SBCL without installing it by invoking the
run-sbcl.sh script. This works both with an unpacked
Binary Distribution and after Building SBCL yourself:
$ sh run-sbcl.sh
#### Running from Emacs
To run SBCL as an inferior-lisp from Emacs, add something like this
to your .emacs:
;;; The SBCL binary and command-line arguments
(setq inferior-lisp-program "/usr/local/bin/sbcl --noinform")
For more information on using SBCL with Emacs, see
Editor Integration.
#### Shebang Scripts
Standard Unix tools that are interpreters follow a common command-line
protocol that is necessary to work with "shebang scripts". SBCL
supports this via the --script command-line option (see
Command-line Options).
Example file (hello.lisp):
#!/usr/local/bin/sbcl --script
(write-line "Hello, World!")
Usage from the command line:
$ ./hello.lisp
Hello, World!
Note that SBCL skips the shebang line when it reads the file:
$ sbcl --script hello.lisp
Hello, World!
#### Parts of SBCL
If you only ever use SBCL packaged for your operating system,
run it from an installation created with install.sh, run it with run-sbcl.sh, there is no need to worry about the
files necessary at run-time. If you, for example, want to install
SBCL manually, package it in a way that deviates from the file
hierarchy created by install.sh, or run SBCL with your own core
file saved by sb-ext:save-lisp-and-die, then read on.
The following files play a part in running SBCL.
- The sbcl binary
This is a standard executable built by compiling and linking an
ordinary C program. It provides the runtime environment for the
running Lisp image, but it doesn't know much about high-level
Lisp stuff (like symbols and printing and objects), so it's
pretty useless by itself.
The binary is src/runtime/sbcl in Binary Distributions and
Source Distributions; and it is installed
to /usr/local/bin/sbcl by default.
- The sbcl.core file
This is an image dump written in a
special SBCL format that only SBCL understands, and it contains
all the high-level Lisp stuff.
The core file is obj/sbcl-home/sbcl.core in distributions;
installed to /usr/local/lib/sbcl/sbcl.core by default. In
addition, there are a number of Contributed Modules that extend
the basic SBCL functionality.
- The contrib/ directory
This holds the compiled fasl files for the Contributed Modules,
to be loaded on demand.
The contrib fasl files are in obj/sbcl-home/contrib/ in
distributions; installed to /usr/local/lib/sbcl/contrib/ by
default.
> Note: Only the binary and the core file are absolutely necessary
> to start SBCL; the contrib fasls are optional.
#### Finding Parts of SBCL
When you invoke the SBCL binary, it needs to be able to find the other
Parts of SBCL, namely the sbcl.core file and the
Contributed Modules in the contrib/ directory.
- Finding sbcl.core
If the --core runtime option is specified,
then its value is used. Example:
$ sbcl --core /foo/bar/sbcl.core
Else, the runtime looks for sbcl.core in the following
directories until the first match.
- The directory denoted by the SBCL_HOME environment
variable if it is set
- The ../lib/sbcl/ directory relative to the sbcl binary
- The directory of the sbcl binary
- The current directory
If no core file was found by the above rules, then the runtime
exits with an error message.
- Finding contrib/
Once the runtime loads the core file, the Lisp looks for
contrib/ in the following directories until the first match.
- The directory denoted by the SBCL_HOME environment
variable if it is set
- The directory of sbcl.core
- The directory ../lib/sbcl relative to sbcl.core
- The directory ../lib/sbcl relative to the sbcl binary
- The directory of the sbcl binary
- The current directory
The list of directories is the same as for finding the core file
except here we also try directories relative to sbcl.core.
If the contrib/ directory is not found, then no error is
signalled immediately, but loading modules will fail.
### Stopping SBCL
#### Exit
SBCL can be stopped at any time by calling sb-ext:exit,
optionally returning a specified numeric value to the calling
process. See Threading for information about terminating individual
threads.
#### End of File
By default, SBCL also exits upon reaching the end of input. This can
be caused either by the user pressing Control-D on an attached
terminal, or by the input stream ending when SBCL is used as part of
a shell pipeline.
#### Exit on Errors
SBCL can also be configured to exit if an unhandled error occurs,
which is mainly useful for acting as part of a shell pipeline; doing
so under most other circumstances would mean giving up large parts
of the flexibility and robustness of Common Lisp. See
Debugger Entry and the command-line option --disable-debugger in
Toplevel Options.
### Command-line Options
Command-line options can be considered an advanced topic; for ordinary
interactive use, no command-line arguments should be necessary.
In order to understand the command-line argument syntax for SBCL, it
is helpful to understand that the SBCL system is implemented as two
components, a low-level runtime environment written in C and a
higher-level system written in Common Lisp. Arguments are processed
during the respective initializations of the runtime and Lisp
system, with any remainder available to user code via
sb-ext:*posix-argv*.
The full, unambiguous syntax for invoking SBCL at the command line
is:
sbcl * --end-runtime-options \
* --end-toplevel-options \
*
The --end-runtime-options and --end-toplevel-options can be
omitted, provided that no ambiguities are possible with the option
values used. Omitting these elements is probably a bad idea for any
batch file where any of the options are under user control because
it makes it impossible for SBCL to detect erroneous command-line
arguments, which will then be passed on to the user program even if
they were intended for the runtime system or the Lisp system.
#### Runtime Options
- --core
Run the specified Lisp core file instead of the default. Note
that if the Lisp core file is a user-created core file, it may
run a nonstandard toplevel that does not recognize the standard
toplevel options.
- --dynamic-space-size
Size of the dynamic space reserved on startup. The default value
is platform-dependent. The units supported are kB (or KiB),
MB (or MiB), GB (or GiB), and TB (or TiB). The names are
compared case-insensitively, and the default unit is megabytes.
Thus, 8, 8mb, and 8mib all mean 8 * 2^20 bytes.
- --control-stack-size
Size of control stack reserved for each thread. The
argument has the same format as in --dynamic-space-size. The
default is 2MB.
- --tls-limit
Maximum number of thread-local special variables (see
Special Variables in Threads) in threaded builds. Default value
is 4096.
- --noinform
Suppress the printing of any banner or other informational
message at startup. This makes it easier to write Lisp programs
which work cleanly in Unix pipelines. See also the --noprint
and --disable-debugger options.
- --disable-ldb
Disable the LDB, the low-level debugger. Only effective if SBCL
is compiled with LDB. When LDB is not available or is
disabled, SBCL exits with a non-zero exit code whenever it would
enter LDB.
- --lose-on-corruption
There are some dangerous low-level errors (for instance, control
stack exhausted, memory fault) that (or whose handlers) can
corrupt the image. By default, SBCL prints a warning, then tries
to continue and handle the error in Lisp. However, this will not
always work, and SBCL may subsequently malfunction or even hang.
With this option, upon encountering such an error, SBCL will
instead attempt to enter LDB (and exit if LDB is not
available). See also Default Signal Handlers and
Foreign Threads.
- --script
As a runtime option, this is equivalent to --noinform
--disable-ldb --lose-on-corruption
--end-runtime-options --script . See
the description of --script as a toplevel option below.
If there are no other command-line arguments following
--script, the filename argument can be omitted.
- --merge-core-pages
When platform support is present, provide hints to the operating
system that identical pages may be shared between processes
until they are written to. This can be useful to reduce the
memory usage on systems with multiple SBCL processes started
from similar but differently-named core files, or from
compressed cores. Without platform support, do nothing. By
default only compressed cores trigger hinting.
- --no-merge-core-pages
Ensures that no sharing hint is provided to the operating
system.
- --help
Print some basic information about SBCL, then exit.
- --version
Print SBCL's version information, then exit.
- --end-runtime-options
End processing of runtime options and pass the rest of the
command-line arguments to the toplevel function.
In the future, runtime options may be added to control behavior
such as lazy allocation of memory.
#### Toplevel Options
The following options are supported by the Default Toplevel. If the
toplevel function was overriden with sb-ext:save-lisp-and-die, the
set of available toplevel options is likely very different.
- --sysinit
Load instead of the default system initialization
file (see Initialization Files).
- --no-sysinit
Don't load a system-wide initialization file. If this option is
given, the --sysinit option is ignored.
- --userinit
Load instead of the default user initialization
file (see Initialization Files.)
- --no-userinit
Don't load a user initialization file. If this option is given,
the --userinit option is ignored.
- --eval
After executing any initialization file, but before starting the
read-eval-print loop on standard input, read and evaluate
. More than one --eval option can be used, and all
will be read and executed, in the order they appear on the
command line.
- --load
This is equivalent to --eval '(load "")'. The
special syntax is intended to reduce quoting headaches when
invoking SBCL from shell scripts.
- --noprint
When ordinarily the toplevel "read-eval-print loop" would be
executed, execute a "read-eval loop" instead, i.e. don't print
a prompt and don't echo results. Combined with the --noinform
runtime option, this makes it easier to write Lisp scripts that
work cleanly in Unix pipelines.
- --disable-debugger
By default, when SBCL encounters an error, it enters the builtin
debugger, allowing interactive diagnosis and possible
intercession. This option disables the debugger, causing errors
to print a backtrace and exit with status 1 instead. When given,
this option takes effect before loading initialization files or
processing --eval and --load options. See
sb-ext:disable-debugger and Debugger Entry.
- --script
Implies --no-userinit --no-sysinit --disable-debugger
--end-toplevel-options.
Causes the system to load the specified file instead of entering
the read-eval-print-loop, and exit afterwards. If the file
begins with a shebang line, it is ignored.
If there are no other command-line arguments following, the
filename can be omitted: this causes the script to be loaded
from standard input instead. In this case, shebang lines are
currently not ignored.
In either case, if there is an unhandled error (such as an end
of file condition or a broken pipe) on standard input, standard
output, or standard error, the script silently exits with code
0. This allows piping output from SBCL to another command
without unexpected errors.
Additionally, the option sets *compile-verbose* and
*load-verbose* to nil while loading the file to avoid
potentially verbose diagnostic messages printed on the standard
output.
- --end-toplevel-options
End processing of toplevel options, leaving the rest of the
command-line arguments in sb-ext:*posix-argv*.
### Initialization Files
The Default Toplevel supports customization via the system and user
initialization files. These files with read and eval, not load;
hence initialization files can be used to set startup *package* and
*readtable*, and for proclaiming a global optimization policy.
- System Initialization File: Defaults to sbclrc in the
directory where contrib/ is found (see Finding Parts of SBCL),
or if that doesn't exist to /etc/sbclrc. Can be overridden with
the command-line option --sysinit or --no-sysinit (see
Toplevel Options). Set sb-ext:*sysinit-pathname-function* to
override the above defaulting behavior.
The system initialization file is intended for system
administrators and software packagers to configure locations of
installed third party modules, etc.
- User Initialization File: Defaults to $HOME/.sbclrc. Can be
overridden with the command-line option --userinit or
--no-userinit (see Toplevel Options). Set
sb-ext:*userinit-pathname-function* to override the above
defaulting behavior.
The user initialization file is intended for personal
customizations, such as loading certain modules at startup,
defining convenience functions to use in the REPL, handling
automatic recompilation of fasls (see Fasl Format), etc.
Neither initialization file is required.
- [variable] sb-ext:*sysinit-pathname-function* nil
Controls the sysinit file defaulting of the
Default Toplevel. This is nil or a designator for a
function of zero arguments.
- If nil, the default behavior described in
Initialization Files is in effect.
- If a function, it is called by the default toplevel to obtain a
pathname designator for the default sysinit file or nil. If the
function returns nil, no sysinit file is used unless one has been
specified on the command line.
- [variable] sb-ext:*userinit-pathname-function* nil
Controls the userinit file defaulting of the
Default Toplevel. This is nil or a designator for a
function of zero arguments.
- If nil, the default behavior described in
Initialization Files is in effect.
- If a function, it is called by the default toplevel to obtain a
pathname designator for the default userinit file or nil. If the
function returns nil, no sysinit file is used unless one has been
specified on the command line.
### Initialization and Exit Hooks
SBCL provides hooks into the system initialization and exit.
- [variable] sb-ext:*init-hooks* nil
A list of function designators called in an unspecified
order when a saved core image starts up, after the system itself has
been initialized, but before non-user threads such as the finalizer
thread have been started.
Unused by SBCL itself; reserved for the user, contribs and applications.
- [variable] sb-ext:*exit-hooks* nil
A list of function designators called in an unspecified
order when SBCL process exits.
Unused by SBCL itself; reserved for the user, contribs and applications.
Using (sb-ext:exit :abort t), or calling exit(3) directly circumvents
these hooks.
### Core Images
#### Saving a Core Image
SBCL has the ability to save its state as a file for later
execution. This functionality is important for its bootstrapping
process and is also provided as an extension to the user.
- [function] sb-ext:save-lisp-and-die core-file-name &key toplevel executable save-runtime-options callable-exports (purify t) root-structures (environment-name "auxiliary") compression
Save a "core image", i.e. enough information to restart a Lisp
process later in the same state, in the file of the specified name.
Only global state is preserved: the stack is unwound in the process.
The following &key arguments are defined:
- :toplevel
The function to run when the created core file is resumed. The
default function handles command line toplevel option
processing (see Toplevel Options) and runs the top
level read-eval-print loop. This function returning is equivalent
to (sb-ext:exit :code 0) being called.
toplevel functions should always provide an abort restart:
otherwise code they call will run without one.
- :executable
If true, arrange to combine the SBCL runtime and the core image to
create a standalone executable. If false (the default), the core
image will not be executable on its own. Executable images always
behave as if they were passed the --noinform runtime option.
If :executable is :elf-object, then the resulting core will be
wrapped in a .o which requires further linking. (EXPERIMENTAL)
- :save-runtime-options
If true, values of Runtime Options
--dynamic-space-size and --control-stack-size that were used
to start SBCL are stored in the standalone executable, and
restored when the executable is run. This also inhibits normal
runtime option processing, causing all command line arguments to
be passed to the toplevel. If
:accept-runtime-options, then --dynamic-space-size and
--control-stack-size are still processed by the runtime.
Meaningless if :executable is nil.
- :callable-exports
This should be a list of symbols to be initialized to the
appropriate alien callables on startup. All exported symbols
should be present as global symbols in the symbol table of the
runtime before the saved core is loaded. When this list is
non-empty, the :toplevel argument cannot be supplied.
- :purify
If true (the default), then some objects in the restarted core
will be memory-mapped as read-only. Among those objects are
numeric vectors that were determined to be compile-time constants,
and any immutable values according to the language specification
such as symbol names.
- :root-structures
This should be a list of the main entry points in any newly loaded
systems. This need not be supplied, but locality and/or gc
performance may be better if they are. This has two different but
related meanings: If :purify is true -- and only for CheneyGC --
the root structures are those which anchor the set of objects
moved into static space. On GENCGC -- and only on platforms
supporting immobile code -- these are the functions and/or
function-names which commence a depth-first scan of code when
reordering based on the statically observable call chain. The
complete set of reachable objects is not affected per se. This
argument is meaningless if neither enabling precondition holds.
- :environment-name
This has no purpose; it is accepted only for legacy compatibility.
- :compression
This is only meaningful if the runtime was built with the
:sb-core-compression feature enabled. If nil (the default),
saves to uncompressed core files. If :sb-core-compression was
enabled at build-time, the argument may also be an integer from -7
to 22, corresponding to zstd compression levels, or t (which is
equivalent to the default compression level, 9).
- :application-type
Present only on Windows and meaningful only with :executable t.
Specifies the subsystem of the executable, :console or :gui.
The notable difference is that :gui doesn't automatically create
a console window. The default is :console.
The save/load process changes the values of some global variables:
- *standard-output*, *debug-io*, etc
Everything related to open streams is necessarily changed, since
the OS won't let us preserve a stream across save and load.
- *default-pathname-defaults*
This is reinitialized to reflect the working directory where the
saved core is loaded.
save-lisp-and-die interacts with sb-alien:load-shared-object: see its
documentation for details.
On threaded platforms, only a single thread may remain running after
sb-ext:*save-hooks* have run. Applications using multiple threads can
be save-lisp-and-die friendly by registering a save-hook that quits
any additional threads, and an init-hook that restarts them.
This implementation is not as polished and painless as you might like:
- It corrupts the current Lisp image enough that the current process
needs to be killed afterwards. This can be worked around by forking
another process that saves the core.
- There is absolutely no binary compatibility of core images between
different runtime support programs. Even runtimes built from the
same sources at different times are treated as incompatible for this
purpose.
This isn't because we like it this way, but just because there don't
seem to be good quick fixes for either limitation and no one has been
sufficiently motivated to do lengthy fixes.
- [variable] sb-ext:*save-hooks* nil
A list of function designators called in an unspecified
order before creating a saved core image.
Unused by SBCL itself; reserved for the user and applications.
To facilitate distribution of SBCL applications using external
resources, the filesystem location of the SBCL core file being used
is available from Lisp.
- [variable] sb-ext:*core-pathname* ""
The absolute pathname of the running SBCL core.
#### Default Toplevel
SBCL's default toplevel function processes Toplevel Options,
runs Initialization Files, and provides a REPL.
The toplevel function of Core Images can be specified with the
:toplevel argument of sb-ext:save-lisp-and-die.
## Compiler
This chapter discusses most compiler issues other than Efficiency,
including compiler messages, type safety in the presence of type
declarations, the effects of various optimization policies, and the
way that inlining and open coding may cause optimized code to differ
from a naive translation.
### Calling the Compiler
- [function] compile name &optional (definition (or (and (symbolp name) (macro-function name)) (fdefinition name)))
Produce a compiled function from definition.
- If definition is a lambda-expression, it is coerced to a function.
- If definition is an interpreted function, it is compiled.
- If definition is already a compiled function, it is returned
as-is. (Future versions of SBCL might try to recompile the existing
definition, but this is not currently supported.)
If name is nil, the compiled function is returned as the primary
value. Otherwise, the resulting compiled function replaces existing
function definition of name, and name is returned as primary value; if
name is a symbol that names a macro, its macro-function is replaced
and name is returned as primary value.
Also returns a secondary value which is true if any conditions of type
warning occur during the compilation, and nil otherwise.
Tertiary value is true if any conditions of type error or warning that
are not style-warnings occur during compilation, and nil otherwise.
Also, see the CLHS.
- [function] compile-file input-file &key (output-file "") (verbose *compile-verbose*) (print *compile-print*) (external-format :default) (progress *compile-progress*) trace-file (block-compile *block-compile-default*) entry-points (emit-cfasl *emit-cfasl*)
Compile input-file, producing a corresponding fasl file and
returning its filename.
- :output-file
The name of the fasl to output. The returned pathname of the
output file may differ from the pathname of the :output-file
parameter, e.g. when the latter is a designator for a directory.
- :verbose
If true, information indicating what file is being compiled is
printed to *standard-output*.
- :print
If true, each top level form in the file is printed to *standard-output*.
- :external-format
The external format to use when opening the source file. The
default is :default which uses the
sb-ext:*default-source-external-format*.
The rest of the arguments are extensions to the standard:
- :block-compile {nil | :specified | t}
Determines whether multiple functions are compiled together as a
unit, resolving function references at compile time. nil means
that global function names are never resolved at compilation time.
:specified means that names are resolved at compile-time when
convenient (as in a self-recursive call), but the compiler doesn't
combine top-level defuns. With :specified, an explicit start-block
declaration will enable block compilation. A value of t indicates
that all forms in the file(s) should be compiled as a unit. The
default is the value of sb-ext:*block-compile-default*, which is
initially nil. See Block Compilation.
- :entry-points
This specifies a list of function names for functions in the
file(s) that must be given global definitions. This only applies
to block compilation and is useful mainly when :block-compile t is
specified on a file that lacks start-block declarations. If the
value is nil (the default), then all functions will be globally
defined. See Block Compilation.
- :trace-file
If given, internal data structures are dumped to the specified
file, or if a value of t is given, to a file of .trace type
derived from the input file name. See Trace Files.
- :emit-cfasl
(Experimental). If true, outputs the toplevel compile-time effects
of this file into a separate .cfasl file.
Also, see the CLHS.
- [variable] sb-ext:*block-compile-default* nil
The default value for the :block-compile argument to compile-file.
- [macro] with-compilation-unit options &body body
Affects compilations that take place within its dynamic extent. It is
intended to be e.g. wrapped around the compilation of all files in the
same system.
Following options are defined:
- :override
One of the effects of this form is to delay undefined warnings
until the end of the form, instead of giving them at the end of
each compilation. If override is nil (the default), then the
outermost with-compilation-unit form grabs the undefined warnings.
Specifying :override true causes that form to grab any enclosed
warnings, even if it is enclosed by another with-compilation-unit.
- :policy
Provides dynamic scoping for global compiler optimization
qualities and restrictions, limiting effects of subsequent
optimize proclamations and calls to
sb-ext:restrict-compiler-policy to the dynamic scope of body.
If :override is false, the specified :policy is merged with
current global policy. If :override is true, the current global
policy, including any restrictions, is discarded in favor of the
specified :policy.
Supplying :policy nil is equivalent to the option not being
supplied at all, i.e. dynamic scoping of policy does not take
place. If dynamic scoping without changing the current policy is
desired, use :policy '(optimize) with :override nil.
This option is an SBCL-specific experimental extension: Interface
subject to change.
- :source-namestring
Attaches the value returned by to the internal
debug-source information as the namestring of the source file.
Normally the namestring of the input-file for compile-file is
used: this option can be used to provide source-file information
for functions compiled using compile, or to override the
input-file argument of compile-file.
Can be accessed using sb-introspect:definition-source-pathname.
If both an outer and an inner with-compilation-unit provide a
:source-namestring, the inner one takes precedence. Unaffected by
:override.
This is an SBCL-specific extension.
- :source-plist
Attaches the value returned by to internal
debug-source information of functions compiled in within the
dynamic extent of body.
Primarily for use by development environments, in order to e.g.
associate function definitions with editor-buffers. Can be
accessed using sb-introspect:definition-source-plist.
If an outer with-compilation-unit form also provide a
source-plist, it is appended to the end of the provided
source-plist. Unaffected by :override.
This is an SBCL-specific extension.
Examples:
;; Prevent proclamations from the file leaking, and restrict
;; SAFETY to 3 -- otherwise uses the current global policy.
(with-compilation-unit (:policy '(optimize))
(restrict-compiler-policy 'safety 3)
(load "foo.lisp"))
;; Using default policy instead of the current global one,
;; except for DEBUG 3.
(with-compilation-unit (:policy '(optimize debug)
:override t)
(load "foo.lisp"))
;; Same as if :POLICY had not been specified at all: SAFETY 3
;; proclamation leaks out from WITH-COMPILATION-UNIT.
(with-compilation-unit (:policy nil)
(declaim (optimize safety))
(load "foo.lisp"))
Also, see the CLHS.
### Diagnostic Messages
#### Diagnostic Severity
There are four levels of compiler diagnostic severity:
- error
- warning
- style warning
- note
The first three levels correspond to condition classes which are
defined in the ANSI standard for Common Lisp and which have special
significance to the compile and compile-file functions. These levels
of compiler error severity occur when the compiler handles
conditions of these classes.
The fourth level of compiler error severity, note, corresponds to
the sb-ext:compiler-note condition and is used for problems too mild
for the standard condition classes, typically hints about how
efficiency might be improved. sb-ext:code-deletion-note, a subtype
of sb-ext:compiler-note, is signalled when the compiler deletes
user-supplied code after proving that the code in question is
unreachable.
Future work for SBCL includes expanding this hierarchy of types to
allow more fine-grained control over emission of diagnostic
messages.
- [condition] sb-ext:compiler-note
Root of the hierarchy of conditions representing information discovered
by the compiler that the user might wish to know, but which does not merit
a style-warning (or any more serious condition).
- [condition] sb-ext:code-deletion-note simple-compiler-note
A condition type signalled when the compiler deletes code that the user
has written, having proved that it is unreachable.
#### Understanding Compiler Diagnostics
The messages emitted by the compiler contain a lot of detail in a
terse format, which may be confusing at first. The messages will be
illustrated using this example program:
(defmacro zoq (x)
`(roq (ploq (+ ,x 3))))
(defun froq (y)
(declare (symbol y))
(zoq y))
The main problem with this program is that it is trying to add 3
to a symbol. Note also that the functions roq and ploq aren't
defined anywhere.
##### Parts of a Compiler Diagnostic
When processing the above program, the compiler will first output this
warning:
; file: /tmp/froq.lisp
; in: DEFUN FROQ
; (ZOQ Y)
; --> ROQ PLOQ
; ==>
; (+ Y 3)
;
; caught WARNING:
; Derived type of Y is
; (VALUES SYMBOL &OPTIONAL),
; conflicting with its asserted type
; NUMBER.
; See also:
; The SBCL Manual, Node "Handling of Types"
In this example we see each of the six possible parts of a compiler
diagnostic:
- file: /tmp/froq.lisp is the name of the file that the compiler
read the relevant code from. The file name is displayed because it
may not be immediately obvious when there is an error during
compilation of a large system, especially when
with-compilation-unit is used to delay undefined warnings.
- in: DEFUN FROQ is the definition top level form responsible for
the diagnostic. It is obtained by taking the first two elements of
the enclosing form whose first element is a symbol beginning with
def. If there is no such enclosing def form, then the
outermost form is used. If there are multiple def forms, then
they are all printed from the outside in, separated by =>s. In
this example, the problem was in the defun for froq.
- (zoq y) is the original source form responsible for the
diagnostic. Original source means that the form directly appeared
in the original input to the compiler, i.e. in the lambda passed
to compile or in the top level form read from the source file. In
this example, the expansion of the zoq macro was responsible for
the message.
- --> roq ploq This is the processing path that the compiler
used to produce the code that caused the message to be emitted.
The processing path is a representation of the evaluated forms
enclosing the actual source that the compiler encountered when
processing the original source. The path is the first element of
each form, or the form itself if the form is not a list. These
forms result from the expansion of macros or source-to-source
transformation done by the compiler. In this example, the
enclosing evaluated forms are the calls to roq and ploq. These
calls resulted from the expansion of the zoq macro.
- ==> (+ y 3) is the actual source responsible for the
diagnostic. If the actual source appears in the explanation, then
we print the next enclosing evaluated form, instead of printing
the actual source twice. (This is the form that would otherwise
have been the last form of the processing path.) In this example,
the problem is with the evaluation of the reference to the
variable y.
- The warning about the derived type symbol conflicting with the
asserted type number is the explanation of the problem. In this
example, the problem is that, while the call to + requires that
its arguments are all of type number, the compiler has derived
that Y will evaluate to a symbol. Note that
(values symbol &optional) expresses that y evaluates to
precisely one value.
Note that each part of the message is distinctively marked:
- file: and in: mark the file and definition, respectively.
- The original source is an indented form with no prefix.
- Each line of the processing path is prefixed with -->.
- The actual source form is indented like the original source, but
is marked by a preceding ==> line.
- The explanation is prefixed with the diagnostic severity, which
can be caught ERROR:, caught WARNING:, caught
STYLE-WARNING:, or note:.
After the type warning, the compiler prints the two undefined
function warnings. Each part of the message is more specific than
the preceding one. If consecutive messages are for nearby locations,
then the front part of the messages would be the same. In this case,
the compiler omits as much of the second message as is in common
with the first. For example:
; in: DEFUN FROQ
; (ZOQ Y)
; --> ROQ
; ==>
; (PLOQ (+ Y 3))
;
; caught STYLE-WARNING:
; undefined function: COMMON-LISP-USER::PLOQ
; ==>
; (ROQ (PLOQ (+ Y 3)))
;
; caught STYLE-WARNING:
; undefined function: COMMON-LISP-USER::ROQ
In this example, the file, definition and original source are
identical for the two messages, so the compiler omits them in the
second message. If consecutive messages are entirely identical, then
the compiler prints only the first message, followed by: [Last
message occurs times] where is the number of
times the message was given.
If the source was not from a file, then no file line is printed. If
the actual source is the same as the original source, then the
processing path and actual source will be omitted. If no forms
intervene between the original source and the actual source, then
the processing path will also be omitted.
##### Original and Actual Source
The original source displayed will almost always be a list. If
the actual source for a message is a symbol, the original source
will be the immediately enclosing evaluated list form. So even if
the offending symbol does appear in the original source, the
compiler will print the enclosing list and then print the symbol as
the actual source (as though the symbol were introduced by a macro.)
When the actual source is displayed (and is not a symbol), it will
always be code that resulted from the expansion of a macro or a
source-to-source compiler optimization. This is code that did not
appear in the original source program; it was introduced by the
compiler.
Keep in mind that when the compiler displays a source form in an
diagnostic message, it always displays the most specific (innermost)
responsible form. For example, compiling this function
(defun bar (x)
(let (a)
(declare (fixnum a))
(setq a x)
a))
gives this error message
; in: DEFUN BAR
; (LET (A)
; (DECLARE (FIXNUM A))
; (SETQ A X)
; A)
;
; note: deleting unreachable code
;
; caught WARNING:
; Constant NIL conflicts with its asserted type FIXNUM.
This message is not saying that there is a problem somewhere in this
let -- it is saying that there is a problem with the let itself. In
this example, the problem is that a's nil initial value is not a
fixnum.
##### Processing Paths
The processing path is mainly useful for debugging macros, so if you
don't write macros, you can probably ignore it. Consider this example:
(defun frox (n)
(dotimes (i n *undefined*)))
Compiling results in this error message:
; in: DEFUN FROX
; (DOTIMES (I N *UNDEFINED*))
; --> DO BLOCK LET TAGBODY RETURN-FROM
; ==>
; (PROGN *UNDEFINED*)
;
; caught WARNING:
; undefined variable: COMMON-LISP-USER::*UNDEFINED*
Note that do appears in the processing path. This is because
dotimes expands into:
(do ((i 0 (1+ i)) (#:g1 n))
((>= i #:g1) *undefined*)
(declare (type unsigned-byte i)))
The rest of the processing path results from the macroexpansion of
do:
(block nil
(let ((i 0) (#:g1 n))
(declare (type unsigned-byte i))
(tagbody (go #:g3)
#:g2 (psetq i (1+ i))
#:g3 (unless (>= i #:g1) (go #:g2))
(return-from nil (progn *undefined*)))))
In this example, the compiler descended into the block, let, tagbody
and return-from to reach the progn printed as the actual source.
This is a place where the "actual source appears in explanation"
rule was applied. The innermost actual source form was the symbol
*undefined* itself, but that also appeared in the explanation, so
the compiler backed out one level.
#### Controlling Verbosity
The compiler can be quite verbose in its diagnostic reporting -- rather
more than some users would prefer. However, the amount of noise
emitted can be controlled.
To control emission of compiler diagnostics (except those with
Diagnostic Severity error) use the sb-ext:muffle-conditions and
sb-ext:unmuffle-conditions declarations, specifying the type of
condition that is to be muffled (the muffling is done using an
associated muffle-warning restart).
Global control:
;;; Muffle compiler-notes globally
(declaim (sb-ext:muffle-conditions sb-ext:compiler-note))
Local control:
;;; Muffle compiler-notes based on lexical scope
(defun foo (x)
(declare (optimize speed) (fixnum x)
(sb-ext:muffle-conditions sb-ext:compiler-note))
(values (* x 5) ; no compiler note from this
(locally
(declare (sb-ext:unmuffle-conditions sb-ext:compiler-note))
;; this one gives a compiler note
(* x -5))))
- [declaration] sb-ext:muffle-conditions
Syntax: (sb-ext:muffle-conditions &rest types).
Silence the diagnostic messages that would be printed when a condition
matching any of types is signalled at compile time.
- [declaration] sb-ext:unmuffle-conditions
Syntax: (sb-ext:unmuffle-conditions &rest types).
Cancel the effect of a previous sb-ext:muffle-conditions declaration.
For information about muffling warnings signaled outside of the
compiler, see Customization Hooks for Users.
The following variables and macros control how the compiler
messages are printed.
- [variable] sb-ext:*compiler-print-variable-alist* nil
An association list describing new bindings for special variables
to be used by the compiler for error-reporting, etc.
E.g. ((*print-length* . 10) (*print-level* . 6) (*print-pretty* .
nil)).
The variables in the car positions are bound to the values in the cdr
during the execution of some debug commands. When evaluating arbitrary
expressions in the debugger, the normal values of the printer control
variables are in effect.
Initially empty, *compiler-print-variable-alist* is typically used
to specify bindings for printer control variables.
- [variable] sb-ext:*enclosing-source-cutoff* 1
The maximum number of enclosing actual source forms (i.e. from
macroexpansion) that we print in full. For additional enclosing forms, we
print only the car.
- [variable] sb-ext:*undefined-warning-limit* 3
If non-null, then an upper limit on the number of unknown function or type
warnings that the compiler will print for any given name in a single
compilation. This prevents excessive amounts of output when the real
problem is a missing definition (as opposed to a typo in the use.)
- [variable] sb-ext:*efficiency-note-limit* 2
This is the maximum number of possible optimization alternatives will be
mentioned in a particular efficiency note. nil means no limit.
- [variable] sb-ext:*efficiency-note-cost-threshold* 5
This is the minimum cost difference between the chosen implementation and
the next alternative that justifies an efficiency note.
- [variable] sb-ext:*compile-progress* nil
When this is true, the compiler prints to *standard-output* progress
information about the phases of compilation of each function. (This
is useful mainly in large block-compilations.)
- [macro] sb-ext:define-source-context name lambda-list &body body
Define how to abbreviate a source context form whose car is
name when it appears in the compiler input. lambda-list is a
defmacro style lambda-list used to parse the form.
body should return a list of subforms that fit on one line when
printed with the "~{~S ~}" format string. There are predefined
extractors for defstruct and function forms. If there is no
definition, then the first two subforms are returned.
### Handling of Types
The most important features of the SBCL compiler (similar
to the original CMUCL compiler) are its fairly sophisticated
understanding of the Common Lisp type system and its conservative
approach to the implementation of type declarations.
These two features reward the use of type declarations throughout
development, even when high performance is not a concern. Also, as
discussed in the chapter on performance (see Efficiency), the use
of appropriate type declarations can be very important for
performance as well.
The SBCL compiler also has a greater knowledge of the Common Lisp
type system than other compilers. Support is incomplete only for
types involving the satisfies type specifier.
#### Type Declaration Checking
The compiler treats type declarations differently from most other
Lisp compilers. Under the default Compiler Policy, the compiler
doesn't blindly believe type declarations but considers them
assertions about the program that should be checked: all type
declarations that have not been proven to always hold are asserted
at runtime. This behavior allows Type Inference to trust declared
types and from them derive the types of other expressions, opening
up lots of optimization possibilities.
There are three type checking policies available in SBCL, selectable
via optimize declarations.
- Safe code (>= safety 1)
Full type checks. All declarations are considered assertions to
be checked at compile or run time, and all type checks are
precise. The default compilation policy provides full type
checks.
> Warning: The callee's ftype declaration is trusted when
> compiling the caller unless the debug (!) optimization
> quality is 3. Thus, if an ftype is placed after the function
> definition, the function won't perform any type checks and the
> caller's trust in the type checking will be misplaced and
> render the caller unsafe. Adding or changing a ftype
> declaration necessitates recompiling the function definition
> and all its callers. See also Global Function Type Inference.
- Unsafe code (= safety 0)
No type checks. All declarations are believed without
assertions. Also disables argument count and array bounds
checking. Any type errors in code where type checks are not
performed are liable to corrupt the heap.
> Note: There is a third option of mostly historical interest
> called Weak Type Checking, where declared types may be simplified
> into faster to check supertypes: for example, (or (integer -17
> -7) (integer 7 17)) is simplified into (integer -17 17). This
> option is also unsafe and is no longer available by any
> combination of the standard optimization qualities.
> Note: CLOS slots with types declared using the :type slot option
> in defclass are asserted if and only if the class was defined in
> safe code and the slot access location is in safe code as
> well. This laxness does not pose any safety issues, as the CLOS
> slot types are not available for Type Inference, nor do CLOS slot
> types provide any efficiency benefits.
> Note: The sb-ext:truly-the special form declares the type of the
> result of the operations, producing its argument; the declaration
> is not checked. In short: don't use it.
#### Precise Type Checking
Precise checking means that the check is done as though typep
had been called with the exact type specifier that appeared in the
declaration.
If a variable is declared to be (integer 3 17), then its value
must always be an integer between 3 and 17. If multiple type
declarations apply to a single variable, then all the declarations
must be correct; it is as though all the types were intersected
producing a single and type specifier.
To gain maximum benefit from the compiler's type checking, you
should always declare the types of function arguments and structure
slots as precisely as possible. This often involves the use of or,
member, and other list-style type specifiers.
#### Getting Existing Programs to Run
Since SBCL's compiler does much more comprehensive type checking than
most Lisp compilers, SBCL may detect type errors in programs that have
been debugged using other compilers. These errors are mostly incorrect
declarations, although compile-time type errors can find actual bugs
if parts of the program have never been tested.
Some incorrect declarations can only be detected by run-time type
checking. It is very important to initially compile a program with
full type checks (high safety optimization) and then test this safe
version. After the checking version has been tested, then you can
consider weakening or eliminating type checks. This applies even to
previously debugged programs because the SBCL compiler does much
more type inference than other Common Lisp compilers, so an
incorrect declaration can do more damage.
The most common problem is with variables whose constant initial
value doesn't match the type declaration. Incorrect constant initial
values will always be flagged by a compile-time type error, and they
are simple to fix once located. Consider this code fragment:
(prog (foo)
(declare (fixnum foo))
(setq foo ...)
...)
Here foo is given an initial value of nil but is declared to be a
fixnum. Even if it is never read, the initial value of a variable
must match the declared type. There are two ways to fix this
problem. Change the declaration
(prog (foo)
(declare (type (or fixnum null) foo))
(setq foo ...)
...)
or change the initial value
(prog ((foo 0))
(declare (fixnum foo))
(setq foo ...)
...)
It is generally preferable to change to a legal initial value rather
than to weaken the declaration, but sometimes it is simpler to
weaken the declaration than to try to make an initial value of the
appropriate type.
Another declaration problem occasionally encountered is incorrect
declarations on defmacro arguments. This can happen when a function
is converted into a macro. Consider this macro:
(defmacro my-1+ (x)
(declare (fixnum x))
`(the fixnum (1+ ,x)))
Although legal and well-defined Common Lisp code, the meaning of
this definition is almost certainly not what the writer intended.
For example, this call is illegal:
(my-1+ (+ 4 5))
This call is illegal because the argument to the macro is (+ 4 5),
which is a list, not a fixnum. Because of macro semantics, it is
hardly ever useful to declare the types of macro arguments. If you
really want to assert something about the type of the result of
evaluating a macro argument, then put a the in the expansion:
(defmacro my-1+ (x)
`(the fixnum (1+ (the fixnum ,x))))
In this case, it would be stylistically preferable to change this
macro back to a function and declare it inline. See
Open Coding and Inline Expansion.
Some more subtle problems are caused by incorrect declarations that
can't be detected at compile time. Consider this code:
(do ((pos 0 (position #a string :start (1+ pos))))
((null pos))
(declare (fixnum pos))
...)
Although pos is almost always a fixnum, it is nil at the end of
the loop. If this example is compiled with full type checks (the
default), then running it will signal a type error at the end of the
loop. If compiled without type checks, the program will go into an
infinite loop (or perhaps position will complain because (1+ nil)
isn't a sensible start.) Why? Because if you compile without type
checks, the compiler just quietly believes the type declaration.
Since the compiler believes that pos is always a fixnum, it
believes that pos is never nil, so (null pos) is never true, and
the loop exit test is optimized away. Such errors are sometimes
flagged by unreachable code notes, but it is still important to
initially compile and test any system with full type checks, even if
the system works fine when compiled using other compilers.
In this case, the fix is to weaken the type declaration to (or
fixnum null). (Actually, this declaration is unnecessary in SBCL,
since it already knows that position returns a non-negative fixnum
or nil.)
Note that there is usually little performance penalty for weakening
a declaration in this way. Any numeric operations in the body can
still assume that the variable is a fixnum since nil is not a legal
numeric argument. Another possible fix would be to say:
(do ((pos 0 (position #a string :start (1+ pos))))
((null pos))
(let ((pos pos))
(declare (fixnum pos))
...))
This would be preferable in some circumstances since it would allow
a non-standard representation to be used for the local pos
variable in the loop body. See also Non-descriptor.
### Compiler Policy
The compiler policy is what tells the compiler how to
compile a program. This is logically (and often textually) distinct
from the program itself. Broad control of policy is provided by the
optimize declaration; other declarations and variables control more
specific aspects of compilation.
The optimize declaration recognizes six different qualities. The
qualities are conceptually independent aspects of program
performance. In reality, increasing one quality tends to have
adverse effects on other qualities. The compiler compares the
relative values of qualities when it needs to make a trade-off; i.e.
if speed is greater than safety, then improve speed at the cost of
safety.
All qualities take values of type (integer 0 3). The default for
all qualities is 1. Whenever qualities are equal, ties are broken
according to a broad idea of what a good default environment is
supposed to be. Generally this downplays speed, compilation-speed
and space in favor of safety and debug. Novice and casual users
should stick to the default policy. Advanced users often want to
improve speed and memory usage at the cost of safety and
debuggability.
If the value for a quality is 0 or 3, then it may have a special
interpretation. A value of 0 means totally unimportant, and a 3
means ultimately important. These extreme optimization values enable
"heroic" compilation strategies that are not always desirable and
sometimes self-defeating. Specifying more than one quality as 3 is
not desirable, since it doesn't tell the compiler which quality is
most important.
These are the optimization qualities:
- speed: How fast the program should run. speed 3 enables some
optimizations that may hurt debuggability. Ordinarily, when the
speed quality is high, the compiler emits notes to notify the
programmer about its inability to apply various optimizations. For
selective muffling of these notes, see Controlling Verbosity.
- compilation-speed: How fast the compiler should run. If this is
high, then some expensive optimizations may be disabled.
- space: How much space the compiled code should take up. A high
value makes inline functions semi-inlined, and 0 enables
semi-inlining of sb-ext:maybe-inline functions (see
Semi-inline Expansion).
- debug: How debuggable the program should be. The quality is
treated differently from the other qualities: each value indicates
a particular level of debugger information; it is not compared
with the other qualities. See Debug Information for the details.
- safety: How much error checking should be done. If speed, space
or compilation-speed is more important than safety, then
Type Declaration Checking is weakened. safety 0 also
suppresses argument count checking, unbound-symbol checking, array
bounds checks, and checking of tag existence in return-from and
go.
- sb-ext:inhibit-warnings: This is a deprecated extension that
determines how little (or how much) diagnostic output should be
printed during compilation. This quality is compared to other
qualities to determine whether to print style notes and warnings
concerning those qualities. If speed is greater than
inhibit-warnings, then notes about how to improve speed will be
printed, etc. The default value is 1, so raising the value for
any standard quality above its default enables notes for that
quality. If it is 3, then all notes and most non-serious
warnings are inhibited. This is useful with declare to suppress
warnings about unavoidable problems.
See also the :policy argument of with-compilation-unit.
In the following, we discuss extensions related to compiler policies.
- [function] sb-ext:describe-compiler-policy &optional spec
Print all global optimization settings, augmented by spec.
- [function] sb-ext:restrict-compiler-policy &optional quality (min 0) (max 3)
Restrict the range of values the optimization quality can take.
The effect is that optimize declarations with quality are clamped to
the restricted range. quality must be a valid optimization quality or
nil. min is the minimum allowed value, and max is the maximum; both of
type (integer 0 3).
Returns two alists describing the current minimum and maximum policy
restrictions on all optimization qualities.
If quality is nil or not given, nothing is done. Use this to query the
current restrictions.
If quality is non-nil, min is 0 and max is 3, any existing
restrictions on quality are removed. In general, restrictions can be
loosened.
See also :policy option in with-compilation-unit, which can impose
dynamic scoping on restrictions.
### Compiler Errors
#### Type Errors at Compile Time
If the compiler can prove at compile time that some portion of the
program cannot be executed without a type error, then it will give a
style-warning at compile time. This sort of type warning happens
moderately often in the expansion of complex macros and in inline
functions.
For example, consider this code fragment:
(defun raz (foo)
(let ((x (if foo 13 "str")))
(declare (fixnum x))
(print x)))
Compilation produces this warning:
; in: DEFUN RAZ
; (LET ((X (IF FOO 13 "str")))
; (DECLARE (FIXNUM X))
; (PRINT X))
;
; caught STYLE-WARNING:
; Constant "str" conflicts with its asserted type FIXNUM.
The warning means that if foo is nil, then x will be initialized
to "str", which the fixnum declaration makes illegal.
This warning doesn't always indicate an incorrect program because
- it is possible that the offending code would never actually be
executed at run-time due to some higher level consistency constraint
unknown to the compiler; and
- in rare cases, the type error is actually intended and part of the
normal control flow.
> Note: In the common situation where the value triggering the
> type error is nil, this warning is suppressed.
#### Errors During Macroexpansion
The compiler handles errors that happen during macroexpansion, turning
them into compiler errors. If you want to debug the error (to debug
a macro), you can set *break-on-signals* to error. For example, this
definition:
(defun foo (e l)
(do ((current l (cdr current))
((atom current) nil))
(when (eq (car current) e) (return current))))
gives this error:
; in: DEFUN FOO
; (DO ((CURRENT L (CDR CURRENT))
; ((ATOM CURRENT) NIL))
; (WHEN (EQ (CAR CURRENT) E) (RETURN CURRENT)))
;
; caught ERROR:
; (in macroexpansion of (DO # #))
; (hint: For more precise location, try *BREAK-ON-SIGNALS*.)
; DO step variable is not a symbol: (ATOM CURRENT)
#### Read Errors
SBCL's compiler does not attempt to recover from read errors when
reading a source file but instead just reports the offending
character position and gives up on the entire source file.
### Open Coding and Inline Expansion
Since Common Lisp forbids the redefinition of standard functions, the
compiler can have special knowledge of these standard functions
embedded in it. This special knowledge is used in various ways (open
coding, Inline Expansion, Source Optimization), but the
implications to the user are basically the same:
- Attempts to redefine standard functions may be frustrated since
the function may never be called. Although it is technically
illegal to redefine standard functions, users sometimes want to
implicitly redefine these functions when they are debugging using
the trace macro. Special-casing of standard functions can be
inhibited using the notinline declaration, but even then some
phases of analysis such as type inferencing are applied by the
compiler.
- The compiler can have multiple alternate implementations of
standard functions that implement different trade-offs of speed,
space and safety. This selection is based on the Compiler Policy.
When a function call is open coded, inline code whose effect is
equivalent to the function call is substituted for that function
call. When a function call is closed coded, it is usually left as
is, although it might be turned into a call to a different function
with different arguments. As an example, if nthcdr were to be open
coded, then
(nthcdr 4 foobar)
might turn into
(cdr (cdr (cdr (cdr foobar))))
or even
(do ((i 0 (1+ i))
(list foobar (cdr foobar)))
((= i 4) list))
If nth is closed coded, then
(nth x l)
might stay the same, or turn into something like
(car (nthcdr x l))
In general, open coding sacrifices space for speed, but some functions
(such as car) are so simple that they are always open-coded. Even
when not open-coded, a call to a standard function may be
transformed into a different function call (as in the last example)
or compiled as static call. Static function calls use a more
efficient calling convention that forbids redefinition.
### Interpreter
By default, SBCL implements eval by calling the native-code
compiler. There are two, mutually exclusive interpreter
implementations: sb-eval (the default) and sb-fasteval. These are
intended for when using the compiler is undesirable, for example due
to compilation overhead.
An interpreterless SBCL can be compiled by passing
--without-sb-eval to make.sh, while sb-fasteval can be enabled
with --without-sb-eval --with-sb-fasteval (see
Customizing the Build).
Unlike in some other Lisp implementations, in SBCL, interpreted code
is not safer or more debuggable than compiled code.
- [variable] sb-ext:*evaluator-mode* :compile
Toggle between different evaluator implementations. If set to :compile,
an implementation of eval that calls the compiler will be used. If set
to :interpret, an interpreter will be used. :interpret is a valid
value only if SBCL has been compiled with either the sb-eval or the
sb-fasteval feature.
## Debugging
This chapter documents the debugging facilities of SBCL, including
the debugger, single-stepper and trace, and the effect of (optimize
debug) declarations.
### Debugger
#### Debugger Entry
##### Debugger Banner
When you enter the debugger, it looks something like this:
* (symbol-value 'x)
debugger invoked on a UNBOUND-VARIABLE @B80027A0C1 in thread
#:
The variable X is unbound.
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [CONTINUE ] Retry using X.
1: [USE-VALUE ] Use specified value.
2: [STORE-VALUE] Set specified value and use it.
3: [ABORT ] Exit debugger, returning to top level.
(SYMBOL-VALUE X)
0]
The first group of lines describe what the error was that put us in
the debugger. This is followed by the "beginner help line", which
appears only if sb-debug:*debug-beginner-help-p* is true (default).
Next comes a listing of the active restart names, along with their
descriptions -- the ways we can restart execution after this error.
Restarts can be selected by entering the corresponding number or
name. If the name coincides with the name of a debugger command or
that of another restart, use its number.
The current frame appears right underneath the restarts, immediately
followed by the debugger prompt, where 0 is the index of the
current frame.
- [variable] sb-debug:*debug-beginner-help-p* t
Should entering the debugger print a beginner-oriented help message?
##### Debugger Invocation
The debugger is invoked when
- error is called and the condition it signals is not handled, or
- break is called, or
- signal is called with a condition that matches the current
*break-on-signals*, or
- invoke-debugger is called.
Unless the debugger is to be entered by break, ANSI mandates that
the value of *debugger-hook*, if non-nil, be called with two
arguments: the condition that caused the debugger to be invoked and
the previous value of *debugger-hook*. When this happens,
*debugger-hook* is bound to nil to prevent recursive errors.
However, ANSI also mandates that *debugger-hook* not be invoked when
the debugger is to be entered by the break function. For users who
wish to provide an alternate debugger interface (and thus catch
break entries into the debugger), SBCL provides
sb-ext:*invoke-debugger-hook*, which is invoked during any entry
into the debugger.
- [variable] sb-ext:*invoke-debugger-hook* nil
This is either nil or a designator for a function of two arguments,
to be run when the debugger is about to be entered. The function is
run with *invoke-debugger-hook* bound to nil to minimize
recursive errors, and receives as arguments the condition that
triggered debugger entry and the previous value of
*invoke-debugger-hook*.
This mechanism is an SBCL extension similar to the standard *debugger-hook*.
In contrast to *debugger-hook*, it is observed by invoke-debugger even when
called by break.
#### Debugger Command Loop
The debugger is an interactive read-eval-print loop much like the
normal top level, but some symbols are interpreted as debugger
commands instead of being evaluated. A debugger command starts with
the symbol name of the command, possibly followed by some arguments
on the same line. Some commands prompt for additional input.
Debugger commands can be abbreviated by any unambiguous prefix:
help can be typed as h, he, etc.
The package is not significant in debugger commands; any symbol with
the name of a debugger command will work. If you want to show the
value of a variable that happens also to be the name of a debugger
command you can wrap the variable in a progn to hide it from
the command loop.
The debugger prompt is ], where is the number of
the current frame. Frames are numbered starting from zero at the
top (most recent call), increasing down to the bottom. The current
frame is the frame that commands refer to.
The debugger can be invoked again within a debugger session
following the normal rules (see Debugger Invocation). In such
nested debugger sessions, the prompt is [].
It is possible to override the normal printing behavior in the
debugger by using the sb-ext:*debug-print-variable-alist*.
- [variable] sb-ext:*debug-print-variable-alist* nil
An association list describing new bindings for special variables
to be used within the debugger. For example,
((*print-length* . 10) (*print-level* . 6) (*print-pretty* . nil))
The variables in the car positions are bound to the values in the cdr
during the execution of some debug commands. When the same variable
has multiple bindings specified, the earliest one takes precendence.
Entering the debugger establishes these bindings, as does the
backtrace debugger command (see Information Commands)
among other things.
Initially empty, *debug-print-variable-alist* is typically used to
provide bindings for printer control variables.
#### Stack Frames
A stack frame is the run-time representation of a call to a
function; the frame stores the state that a function needs to
remember what it is doing. Frames have:
- Variables (see Variable Access), which are the values being
operated on.
- Arguments to the call (which are really just particularly
interesting variables).
- A current source location (Source Location Printing), which is
the place in the program where the function was running when it
stopped to call another function, or because of an interrupt or
error.
##### Stack Motion
These commands move to a new stack frame and print the name of the
function and the values of its arguments in the style of a Lisp
function call:
- up
Move up to the next higher frame. More recent function calls are
considered to be higher on the stack.
- down
Move down to the next lower frame.
- bottom
Move to the lowest frame.
- frame []
Move to the frame with the specified number. Prompts for the
number if not supplied. The frame with number 0 is the frame
where the debugger was entered.
##### How Arguments are Printed
A frame is printed to look like a function call but with the actual
argument values in the argument positions. So the frame for this call
in the source:
(myfun (+ 3 4) 'a)
would look like this:
(MYFUN 7 A)
All keyword and optional arguments are displayed with their actual
values; if the corresponding argument was not supplied, the value will
be the default. So this call:
(subseq "foo" 1)
would look like this:
(SUBSEQ "foo" 1 3)
And this call:
(string-upcase "test case")
would look like this:
(STRING-UPCASE "test case" :START 0 :END NIL)
The arguments to a function call are displayed by accessing the
argument variables. Although those variables are initialized to the
actual argument values, they can be set inside the function; in this
case the new value will be displayed.
&rest arguments are handled somewhat differently. The value of the
rest argument variable is displayed as the spread-out arguments to
the call, so:
(format t "~A is a ~A." "This" 'test)
would look like this:
(FORMAT T "~A is a ~A." "This" 'TEST)
Rest arguments cause an exception to the normal display of keyword
arguments in functions that have both &rest and &key arguments. In
this case, the keyword argument variables are not displayed at all;
the rest arg is displayed instead. So for these functions, only the
keywords actually supplied will be shown, and the values displayed
will be the argument values, not values of the
(possibly modified) variables.
If the variable for an argument is never referenced by the function,
it will be deleted. The variable value is then unavailable, so the
debugger prints # instead of the value. Similarly, if
for any of a number of reasons the value of the variable is
unavailable or not known to be available (Variable Access), then
# will be printed instead of the argument value.
Note that Open Coding and Inline Expansion affect what frames are
present in the debugger, see Debug Information.
##### Function Names
If a function is defined by defun it will appear in backtrace
by that name. Functions defined by labels and flet will appear as
(flet ) and (labels ) respectively. Anonymous
lambdas will appear as (lambda ).
##### Entry Point Details
Sometimes the compiler introduces new functions that are used to
implement a user function but are not directly specified in the
source. This is mostly done for argument type and count checking.
With recursive or block compiled functions, an additional external
frame may appear before the frame representing the first call to the
recursive function or entry to the compiled block. This is a
consequence of the way the compiler works: there is nothing odd with
your program. You may also see cleanup frames during the execution
of unwind-protect cleanup code, and optional for variable argument
entry points.
##### Debugging Tail Calls
Tail Call Optimization can eliminate frames. Consider this backtrace:
(BAR ...)
(FOO ...)
Because of tail calls, it is not necessarily the case that foo
directly called bar. It may be that foo called some other
function foo2, which then tail-called bar, as in this example:
(defun foo ()
...
(foo2 ...)
...)
(defun foo2 (...)
...
(bar ...))
(defun bar (...)
...)
If there is any doubt about how one function called another, it can
usually be eliminated by finding the source location in the calling
frame. See Source Location Printing.
##### Unknown Locations and Interrupts
The debugger operates using special debugging information attached to
the compiled code. This debug information tells the debugger what it
needs to know about the locations in the code where the debugger can
be invoked. If the debugger somehow encounters a location not
described in the debug information, then it is said to be unknown.
If the code location for a frame is unknown, then some variables may
be inaccessible, and the source location cannot be precisely
displayed.
There are three reasons why a code location could be unknown:
- There is inadequate Debug Information due to the value of the
debug optimization quality.
- The debugger was entered because of an interrupt such as C-c.
- A hardware error such as a bus error occurred in
code that was compiled unsafely due to the value of the safety
optimization quality. See Compiler Policy.
In the last two cases, the values of argument variables are
accessible, but may be incorrect. For more details on when variable
values are accessible, see Variable Value Availability.
It is possible for an interrupt to happen when a function call or
return is in progress. The debugger may then flame out with some
obscure error or insist that the bottom of the stack has been
reached, when the real problem is that the current stack frame can't
be located. If this happens, return from the interrupt and try
again.
#### Variable Access
There are two ways to access the current frame's local variables in
the debugger: list-locals and sb-debug:var.
The debugger doesn't really understand lexical scoping; it has just
one namespace for all the variables in the current stack frame. If a
symbol is the name of multiple variables in the same function, then
the reference appears ambiguous, even though lexical scoping
specifies which value is visible at any given source location. If
the scopes of the two variables are not nested, then the debugger
can resolve the ambiguity by observing that only one variable is
accessible.
When there are ambiguous variables, the evaluator assigns each one a
small integer identifier. The sb-debug:var function uses this
identifier to distinguish between ambiguous variables. The
list-locals command prints the identifier. In the following
example, there are two variables named x. The first one has
identifier 0 (which is not printed), the second one has identifier
1.
X = 1
X#1 = 2
- list-locals []
This command prints the name and value of all variables in the
current frame whose name has the specified , which may
be a string or a symbol. If no is given, then all
available variables are printed. If a variable has a potentially
ambiguous name, then the name is printed with a #
suffix, where is the small integer used to make
the name unique.
- [function] sb-debug:var name &optional (id 0)
Return a variable's value if possible. name is a simple-string or symbol.
If it is a simple-string, it is an initial substring of the
variable's name. If name is a symbol, it has the same name and
package as the variable whose value this function returns. If the
symbol is uninterned, then the variable has the same name as the
symbol, but it has no package.
If name is the initial substring of variables with different names,
then this returns no values after displaying the ambiguous names.
If name determines multiple variables with the same name, then you
must use the optional id argument to specify which one you want. If
you left id unspecified, then this returns no values after
displaying the distinguishing id values.
The result of this function is limited to the availability of
variable information. This is setfable.
##### Variable Value Availability
The value of a variable may be unavailable to the debugger in portions
of the program where Lisp says that the variable is defined. If a
variable value is not available, the debugger will not let you read
or write that variable. With one exception, the debugger will never
display an incorrect value for a variable. Rather than displaying
incorrect values, the debugger tells you the value is unavailable.
The one exception is this: if you interrupt (e.g. with C-c) or if
there is an unexpected hardware error such as a bus error (which
should only happen in unsafe code; see Type Declaration Checking),
then the values displayed for arguments to the interrupted frame
might be incorrect. This exception applies only to the interrupted
frame: any frame farther down the stack will be fine.
> Note: Since the location of an interrupt or hardware error will
> always be an unknown location, non-argument variable values will
> never be available in the interrupted frame. See
> Unknown Locations and Interrupts.)
If the necessary Debug Information was not recorded, the value of a
variable is unavailable. This can happen for the following reasons:
- The value of the debug optimization quality may have omitted
debug information needed to determine whether the variable is
available. Unless a variable is an argument, its value will only
be available when debug is at least 2.
- The compiler did lifetime analysis and determined that the value
was no longer needed, even though its scope had not been exited.
Lifetime analysis is inhibited when the debug optimization
quality is 3.
- The variable's name is an uninterned symbol (gensym). To save
space, the compiler only dumps debug information about uninterned
variables when the debug optimization quality is 3.
The value of a variables may be unavailable also for other reasons:
- The frame's location is unknown (see
Unknown Locations and Interrupts) because the debugger was
entered due to an interrupt or unexpected hardware error. Under
these conditions the values of arguments will be available, but
might be incorrect. This is the exception mentioned above.
- The variable (or the code referencing it) was optimized out of
existence. Variables with no reads are always optimized away. The
degree to which the compiler deletes variables will depend on the
value of the compilation-speed optimization quality, but most
source-level optimizations are done under all compilation
policies.
- The variable is never set and its definition looks like
(let ((var1 var2))
...)
In this case, var1 is substituted with var2.
- The variable is never set and is referenced exactly once. In this
case, the reference is substituted with the variable initial
value.
To summarize, since it is especially useful to be able to get the
arguments to a function, values of argument variables are
available (even at unknown locations) when the speed optimization
quality is less than 3 and the debug quality is at least 1. For
non-argument variables, debug must be at least 2 for values to be
available, and even then, values are only available at known
locations.
##### Note On Lexical Variable Access
When the debugger command loop establishes variable bindings for
available variables, these variable bindings have lexical scope and
dynamic extent. You can close over them, but such closures can't be
used as upward function arguments.
> Note: The variable bindings are actually created using the Lisp
> symbol-macrolet special form.
You can also set local variables using setq, but if the variable was
closed over in the original source and never set, then setting the
variable in the debugger may not change the value in all the
functions the variable is defined in. Another risk of setting
variables is that you may assign a value of a type that the compiler
proved the variable could never take on. This may result in bad
things happening.
#### Source Location Printing
One of the debugger's capabilities is source-level debugging of
compiled code.
- source []
This command displays the file that the current frame's function
was defined from (if it was defined from a file), and then the
source form responsible for generating the code that the current
frame was executing. If is specified, then it is an
integer specifying the number of enclosing levels of list
structure to print.
The source form for a location in the code is the innermost list
present in the original source that encloses the form responsible
for generating that code. If the actual source form is not a list,
then some enclosing list will be printed. For example, if the source
form was a reference to the variable *some-random-special*, then
the innermost enclosing evaluated form will be printed. Here are
some possible enclosing forms:
(let ((a *some-random-special*))
...)
(+ *some-random-special* ...)
If the code at a location was generated from the expansion of a
macro or a source-level compiler optimization, then the form in the
original source that expanded into that code will be printed.
Suppose the file /usr/me/mystuff.lisp looked like this:
(defmacro mymac ()
'(myfun))
(defun foo ()
(mymac)
...)
If foo has called myfun, and is waiting for it to return, then
the source command would print:
; File: /usr/me/mystuff.lisp
(MYMAC)
Note that the macro use was printed, not the actual function call form,
(myfun).
If enclosing source is printed by giving an argument to source or
vsource, then the actual source form is marked by wrapping it in a
list whose first element is #:***here***. In the previous example,
source 1 would print:
; File: /usr/me/mystuff.lisp
(DEFUN FOO ()
(#:***HERE***
(MYMAC))
...)
##### How the Source is Found
If the code was defined from Lisp by compile or eval, then the source
can always be reliably located. If the code was defined from a fasl
file created by compile-file, then the debugger gets the source
forms it prints by reading them from the original source file. This
is a potential problem, since the source file might have moved or
changed since the time it was compiled.
The source file is opened using the truename of the source file
pathname originally given to the compiler. This is an absolute
pathname with all logical names and symbolic links expanded. If the
file can't be located using this name, then the debugger gives up
and signals an error.
If the source file can be found, but has been modified since the time it was
compiled, the debugger prints this warning:
; File has been modified since compilation:
;
; Using form offset instead of character position.
where is the name of the source file. It then proceeds
using a robust but not foolproof heuristic for locating the source.
This heuristic works if:
- No top-level forms before the top-level form containing the source
have been added or deleted, and
- the top-level form containing the source has not been modified
much. (More precisely, none of the list forms beginning before the
source form have been added or deleted.)
If the heuristic doesn't work, the displayed source will be wrong,
but will probably be near the actual source. If the "shape" of the
top-level form in the source file is too different from the original
form, then an error will be signaled. When the heuristic is used,
the source location commands are noticeably slowed.
Source location printing can also be confused if (after the source
was compiled) a read-macro you used in the code was redefined to
expand into something different, or if a read-macro ever returns the
same eq list twice. If you don't define read macros and don't use
## in perverted ways, you don't need to worry about this.
##### Source Location Availability
Source location information is only available when the debug
optimization quality is at least 2. If source location information
is unavailable, the source commands will give an error message.
If source location information is available, but the source location
is unknown because of an interrupt or unexpected hardware error
(see Unknown Locations and Interrupts), then the command will
print
Unknown location: using block start.
and then proceed to print the source location for the start of the
basic block enclosing the code location. It's a bit complicated to
explain exactly what a basic block is, but here are some properties
of the block start location:
- The block start location may be the same as the true location.
- The block start location will never be later in the program's flow
of control than the true location.
- No conditional control structures (such as if, cond, or) will
intervene between the block start and the true location (but note
that some conditionals present in the original source could be
optimized away.) Function calls do not end basic blocks.
- The head of a loop will be the start of a block.
- The programming language concept of block structure and the Lisp
block special form are totally unrelated to the compiler's basic
block.
In other words, the true location lies between the printed location
and the next conditional (but watch out because the compiler may
have changed the program on you.)
#### Debug Information
The Compiler Policy specified by optimize declarations
affects the behavior seen in the debugger. The debug quality
directly affects the debugger by controlling the amount of debugger
information dumped. Other optimization qualities have indirect but
observable effects due to changes in the way compilation is done.
Unlike the other optimization qualities (which are compared in
relative value to evaluate tradeoffs), the debug optimization
quality is directly translated to a level of debug information. This
absolute interpretation allows the user to count on a particular
amount of debug information being available, even when the values of
the other qualities are changed during compilation. We list what
debug information is available at different levels of the debug
quality:
- 0<=: Only the function name and enough information to allow the
stack to be parsed.
- 1<=: Argument variables. The value will only be available if the
argument variable is never set and speed is not 3.
Also, argument documentation (printed argument lists) and
derived argument/result type information. This makes describe
more informative and allows the compiler to do compile-time
argument count and type checking for any calls compiled at
run-time.
- 2<=: Interned local variables, source location information, and
lifetime information that tells the debugger when arguments are
available (even when speed is 3 or the argument is set).
- 3: Uninterned variables.
- In addition, lifetime analysis is disabled (even when speed
is 3), ensuring that all variable values are available at any
known location within the scope of the binding. This has a
speed penalty in addition to the obvious space penalty.
- Tail Call Optimization is disabled. Thus, backtraces will
contain frames for all invoked functions, even those in tail
positions.
- Inlining of local functions is inhibited so that they may be
traced.
- Type Declaration Checking does not trust ftype declarations.
- > (max speed space): If debug is greater than both speed and
space, the command return can be used to continue execution by
returning a value from the current stack frame.
- > (max speed space compilation-speed): If debug is greater than
all of speed, space and compilation-speed the code will be
steppable (see Single Stepping).
As you can see, if the speed quality is 3, debugger performance is
degraded. This effect comes from the elimination of argument
variable special-casing (see Variable Value Availability). Some
degree of speed/debuggability tradeoff is unavoidable, but the
effect is not too drastic when debug is at least 2.
In addition to inline and notinline declarations, the relative
values of the speed and space qualities also change whether
functions are inline expanded. If a function is inline expanded,
then there will be no frame to represent the call, and the arguments
will be treated like any other local variable. Functions may also be
semi inline (see Semi-inline Expansion), in which case there is a
frame to represent the call, but the call is to an optimized local
version of the function, not to the original function. See
Open Coding and Inline Expansion for more.
#### Exiting the Debugger
These commands get you out of the debugger.
- toplevel
Throw to top level.
- restart [] or
Invoke the th restart case as displayed by the error
command. If is not specified, the available restart cases
are reported. When using the short form (), an integer for
which there is no corresponding restart is evaluated following
normal REPL semantics.
- continue
Call continue with the condition given that invoked the
debugger. If there is no restart case named continue, then an
error is signaled. This is not a debugger command but the name
of a commonly available restart.
- abort
Call abort on the condition that invoked the debugger. This is
useful for popping debug command loop levels or aborting to top
level, as the case may be. This is not a debugger command but
the name of a commonly available restart.
- return
Return value from the current stack frame. This command is
available when the debug optimization quality is greater than
both speed and space. Care must be taken that the value is of
the same type as SBCL expects the stack frame to return.
- restart-frame
Restart execution of the current stack frame. This command is
available when the debug optimization quality is greater than
both speed and space and when the frame is for a global
function. If the function is redefined in the debugger before
the frame is restarted, the new function will be used.
#### Information Commands
Most of these commands print information about the current frame or
function, but a few show general information.
- help or ?
Display a synopsis of debugger commands.
- describe
Call describe on the current function and display the number of
local variables.
- print
Display the current function call as it would be displayed by
moving to this frame.
- error
Print the condition given to invoke-debugger and the active
proceed cases.
- backtrace []
Display all the frames from the current to the bottom. Only
shows frames if specified. The printing is controlled by
sb-debug:*debug-print-variable-alist*.
#### Breakpoint Commands
SBCL supports setting of breakpoints inside compiled functions and
stepping of compiled code. Breakpoints can only be set at known
locations (see Unknown Locations and Interrupts), so these commands
are largely useless unless the debug optimize quality is at least
2 (see Debug Information). These commands manipulate breakpoints:
- breakpoint [