Simplicity first: spending your complexity budget wisely.

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.

These goals are usually complementary: simplifying code generally reduces its size (both in terms of binary size and runtime memory usage), and avoiding unnecessary work makes code run faster. Smaller code also tends to run faster on modern hardware due to CPU cacheing: fitting your code into L1 cache is great, and staying in L2 cache is still pretty good.

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.

Ken Thompson's maximum "when in doubt, use brute force" is an admonishment to start with the simplest possible approach and only optimize as needed. Although implementing a given set of features is the eventual purpose of toybox, we choose to weight simplicity more heavily than anything else. Complexity is what we spend to get features (and occasionally smaller size or faster running time than the simplest possible implementation). Sometimes a feature, speedup, or code shrink isn't worth the complexity cost. We want to get "the best bang for the byte" we can, but sometimes being more explicit is preferable to being clever enough to outsmart yourself. (Even the best programmers are only human.)

Environmental dependencies are a type of complexity, so needing other packages to build or run is a big downside. For example, we don't use curses when we can simply output ansi escape sequences and trust all terminal programs written in the past 30 years to be able to support them. (A common use case is to download a statically linked toybox binary to an arbitrary Linux system, and use it in an otherwise unknown environment. It _must_ be completely self-contained to support this.)

Code style

Toybox source is formatted to be read with 4-space tab stops. Each file starts with a special comment telling vi to set the tab stop to 4. Note that one of the bugs in Ubuntu 7.10 broke vi's ability to parse these comments; you must either rebuild vim from source, or go ":ts=4" yourself each time you load the file.

Gotos are allowed for error handling, and for breaking out of nested loops. In general, a goto should only jump forward (not back), and should either jump to the end of an outer loop, or to error handling code at the end of the function. Goto labels are never indented: they override the block structure of the file. Putting them at the left edge makes them easy to spot as overrides to the normal flow of control, which they are.

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 to enable when building 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.

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: "configure" describes the build and installation environment, ".config" lists the features selected by defconfig/menuconfig.)

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 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.)

An easy way to start a new command is copy the file "hello.c" to the name of the new command, and modify this copy to implement the new command. This file is an example command meant to be used as a "skeleton" for new commands (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). It provides examples of all the build infrastructure (including optional elements like command line argument parsing and global variables that a "hello world" program doesn't strictly need).

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

Top level directory.

This directory contains global infrastructure.

toys.h

Each command #includes "toys.h" as part of its standard prolog.

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:

The "generated/" directory contains files generated from other source code in toybox. All of these files can be recreated by the build system, although some (such as generated/help.h) are shipped in release versions to reduce environmental dependencies (I.E. so you don't need python on your build system).

Directory toys/

toys/Config.in

Included from the top level Config.in, contains one or more configuration entries for each command.

Each command has a configuration entry matching the command name (although configuration symbols are uppercase and command names are lower case). Options to commands start with the command name followed by an underscore and the option name. Global options are attached to the "toybox" command, and thus use the prefix "TOYBOX_". This organization is used by scripts/cfg2files to select which toys/*.c files to compile for a given .config.

A command with multiple names (or multiple similar commands implemented in the same .c file) should have config symbols prefixed with the name of their C file. I.E. config symbol prefixes are NEWTOY() names. If OLDTOY() names have config symbols they're options (symbols with an underscore and suffix) to the NEWTOY() name. (See toys/toylist.h)

toys/toylist.h

The first half of this file prototypes all the structures to hold global variables for each command, and puts them in toy_union. These prototypes are only included if the macro NEWTOY isn't defined (in which case NEWTOY is defined to a default value that produces function prototypes).

The second half of this file lists all the commands in alphabetical order, along with their command line arguments and install location. Each command has an appropriate configuration guard so only the commands that are enabled wind up in the list.

The first time this header is #included, it defines structures and produces function prototypes for the commands in the toys directory.

The first time it's included, it defines structures and produces function prototypes. This is used to initialize toy_list in main.c, and later in that file to initialize NEED_OPTIONS (to figure out whether the command like parsing logic is needed), and to put the help entries in the right order in toys/help.c.

toys/help.h

#defines two help text strings for each command: a single line command_help and an additinal command_help_long. This is used by help_main() in toys/help.c to display help for commands.

Although this file is generated from Config.in help entries by scripts/config2help.py, it's shipped in release tarballs so you don't need python on the build system. (If you check code out of source control, or modify Config.in, then you'll need python installed to rebuild it.)

This file contains help for all commands, regardless of current configuration, but only the currently enabled ones are entered into help_data[] in toys/help.c.

Directory lib/

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

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. 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 has 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:

DECLARE_GLOBALS(
	char *c;
	char *b;
	long a;
)
#define TT this.command

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 DECLARE_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.

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).

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:

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.

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]. Again 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.

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).

Directory scripts/

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

Directory generated/

All the files in this directory except the README are generated by the build. (See scripts/make.sh)

Everything in this directory is a derivative file produced from something else. The entire directory is deleted by "make distclean".