Code style

The primary goal of toybox is _simple_ code. Keeping the code small is second, with speed and lots of features coming in somewhere after that. (For more on that, see the design page.)

A simple implementation usually takes up fewer lines of source code, meaning more code can fit on the screen at once, meaning the programmer can see more of it on the screen and thus keep more if in their head at once. This helps code auditing and thus reduces bugs. That said, sometimes being more explicit is preferable to being clever enough to outsmart yourself: don't be so terse your code is unreadable.

Toybox has an actual coding style guide over on the design page, but in general we just want the code to be consistent.

Building Toybox

Toybox is configured using the Kconfig language pioneered by the Linux kernel, and adopted by many other projects (uClibc, OpenEmbedded, etc). This generates a ".config" file containing the selected options, which controls which features are included when compiling toybox.

Each configuration option has a default value. The defaults indicate the "maximum sane configuration", I.E. if the feature defaults to "n" then it either isn't complete or is a special-purpose option (such as debugging code) that isn't intended for general purpose use.

For a more compact human-editable version .config files, you can use the miniconfig format.

The standard build invocation is:

Type "make help" to see all available build options.

The file "configure" contains a number of environment variable definitions which influence the build, such as specifying which compiler to use or where to install the resulting binaries. This file is included by the build, but accepts existing definitions of the environment variables, so it may be sourced or modified by the developer before building and the definitions exported to the environment will take precedence.

(To clarify: ".config" lists the features selected by defconfig/menuconfig, I.E. "what to build", and "configure" describes the build and installation environment, I.E. "how to build it".)

Running a command

main

The toybox main() function is at the end of main.c at the top level. It has two possible codepaths, only one of which is configured into any given build of toybox.

If CONFIG_SINGLE is selected, toybox is configured to contain only a single command, so most of the normal setup can be skipped. In this case the multiplexer isn't used, instead main() calls toy_singleinit() (also in main.c) to set up global state and parse command line arguments, calls the command's main function out of toy_list (in the CONFIG_SINGLE case the array has a single entry, no need to search), and if the function returns instead of exiting it flushes stdout (detecting error) and returns toys.exitval.

When CONFIG_SINGLE is not selected, main() uses basename() to find the name it was run as, shifts its argument list one to the right so it lines up with where the multiplexer function expects it, and calls toybox_main(). This leverages the multiplexer command's infrastructure to find and run the appropriate command. (A command name starting with "toybox" will recursively call toybox_main(); you can go "./toybox toybox toybox toybox ls" if you want to...)

toybox_main

The toybox_main() function is also in main,c. It handles a possible --help option ("toybox --help ls"), prints the list of available commands if no arguments were provided to the multiplexer (or with full path names if any other option is provided before a command name, ala "toybox --list"). Otherwise it calls toy_exec() on its argument list.

Note that the multiplexer is the first entry in toy_list (the rest of the list is sorted alphabetically to allow binary search), so toybox_main can cheat and just grab the first entry to quickly set up its context without searching. Since all command names go through the multiplexer at least once in the non-TOYBOX_SINGLE case, this avoids a redundant search of the list.

The toy_exec() function is also in main.c. It performs toy_find() to perform a binary search on the toy_list array to look up the command's entry by name and saves it in the global variable which, calls toy_init() to parse command line arguments and set up global state (using which->options), and calls the appropriate command's main() function (which->toy_main). On return it flushes all pending ansi FILE * I/O, detects if stdout had an error, and then calls xexit() (which uses toys.exitval).

Infrastructure

The toybox source code is in following directories:

Adding a new command

To add a new command to toybox, add a C file implementing that command to one of the subdirectories under the toys directory. No other files need to be modified; the build extracts all the information it needs (such as command line arguments) from specially formatted comments and macros in the C file. (See the description of the "generated" directory for details.)

Currently there are five subdirectories under "toys", one for commands defined by the POSIX standard, one for commands defined by the Linux Standard Base, an "other" directory for commands not covered by an obvious standard, a directory of example commands (templates to use when starting new commands), and a "pending" directory of commands that need further review/cleanup before moving to one of the other directories (run these at your own risk, cleanup patches welcome). These directories are just for developer convenience sorting the commands, the directories are otherwise functionally identical. To add a new category, create the appropriate directory with a README file in it whose first line is the description menuconfig should use for the directory.)

An easy way to start a new command is copy the file "toys/example/hello.c" to the name of the new command, and modify this copy to implement the new command (more or less by turning every instance of "hello" into the name of your command, updating the command line arguments, globals, and help data, and then filling out its "main" function with code that does something interesting).

You could also start with "toys/example/skeleton.c", which provides a lot more example code (showing several variants of command line option parsing, how to implement multiple commands in the same file, and so on). But usually it's just more stuff to delete.

Here's a checklist of steps to turn hello.c into another command:

Headers.

Commands generally don't have their own headers. If it's common code it can live in lib/, if it isn't put it in the command's .c file. (The line between implementing multiple commands in a C file via OLDTOY() to share infrastructure and moving that shared infrastructure to lib/ is a judgement call. Try to figure out which is simplest.)

The top level toys.h should #include all the standard (posix) headers that any command uses. (Partly this is friendly to ccache and partly this makes the command implementations shorter.) Individual commands should only need to include nonstandard headers that might prevent that command from building in some context we'd care about (and thus requiring that command to be disabled to avoid a build break).

Target-specific stuff (differences between compiler versions, libc versions, or operating systems) should be confined to lib/portability.h and lib/portability.c. (There's even some minimal compile-time environment probing that writes data to generated/portability.h, see scripts/genconfig.sh.)

Only include linux/*.h headers from individual commands (not from other headers), and only if you really need to. Data that varies per architecture is a good reason to include a header. If you just need a couple constants that haven't changed since the 1990's, it's ok to #define them yourself or just use the constant inline with a comment explaining what it is. (A #define that's only used once isn't really helping.)

Top level directory.

This directory contains global infrastructure.

toys.h

Each command #includes "toys.h" as part of its standard prolog. It may "#define FOR_commandname" before doing so to get some extra entries specific to this command.

This file sucks in most of the commonly used standard #includes, so individual files can just #include "toys.h" and not have to worry about stdargs.h and so on. Individual commands still need to #include special-purpose headers that may not be present on all systems (and thus would prevent toybox from building that command on such a system with that command enabled). Examples include regex support, any "linux/" or "asm/" headers, mtab support (mntent.h and sys/mount.h), and so on.

The toys.h header also defines structures for most of the global variables provided to each command by toybox_main(). These are described in detail in the description for main.c, where they are initialized.

The global variables are grouped into structures (and a union) for space savings, to more easily track the amount of memory consumed by them, so that they may be automatically cleared/initialized as needed, and so that access to global variables is more easily distinguished from access to local variables.

main.c

Contains the main() function where execution starts, plus common infrastructure to initialize global variables and select which command to run. The "toybox" multiplexer command also lives here. (This is the only command defined outside of the toys directory.)

Execution starts in main() which trims any path off of the first command name and calls toybox_main(), which calls toy_exec(), which calls toy_find() and toy_init() before calling the appropriate command's function from toy_list[] (via toys.which->toy_main()). If the command is "toybox", execution recurses into toybox_main(), otherwise the call goes to the appropriate commandname_main() from a C file in the toys directory.

The following global variables are defined in main.c:

The following functions are defined in main.c:

Config.in

Top level configuration file in a stylized variant of kconfig format. Includes generated/Config.in.

These files are directly used by "make menuconfig" to select which commands to build into toybox (thus generating a .config file), and by scripts/config2help.py to create generated/help.h.

Temporary files:

There is one temporary file in the top level source directory:

Directory generated/

The remaining temporary files live in the "generated/" directory, which is for files generated at build time from other source files.

Directory lib/

TODO: document lots more here.

lib: getmountlist(), error_msg/error_exit, xmalloc(), strlcpy(), xexec(), xopen()/xread(), xgetcwd(), xabspath(), find_in_path(), itoa().

lib/xwrap.c

Functions prefixed with the letter x call perror_exit() when they hit errors, to eliminate common error checking. This prints an error message and the strerror() string for the errno encountered.

You can intercept this exit by assigning a setjmp/longjmp buffer to toys.rebound (set it back to zero to restore the default behavior). If you do this, cleaning up resource leaks is your problem.

lib/lib.c

Eight gazillion common functions:

lib/portability.h

This file is automatically included from the top of toys.h, and smooths over differences between platforms (hardware targets, compilers, C libraries, operating systems, etc).

This file provides SWAP macros (SWAP_BE16(x) and SWAP_LE32(x) and so on).

A macro like SWAP_LE32(x) means "The value in x is stored as a little endian 32 bit value, so perform the translation to/from whatever the native 32-bit format is". You do the swap once on the way in, and once on the way out. If your target is already little endian, the macro is a NOP.

The SWAP macros come in BE and LE each with 16, 32, and 64 bit versions. In each case, the name of the macro refers to the _external_ representation, and converts to/from whatever your native representation happens to be (which can vary depending on what you're currently compiling for).

lib/llist.c

Some generic single and doubly linked list functions, which take advantage of a couple properties of C:

Toybox's list structures always have their next pointer as the first entry of each struct, and singly linked lists end with a NULL pointer. This allows generic code to traverse such lists without knowing anything else about the specific structs composing them: if your pointer isn't NULL typecast it to void ** and dereference once to get the next entry.

lib/lib.h defines three structure types:

List Functions List code trivia questions:

lib/args.c

Toybox's main.c automatically parses command line options before calling the command's main function. Option parsing starts in get_optflags(), which stores results in the global structures "toys" (optflags and optargs) and "this".

The option parsing infrastructure stores a bitfield in toys.optflags to indicate which options the current command line contained, and defines FLAG macros code can use to check whether each argument's bit is set. Arguments attached to those options are saved into the command's global structure ("this"). Any remaining command line arguments are collected together into the null-terminated array toys.optargs, with the length in toys.optc. (Note that toys.optargs does not contain the current command name at position zero, use "toys.which->name" for that.) The raw command line arguments get_optflags() parsed are retained unmodified in toys.argv[].

Toybox's option parsing logic is controlled by an "optflags" string, using a format reminiscent of getopt's optargs but with several important differences. Toybox does not use the getopt() function out of the C library, get_optflags() is an independent implementation which doesn't permute the original arguments (and thus doesn't change how the command is displayed in ps and top), and has many features not present in libc optargs() (such as the ability to describe long options in the same string as normal options).

Each command's NEWTOY() macro has an optflags string as its middle argument, which sets toy_list.options for that command to tell get_optflags() what command line arguments to look for, and what to do with them. If a command has no option definition string (I.E. the argument is NULL), option parsing is skipped for that command, which must look at the raw data in toys.argv to parse its own arguments. (If no currently enabled command uses option parsing, get_optflags() is optimized out of the resulting binary by the compiler's --gc-sections option.)

You don't have to free the option strings, which point into the environment space (I.E. the string data is not copied). A TOYFLAG_NOFORK command that uses the linked list type "*" should free the list objects but not the data they point to, via "llist_free(TT.mylist, NULL);". (If it's not NOFORK, exit() will free all the malloced data anyway unless you want to implement a CONFIG_TOYBOX_FREE cleanup for it.)

Optflags format string

Note: the optflags option description string format is much more concisely described by a large comment at the top of lib/args.c.

The general theory is that letters set optflags, and punctuation describes other actions the option parsing logic should take.

For example, suppose the command line command -b fruit -d walrus -a 42 is parsed using the optflags string "a#b:c:d". (I.E. toys.which->options="a#b:c:d" and argv = ["command", "-b", "fruit", "-d", "walrus", "-a", "42"]). When get_optflags() returns, the following data is available to command_main():

If the command's globals are:

GLOBALS(
	char *c;
	char *b;
	long a;
)

That would mean TT.c == NULL, TT.b == "fruit", and TT.a == 42. (Remember, each entry that receives an argument must be a long or pointer, to line up with the array position. Right to left in the optflags string corresponds to top to bottom in GLOBALS().

Put globals not filled out by the option parsing logic at the end of the GLOBALS block. Common practice is to list the options one per line (to make the ordering explicit, first to last in globals corresponds to right to left in the option string), then leave a blank line before any non-option globals.

long toys.optflags

Each option in the optflags string corresponds to a bit position in toys.optflags, with the same value as a corresponding binary digit. The rightmost argument is (1<<0), the next to last is (1<<1) and so on. If the option isn't encountered while parsing argv[], its bit remains 0.

Each option -x has a FLAG_x macro for the command letter. Bare --longopts with no corresponding short option have a FLAG_longopt macro for the long optionname. Commands enable these macros by #defining FOR_commandname before #including . When multiple commands are implemented in the same source file, you can switch flag contexts later in the file by #defining CLEANUP_oldcommand and #defining FOR_newcommand, then #including .

Options disabled in the current configuration (wrapped in a USE_BLAH() macro for a CONFIG_BLAH that's switched off) have their corresponding FLAG macro set to zero, so code checking them ala if (toys.optargs & FLAG_x) gets optimized out via dead code elimination. #defining FORCE_FLAGS when switching flag context disables this behavior: the flag is never zero even if the config is disabled. This allows code shared between multiple commands to use the same flag values, as long as the common flags match up right to left in both option strings.

For example, the optflags string "abcd" would parse the command line argument "-c" to set optflags to 2, "-a" would set optflags to 8, "-bd" would set optflags to 6 (I.E. 4|2), and "-a -c" would set optflags to 10 (2|8). To check if -c was encountered, code could test: if (toys.optflags & FLAG_c) printf("yup"); (See the toys/examples directory for more.)

Only letters are relevant to optflags, punctuation is skipped: in the string "a*b:c#d", d=1, c=2, b=4, a=8. The punctuation after a letter usually indicate that the option takes an argument.

Since toys.optflags is an unsigned int, it only stores 32 bits. (Which is the amount a long would have on 32-bit platforms anyway; 64 bit code on 32 bit platforms is too expensive to require in common code used by almost all commands.) Bit positions beyond the 1<<31 aren't recorded, but parsing higher options can still set global variables.

Automatically setting global variables from arguments (union this)

The following punctuation characters may be appended to an optflags argument letter, indicating the option takes an additional argument:

GLOBALS

Options which have an argument fill in the corresponding slot in the global union "this" (see generated/globals.h), treating it as an array of longs with the rightmost saved in this[0]. As described above, using "a*b:c#d", "-c 42" would set this[0] = 42; and "-b 42" would set this[1] = "42"; each slot is left NULL if the corresponding argument is not encountered.

This behavior is useful because the LP64 standard ensures long and pointer are the same size. C99 guarantees structure members will occur in memory in the same order they're declared, and that padding won't be inserted between consecutive variables of register size. Thus the first few entries can be longs or pointers corresponding to the saved arguments.

See toys/example/*.c for longer examples of parsing options into the GLOBALS block.

char *toys.optargs[]

Command line arguments in argv[] which are not consumed by option parsing (I.E. not recognized either as -flags or arguments to -flags) will be copied to toys.optargs[], with the length of that array in toys.optc. (When toys.optc is 0, no unrecognized command line arguments remain.) The order of entries is preserved, and as with argv[] this new array is also terminated by a NULL entry.

Option parsing can require a minimum or maximum number of optargs left over, by adding "<1" (read "at least one") or ">9" ("at most nine") to the start of the optflags string.

The special argument "--" terminates option parsing, storing all remaining arguments in optargs. The "--" itself is consumed.

Other optflags control characters

The following characters may occur at the start of each command's optflags string, before any options that would set a bit in toys.optflags:

The following characters may be appended to an option character, but do not by themselves indicate an extra argument should be saved in this[]. (Technically any character not recognized as a control character sets an optflag, but letters are never control characters.)

The following may be appended to a float or double:

Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT is enabled. (Otherwise the code to determine where floating point constants end drops out. When disabled, it can reserve a global data slot for the argument so offsets won't change, but will never fill it out.) You can handle this by using the USE_BLAH() macros with C string concatenation, ala:

"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"

--longopts

The optflags string can contain long options, which are enclosed in parentheses. They may be appended to an existing option character, in which case the --longopt is a synonym for that option, ala "a:(--fred)" which understands "-a blah" or "--fred blah" as synonyms.

Longopts may also appear before any other options in the optflags string, in which case they have no corresponding short argument, but instead set their own bit based on position. So for "(walrus)#(blah)xy:z", "command --walrus 42" would set toys.optflags = 16 (-z = 1, -y = 2, -x = 4, --blah = 8) and would assign this[1] = 42;

A short option may have multiple longopt synonyms, "a(one)(two)", but each "bare longopt" (ala "(one)(two)abc" before any option characters) always sets its own bit (although you can group them with +X).

Only bare longopts have a FLAG_ macro with the longopt name (ala --fred would #define FLAG_fred). Other longopts use the short option's FLAG macro to test the toys.optflags bit.

Options with a semicolon ";" after their data type can only set their corresponding GLOBALS() entry via "--longopt=value". For example, option string "x(boing): y" would set TT.x if it saw "--boing=value", but would treat "--boing value" as setting FLAG_x in toys.optargs, leaving TT.x NULL, and keeping "value" in toys.optargs[]. (This lets "ls --color" and "ls --color=auto" both work.)

[groups]

At the end of the option string, square bracket groups can define relationships between existing options. (This only applies to short options, bare --longopts can't participate.)

The first character of the group defines the type, the remaining characters are options it applies to:

So "abc[-abc]" means -ab = -b, -ba = -a, -abc = -c. "abc[+abc]" means -ab=-abc, -c=-abc, and "abc[!abc] means -ab calls error_exit("no -b with -a"). Note that [-] groups clear the GLOBALS option slot of options they're switching back off, but [+] won't set options it didn't see (just the optflags).

whitespace

Arguments may occur with or without a space (I.E. "-a 42" or "-a42"). The command line argument "-abc" may be interepreted many different ways: the optflags string "cba" sets toys.optflags = 7, "c:ba" sets toys.optflags=4 and saves "ba" as the argument to -c, and "cb:a" sets optflags to 6 and saves "c" as the argument to -b.

Note that & changes whitespace handling, so that the command line "tar cvfCj outfile.tar.bz2 topdir filename" is parsed the same as "tar filename -c -v -j -f outfile.tar.bz2 -C topdir". Note that "tar -cvfCj one two three" would equal "tar -c -v -f Cj one two three". (This matches historical usage.)

Appending a space to the option in the option string ("a: b") makes it require a space, I.E. "-ab" is interpreted as "-a" "-b". That way "kill -stop" differs from "kill -s top".

Appending ; to a longopt in the option string makes its argument optional, and only settable with =, so in ls "(color):;" can accept "ls --color" and "ls --color=auto" without complaining that the first has no argument.

lib/dirtree.c

The directory tree traversal code should be sufficiently generic that commands never need to use readdir(), scandir(), or the fts.h family of functions.

These functions do not call chdir() or rely on PATH_MAX. Instead they use openat() and friends, using one filehandle per directory level to recurse into subdirectories. (I.E. they can descend 1000 directories deep if setrlimit(RLIMIT_NOFILE) allows enough open filehandles, and the default in /proc/self/limits is generally 1024.)

There are two main ways to use dirtree: 1) assemble a tree of nodes representing a snapshot of directory state and traverse them using the ->next and ->child pointers, or 2) traverse the tree calling a callback function on each entry, and freeing its node afterwards. (You can also combine the two, using the callback as a filter to determine which nodes to keep.)

The basic dirtree functions are:

The dirtree_read() function is the standard way to start directory traversal. It takes two arguments: a starting path for the root of the tree, and a callback function. The callback() is called on each directory entry, its argument is a fully populated struct dirtree * (from lib/lib.h) describing the node, and its return value tells the dirtree infrastructure what to do next.

(There's also a three argument version, dirtree_flagread(char *path, int flags, int (*callback)(struct dirtree node)), which lets you apply flags like DIRTREE_SYMFOLLOW and DIRTREE_SHUTUP to reading the top node, but this only affects the top node. Child nodes use the flags returned by callback().

struct dirtree

Each struct dirtree node contains char name[] and struct stat st entries describing a file, plus a char *symlink which is NULL for non-symlinks.

During a callback function, the int dirfd field of directory nodes contains a directory file descriptor (for use with the openat() family of functions). This isn't usually used directly, intstead call dirtree_parentfd() on the callback's node argument. The char again field is 0 for the first callback on a node, and 1 on the second callback (triggered by returning DIRTREE_COMEAGAIN on a directory, made after all children have been processed).

Users of this code may put anything they like into the long extra field. For example, "cp" and "mv" use this to store a dirfd for the destination directory (and use DIRTREE_COMEAGAIN to get the second callback so they can close(node->extra) to avoid running out of filehandles). This field is not directly used by the dirtree code, and thanks to LP64 it's large enough to store a typecast pointer to an arbitrary struct.

The return value of the callback combines flags (with boolean or) to tell the traversal infrastructure how to behave:

Each struct dirtree contains three pointers (next, parent, and child) to other struct dirtree.

The parent pointer indicates the directory containing this entry; even when not assembling a persistent tree of nodes the parent entries remain live up to the root of the tree while child nodes are active. At the top of the tree the parent pointer is NULL, meaning the node's name[] is either an absolute path or relative to cwd. The function dirtree_parentfd() gets the directory file descriptor for use with openat() and friends, returning AT_FDCWD at the top of tree.

The child pointer points to the first node of the list of contents of this directory. If the directory contains no files, or the entry isn't a directory, child is NULL.

The next pointer indicates sibling nodes in the same directory as this node, and since it's the first entry in the struct the llist.c traversal mechanisms work to iterate over sibling nodes. Each dirtree node is a single malloc() (even char *symlink points to memory at the end of the node), so llist_free() works but its callback must descend into child nodes (freeing a tree, not just a linked list), plus whatever the user stored in extra.

The dirtree_flagread() function is a simple wrapper, calling dirtree_add_node() to create a root node relative to the current directory, then calling dirtree_handle_callback() on that node (which recurses as instructed by the callback return flags). The flags argument primarily lets you control whether or not to follow symlinks to the root node; symlinks listed on the command line are often treated differently than symlinks encountered during recursive directory traversal.

The ls command not only bypasses this wrapper, but never returns DIRTREE_RECURSE from the callback, instead calling dirtree_recurse() manually from elsewhere in the program. This gives ls -lR manual control of traversal order, which is neither depth first nor breadth first but instead a sort of FIFO order requried by the ls standard.

Directory toys/

This directory contains command implementations. Each command is a single self-contained file. Adding a new command involves adding a single file, and removing a command involves removing that file. Commands use shared infrastructure from the lib/ and generated/ directories.

Currently there are five subdirectories under "toys/" containing "posix" commands described in POSIX-2008, "lsb" commands described in the Linux Standard Base 4.1, "other" commands not described by either standard, "pending" commands awaiting cleanup (which default to "n" in menuconfig because they don't necessarily work right yet), and "example" code showing how toybox infrastructure works and providing template/skeleton files to start new commands.

The only difference directory location makes is which menu the command shows up in during "make menuconfig", the directories are otherwise identical. Note that the commands exist within a single namespace at runtime, so you can't have the same command in multiple subdirectories. (The build tries to fail informatively when you do that.)

There is one more sub-menus in "make menuconfig" containing global configuration options for toybox. This menu is defined in the top level Config.in.

See adding a new command for details on the layout of a command file.

Directory scripts/

Build infrastructure. The makefile calls scripts/make.sh for "make" and scripts/install.sh for "make install".

There's also a test suite, "make test" calls make/test.sh, which runs all the tests in make/test/*. You can run individual tests via "scripts/test.sh command", or "TEST_HOST=1 scripts/test.sh command" to run that test against the host implementation instead of the toybox one.

scripts/cfg2files.sh

Run .config through this filter to get a list of enabled commands, which is turned into a list of files in toys via a sed invocation in the top level Makefile.

Directory kconfig/

Menuconfig infrastructure copied from the Linux kernel. See the Linux kernel's Documentation/kbuild/kconfig-language.txt