blob: faa718cafba2786fa2403d44d42cdb0a84b0f38d [file] [log] [blame]
Rob Landley349ff522014-01-04 13:09:42 -06001<html><head><title>toybox source code walkthrough</title></head>
Rob Landley4e68de12007-12-13 07:00:27 -06002<!--#include file="header.html" -->
3
Rob Landley27048342013-08-18 14:24:59 -05004<p><h1><a name="style" /><a href="#style">Code style</a></h1></p>
Rob Landleye7c9a6d2012-02-28 06:34:09 -06005
6<p>The primary goal of toybox is _simple_ code. Keeping the code small is
Rob Landleyed6ed622012-03-06 20:49:03 -06007second, with speed and lots of features coming in somewhere after that.
8(For more on that, see the <a href=design.html>design</a> page.)</p>
Rob Landleye7c9a6d2012-02-28 06:34:09 -06009
10<p>A simple implementation usually takes up fewer lines of source code,
11meaning more code can fit on the screen at once, meaning the programmer can
12see more of it on the screen and thus keep more if in their head at once.
Rob Landleyed6ed622012-03-06 20:49:03 -060013This helps code auditing and thus reduces bugs. That said, sometimes being
14more explicit is preferable to being clever enough to outsmart yourself:
15don't be so terse your code is unreadable.</p>
Rob Landley5a0660f2007-12-27 21:36:44 -060016
Rob Landleyca733922014-05-19 18:24:35 -050017<p>Toybox has an actual coding style guide over on
18<a href=design.html#codestyle>the design page</a>, but in general we just
19want the code to be consistent.</p>
Rob Landley5a0660f2007-12-27 21:36:44 -060020
Rob Landley27048342013-08-18 14:24:59 -050021<p><h1><a name="building" /><a href="#building">Building Toybox</a></h1></p>
Rob Landleye7c9a6d2012-02-28 06:34:09 -060022
23<p>Toybox is configured using the Kconfig language pioneered by the Linux
24kernel, and adopted by many other projects (uClibc, OpenEmbedded, etc).
25This generates a ".config" file containing the selected options, which
Rob Landley7aa651a2012-11-13 17:14:08 -060026controls which features are included when compiling toybox.</p>
Rob Landleye7c9a6d2012-02-28 06:34:09 -060027
28<p>Each configuration option has a default value. The defaults indicate the
29"maximum sane configuration", I.E. if the feature defaults to "n" then it
30either isn't complete or is a special-purpose option (such as debugging
31code) that isn't intended for general purpose use.</p>
32
33<p>The standard build invocation is:</p>
34
35<ul>
36<li>make defconfig #(or menuconfig)</li>
37<li>make</li>
38<li>make install</li>
39</ul>
40
41<p>Type "make help" to see all available build options.</p>
42
43<p>The file "configure" contains a number of environment variable definitions
44which influence the build, such as specifying which compiler to use or where
45to install the resulting binaries. This file is included by the build, but
46accepts existing definitions of the environment variables, so it may be sourced
47or modified by the developer before building and the definitions exported
48to the environment will take precedence.</p>
49
50<p>(To clarify: "configure" describes the build and installation environment,
51".config" lists the features selected by defconfig/menuconfig.)</p>
Rob Landley6882ee82008-02-12 18:41:34 -060052
Rob Landley27048342013-08-18 14:24:59 -050053<p><h1><a name="running"><a href="#running">Running a command</a></h1></p>
54
55<h2>main</h2>
56
57<p>The toybox main() function is at the end of main.c at the top level. It has
58two possible codepaths, only one of which is configured into any given build
59of toybox.</p>
60
61<p>If CONFIG_SINGLE is selected, toybox is configured to contain only a single
62command, so most of the normal setup can be skipped. In this case the
63multiplexer isn't used, instead main() calls toy_singleinit() (also in main.c)
64to set up global state and parse command line arguments, calls the command's
65main 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
66it flushes stdout (detecting error) and returns toys.exitval.</p>
67
68<p>When CONFIG_SINGLE is not selected, main() uses basename() to find the
69name it was run as, shifts its argument list one to the right so it lines up
70with where the multiplexer function expects it, and calls toybox_main(). This
71leverages the multiplexer command's infrastructure to find and run the
72appropriate command. (A command name starting with "toybox" will
73recursively call toybox_main(); you can go "./toybox toybox toybox toybox ls"
74if you want to...)</p>
75
76<h2>toybox_main</h2>
77
78<p>The toybox_main() function is also in main,c. It handles a possible
79--help option ("toybox --help ls"), prints the list of available commands if no
80arguments were provided to the multiplexer (or with full path names if any
81other option is provided before a command name, ala "toybox --list").
82Otherwise it calls toy_exec() on its argument list.</p>
83
84<p>Note that the multiplexer is the first entry in toy_list (the rest of the
85list is sorted alphabetically to allow binary search), so toybox_main can
86cheat and just grab the first entry to quickly set up its context without
87searching. Since all command names go through the multiplexer at least once
88in the non-TOYBOX_SINGLE case, this avoids a redundant search of
89the list.</p>
90
91<p>The toy_exec() function is also in main.c. It performs toy_find() to
92perform a binary search on the toy_list array to look up the command's
93entry by name and saves it in the global variable which, calls toy_init()
94to parse command line arguments and set up global state (using which->options),
95and calls the appropriate command's main() function (which->toy_main). On
96return it flushes all pending ansi FILE * I/O, detects if stdout had an
97error, and then calls xexit() (which uses toys.exitval).</p>
98
99<p><h1><a name="infrastructure" /><a href="#infrastructure">Infrastructure</a></h1></p>
Rob Landley4e68de12007-12-13 07:00:27 -0600100
Rob Landley7c04f012008-01-20 19:00:16 -0600101<p>The toybox source code is in following directories:</p>
102<ul>
103<li>The <a href="#top">top level directory</a> contains the file main.c (were
104execution starts), the header file toys.h (included by every command), and
105other global infrastructure.</li>
106<li>The <a href="#lib">lib directory</a> contains common functions shared by
Rob Landleyc8d0da52012-07-15 17:47:08 -0500107multiple commands:</li>
108<ul>
109<li><a href="#lib_lib">lib/lib.c</a></li>
110<li><a href="#lib_llist">lib/llist.c</a></li>
111<li><a href="#lib_args">lib/args.c</a></li>
112<li><a href="#lib_dirtree">lib/dirtree.c</a></li>
113</ul>
Rob Landley7c04f012008-01-20 19:00:16 -0600114<li>The <a href="#toys">toys directory</a> contains the C files implementating
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500115each command. Currently it contains three subdirectories:
116posix, lsb, and other.</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600117<li>The <a href="#scripts">scripts directory</a> contains the build and
118test infrastructure.</li>
119<li>The <a href="#kconfig">kconfig directory</a> contains the configuration
120infrastructure implementing menuconfig (copied from the Linux kernel).</li>
121<li>The <a href="#generated">generated directory</a> contains intermediate
122files generated from other parts of the source code.</li>
123</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600124
Rob Landleybbe500e2012-02-26 21:53:15 -0600125<a name="adding" />
Rob Landley7eaf4f52014-04-09 08:30:09 -0500126<p><h1><a href="#adding">Adding a new command</a></h1></p>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500127<p>To add a new command to toybox, add a C file implementing that command under
Rob Landley7c04f012008-01-20 19:00:16 -0600128the toys directory. No other files need to be modified; the build extracts
Rob Landley6882ee82008-02-12 18:41:34 -0600129all the information it needs (such as command line arguments) from specially
Rob Landley7c04f012008-01-20 19:00:16 -0600130formatted comments and macros in the C file. (See the description of the
Rob Landleye7c9a6d2012-02-28 06:34:09 -0600131<a href="#generated">"generated" directory</a> for details.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600132
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500133<p>Currently there are three subdirectories under "toys", one for commands
134defined by the POSIX standard, one for commands defined by the Linux Standard
135Base, and one for all other commands. (This is just for developer convenience
136sorting them, the directories are otherwise functionally identical.)</p>
137
138<p>An easy way to start a new command is copy the file "toys/other/hello.c" to
Rob Landley7c04f012008-01-20 19:00:16 -0600139the name of the new command, and modify this copy to implement the new command.
Rob Landley6882ee82008-02-12 18:41:34 -0600140This file is an example command meant to be used as a "skeleton" for
Rob Landley7c04f012008-01-20 19:00:16 -0600141new commands (more or less by turning every instance of "hello" into the
142name of your command, updating the command line arguments, globals, and
143help data, and then filling out its "main" function with code that does
Rob Landley6882ee82008-02-12 18:41:34 -0600144something interesting). It provides examples of all the build infrastructure
145(including optional elements like command line argument parsing and global
146variables that a "hello world" program doesn't strictly need).</p>
Rob Landley7c04f012008-01-20 19:00:16 -0600147
148<p>Here's a checklist of steps to turn hello.c into another command:</p>
149
150<ul>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500151<li><p>First "cd toys/other" and "cp hello.c yourcommand.c". Note that the name
Rob Landley7c04f012008-01-20 19:00:16 -0600152of this file is significant, it's the name of the new command you're adding
153to toybox. Open your new file in your favorite editor.</p></li>
154
155<li><p>Change the one line comment at the top of the file (currently
156"hello.c - A hello world program") to describe your new file.</p></li>
157
158<li><p>Change the copyright notice to your name, email, and the current
159year.</p></li>
160
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500161<li><p>Give a URL to the relevant standards document, where applicable.
162(Sample links to SUSv4 and LSB are provided, feel free to link to other
163documentation or standards as appropriate.)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600164
Rob Landley66a69d92012-01-16 01:44:17 -0600165<li><p>Update the USE_YOURCOMMAND(NEWTOY(yourcommand,"blah",0)) line.
166The NEWTOY macro fills out this command's <a href="#toy_list">toy_list</a>
167structure. The arguments to the NEWTOY macro are:</p>
168
169<ol>
170<li><p>the name used to run your command</p></li>
171<li><p>the command line argument <a href="#lib_args">option parsing string</a> (NULL if none)</p></li>
172<li><p>a bitfield of TOYFLAG values
173(defined in toys.h) providing additional information such as where your
174command should be installed on a running system, whether to blank umask
175before running, whether or not the command must run as root (and thus should
176retain root access if installed SUID), and so on.</p></li>
177</ol>
178</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600179
180<li><p>Change the kconfig data (from "config YOURCOMMAND" to the end of the
181comment block) to supply your command's configuration and help
182information. The uppper case config symbols are used by menuconfig, and are
183also what the CFG_ and USE_() macros are generated from (see [TODO]). The
184help information here is used by menuconfig, and also by the "help" command to
185describe your new command. (See [TODO] for details.) By convention,
Rob Landley66a69d92012-01-16 01:44:17 -0600186unfinished commands default to "n" and finished commands default to "y",
187so "make defconfig" selects all finished commands. (Note, "finished" means
188"ready to be used", not that it'll never change again.)<p>
189
190<p>Each help block should start with a "usage: yourcommand" line explaining
191any command line arguments added by this config option. The "help" command
192outputs this text, and scripts/config2help.c in the build infrastructure
193collates these usage lines for commands with multiple configuration
194options when producing generated/help.h.</p>
195</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600196
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500197<li><p>Change the "#define FOR_hello" line to "#define FOR_yourcommand" right
198before the "#include <toys.h>". (This selects the appropriate FLAG_ macros and
199does a "#define TT this.yourcommand" so you can access the global variables
200out of the space-saving union of structures. If you aren't using any command
201flag bits and aren't defining a GLOBAL block, you can delete this line.)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600202
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500203<li><p>Update the GLOBALS() macro to contain your command's global
204variables. If your command has no global variables, delete this macro.</p>
205
206<p>Variables in the GLOBALS() block are are stored in a space saving
207<a href="#toy_union">union of structures</a> format, which may be accessed
208using the TT macro as if TT were a global structure (so TT.membername).
209If you specified two-character command line arguments in
210NEWTOY(), the first few global variables will be initialized by the automatic
211argument parsing logic, and the type and order of these variables must
212correspond to the arguments specified in NEWTOY().
213(See <a href="#lib_args">lib/args.c</a> for details.)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600214
215<li><p>Rename hello_main() to yourcommand_main(). This is the main() function
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500216where execution of your command starts. Your command line options are
217already sorted into this.optflags, this.optargs, this.optc, and the GLOBALS()
218as appropriate by the time this function is called. (See
219<a href="#lib_args">get_optflags()</a> for details.</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600220</ul>
221
Rob Landley7eaf4f52014-04-09 08:30:09 -0500222<a name="headers" /><h2><a href="#headers">Headers.</a></h2>
Rob Landley85a32412013-12-27 06:53:15 -0600223
224<p>Commands generally don't have their own headers. If it's common code
225it can live in lib/, if it isn't put it in the command's .c file. (The line
226between implementing multiple commands in a C file via OLDTOY() to share
227infrastructure and moving that shared infrastructure to lib/ is a judgement
228call. Try to figure out which is simplest.)</p>
229
230<p>The top level toys.h should #include all the standard (posix) headers
231that any command uses. (Partly this is friendly to ccache and partly this
232makes the command implementations shorter.) Individual commands should only
233need to include nonstandard headers that might prevent that command from
234building in some context we'd care about (and thus requiring that command to
235be disabled to avoid a build break).</p>
236
237<p>Target-specific stuff (differences between compiler versions, libc versions,
238or operating systems) should be confined to lib/portability.h and
239lib/portability.c. (There's even some minimal compile-time environment probing
240that writes data to generated/portability.h, see scripts/genconfig.sh.)</p>
241
242<p>Only include linux/*.h headers from individual commands (not from other
243headers), and only if you really need to. Data that varies per architecture
244is a good reason to include a header. If you just need a couple constants
245that haven't changed since the 1990's, it's ok to #define them yourself or
246just use the constant inline with a comment explaining what it is. (A
247#define that's only used once isn't really helping.)</p>
248
Rob Landley7eaf4f52014-04-09 08:30:09 -0500249<p><a name="top" /><h1><a href="#top">Top level directory.</a></h1></p>
Rob Landley7c04f012008-01-20 19:00:16 -0600250
Rob Landley66a69d92012-01-16 01:44:17 -0600251<p>This directory contains global infrastructure.</p>
252
253<h3>toys.h</h3>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500254<p>Each command #includes "toys.h" as part of its standard prolog. It
255may "#define FOR_commandname" before doing so to get some extra entries
256specific to this command.</p>
Rob Landley66a69d92012-01-16 01:44:17 -0600257
258<p>This file sucks in most of the commonly used standard #includes, so
259individual files can just #include "toys.h" and not have to worry about
260stdargs.h and so on. Individual commands still need to #include
261special-purpose headers that may not be present on all systems (and thus would
262prevent toybox from building that command on such a system with that command
263enabled). Examples include regex support, any "linux/" or "asm/" headers, mtab
264support (mntent.h and sys/mount.h), and so on.</p>
265
266<p>The toys.h header also defines structures for most of the global variables
267provided to each command by toybox_main(). These are described in
268detail in the description for main.c, where they are initialized.</p>
269
270<p>The global variables are grouped into structures (and a union) for space
271savings, to more easily track the amount of memory consumed by them,
272so that they may be automatically cleared/initialized as needed, and so
273that access to global variables is more easily distinguished from access to
274local variables.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600275
276<h3>main.c</h3>
277<p>Contains the main() function where execution starts, plus
278common infrastructure to initialize global variables and select which command
Rob Landley6882ee82008-02-12 18:41:34 -0600279to run. The "toybox" multiplexer command also lives here. (This is the
Rob Landley7c04f012008-01-20 19:00:16 -0600280only command defined outside of the toys directory.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600281
Rob Landley6882ee82008-02-12 18:41:34 -0600282<p>Execution starts in main() which trims any path off of the first command
283name and calls toybox_main(), which calls toy_exec(), which calls toy_find()
Rob Landley66a69d92012-01-16 01:44:17 -0600284and toy_init() before calling the appropriate command's function from
285toy_list[] (via toys.which->toy_main()).
Rob Landley6882ee82008-02-12 18:41:34 -0600286If the command is "toybox", execution recurses into toybox_main(), otherwise
287the call goes to the appropriate commandname_main() from a C file in the toys
288directory.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600289
Rob Landley6882ee82008-02-12 18:41:34 -0600290<p>The following global variables are defined in main.c:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600291<ul>
Rob Landley66a69d92012-01-16 01:44:17 -0600292<a name="toy_list" />
293<li><p><b>struct toy_list toy_list[]</b> - array describing all the
Rob Landley4e68de12007-12-13 07:00:27 -0600294commands currently configured into toybox. The first entry (toy_list[0]) is
295for the "toybox" multiplexer command, which runs all the other built-in commands
296without symlinks by using its first argument as the name of the command to
297run and the rest as that command's argument list (ala "./toybox echo hello").
298The remaining entries are the commands in alphabetical order (for efficient
299binary search).</p>
300
301<p>This is a read-only array initialized at compile time by
Rob Landley6882ee82008-02-12 18:41:34 -0600302defining macros and #including generated/newtoys.h.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600303
Rob Landley66a69d92012-01-16 01:44:17 -0600304<p>Members of struct toy_list (defined in "toys.h") include:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600305<ul>
306<li><p>char *<b>name</b> - the name of this command.</p></li>
307<li><p>void (*<b>toy_main</b>)(void) - function pointer to run this
308command.</p></li>
309<li><p>char *<b>options</b> - command line option string (used by
310get_optflags() in lib/args.c to intialize toys.optflags, toys.optargs, and
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500311entries in the toy's GLOBALS struct). When this is NULL, no option
Rob Landley66a69d92012-01-16 01:44:17 -0600312parsing is done before calling toy_main().</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600313<li><p>int <b>flags</b> - Behavior flags for this command. The following flags are currently understood:</p>
314
315<ul>
316<li><b>TOYFLAG_USR</b> - Install this command under /usr</li>
317<li><b>TOYFLAG_BIN</b> - Install this command under /bin</li>
318<li><b>TOYFLAG_SBIN</b> - Install this command under /sbin</li>
319<li><b>TOYFLAG_NOFORK</b> - This command can be used as a shell builtin.</li>
320<li><b>TOYFLAG_UMASK</b> - Call umask(0) before running this command.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600321<li><b>TOYFLAG_STAYROOT</b> - Don't drop permissions for this command if toybox is installed SUID root.</li>
322<li><b>TOYFLAG_NEEDROOT</b> - This command cannot function unless run with root access.</li>
Rob Landley6882ee82008-02-12 18:41:34 -0600323</ul>
324<br>
325
326<p>These flags are combined with | (or). For example, to install a command
327in /usr/bin, or together TOYFLAG_USR|TOYFLAG_BIN.</p>
328</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600329</li>
330
Rob Landley66a69d92012-01-16 01:44:17 -0600331<li><p><b>struct toy_context toys</b> - global structure containing information
332common to all commands, initializd by toy_init() and defined in "toys.h".
333Members of this structure include:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600334<ul>
335<li><p>struct toy_list *<b>which</b> - a pointer to this command's toy_list
336structure. Mostly used to grab the name of the running command
337(toys->which.name).</p>
338</li>
339<li><p>int <b>exitval</b> - Exit value of this command. Defaults to zero. The
340error_exit() functions will return 1 if this is zero, otherwise they'll
341return this value.</p></li>
342<li><p>char **<b>argv</b> - "raw" command line options, I.E. the original
343unmodified string array passed in to main(). Note that modifying this changes
Rob Landley66a69d92012-01-16 01:44:17 -0600344"ps" output, and is not recommended. This array is null terminated; a NULL
345entry indicates the end of the array.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600346<p>Most commands don't use this field, instead the use optargs, optflags,
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500347and the fields in the GLOBALS struct initialized by get_optflags().</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600348</li>
349<li><p>unsigned <b>optflags</b> - Command line option flags, set by
Rob Landley66a69d92012-01-16 01:44:17 -0600350<a href="#lib_args">get_optflags()</a>. Indicates which of the command line options listed in
Rob Landley6882ee82008-02-12 18:41:34 -0600351toys->which.options occurred this time.</p>
352
353<p>The rightmost command line argument listed in toys->which.options sets bit
3541, the next one sets bit 2, and so on. This means the bits are set in the same
355order the binary digits would be listed if typed out as a string. For example,
356the option string "abcd" would parse the command line "-c" to set optflags to 2,
357"-a" would set optflags to 8, and "-bd" would set optflags to 6 (4|2).</p>
358
359<p>Only letters are relevant to optflags. In the string "a*b:c#d", d=1, c=2,
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500360b=4, a=8. Punctuation after a letter initializes global variables at the
361start of the GLOBALS() block (see <a href="#toy_union">union toy_union this</a>
362for details).</p>
363
364<p>The build infrastructure creates FLAG_ macros for each option letter,
365corresponding to the bit position, so you can check (toys.optflags & FLAG_x)
366to see if a flag was specified. (The correct set of FLAG_ macros is selected
367by defining FOR_mycommand before #including toys.h. The macros live in
368toys/globals.h which is generated by scripts/make.sh.)</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600369
Rob Landley66a69d92012-01-16 01:44:17 -0600370<p>For more information on option parsing, see <a href="#lib_args">get_optflags()</a>.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600371
372</li>
Rob Landley4e68de12007-12-13 07:00:27 -0600373<li><p>char **<b>optargs</b> - Null terminated array of arguments left over
374after get_optflags() removed all the ones it understood. Note: optarg[0] is
375the first argument, not the command name. Use toys.which->name for the command
376name.</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600377<li><p>int <b>optc</b> - Optarg count, equivalent to argc but for
378optargs[].<p></li>
Rob Landley4e68de12007-12-13 07:00:27 -0600379<li><p>int <b>exithelp</b> - Whether error_exit() should print a usage message
380via help_main() before exiting. (True during option parsing, defaults to
381false afterwards.)</p></li>
Rob Landley66a69d92012-01-16 01:44:17 -0600382</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600383
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500384<a name="toy_union" />
Rob Landley66a69d92012-01-16 01:44:17 -0600385<li><p><b>union toy_union this</b> - Union of structures containing each
Rob Landley4e68de12007-12-13 07:00:27 -0600386command's global variables.</p>
387
Rob Landley6882ee82008-02-12 18:41:34 -0600388<p>Global variables are useful: they reduce the overhead of passing extra
389command line arguments between functions, they conveniently start prezeroed to
390save initialization costs, and the command line argument parsing infrastructure
391can also initialize global variables with its results.</p>
392
393<p>But since each toybox process can only run one command at a time, allocating
394space for global variables belonging to other commands you aren't currently
395running would be wasteful.</p>
396
397<p>Toybox handles this by encapsulating each command's global variables in
Rob Landley66a69d92012-01-16 01:44:17 -0600398a structure, and declaring a union of those structures with a single global
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500399instance (called "this"). The GLOBALS() macro contains the global
Rob Landley66a69d92012-01-16 01:44:17 -0600400variables that should go in the current command's global structure. Each
401variable can then be accessed as "this.commandname.varname".
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500402If you #defined FOR_commandname before including toys.h, the macro TT is
403#defined to this.commandname so the variable can then be accessed as
404"TT.variable". See toys/hello.c for an example.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600405
Rob Landley66a69d92012-01-16 01:44:17 -0600406<p>A command that needs global variables should declare a structure to
Rob Landley4e68de12007-12-13 07:00:27 -0600407contain them all, and add that structure to this union. A command should never
408declare global variables outside of this, because such global variables would
409allocate memory when running other commands that don't use those global
410variables.</p>
411
Rob Landley66a69d92012-01-16 01:44:17 -0600412<p>The first few fields of this structure can be intialized by <a href="#lib_args">get_optargs()</a>,
Rob Landley4e68de12007-12-13 07:00:27 -0600413as specified by the options field off this command's toy_list entry. See
414the get_optargs() description in lib/args.c for details.</p>
415</li>
416
Rob Landley81b899d2007-12-18 02:02:47 -0600417<li><b>char toybuf[4096]</b> - a common scratch space buffer so
Rob Landley4e68de12007-12-13 07:00:27 -0600418commands don't need to allocate their own. Any command is free to use this,
419and it should never be directly referenced by functions in lib/ (although
420commands are free to pass toybuf in to a library function as an argument).</li>
421</ul>
422
Rob Landley6882ee82008-02-12 18:41:34 -0600423<p>The following functions are defined in main.c:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600424<ul>
425<li><p>struct toy_list *<b>toy_find</b>(char *name) - Return the toy_list
426structure for this command name, or NULL if not found.</p></li>
Rob Landley81b899d2007-12-18 02:02:47 -0600427<li><p>void <b>toy_init</b>(struct toy_list *which, char *argv[]) - fill out
428the global toys structure, calling get_optargs() if necessary.</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600429<li><p>void <b>toy_exec</b>(char *argv[]) - Run a built-in command with
430arguments.</p>
431<p>Calls toy_find() on argv[0] (which must be just a command name
Rob Landley4e68de12007-12-13 07:00:27 -0600432without path). Returns if it can't find this command, otherwise calls
Rob Landley6882ee82008-02-12 18:41:34 -0600433toy_init(), toys->which.toy_main(), and exit() instead of returning.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600434
Rob Landley6882ee82008-02-12 18:41:34 -0600435<p>Use the library function xexec() to fall back to external executables
436in $PATH if toy_exec() can't find a built-in command. Note that toy_exec()
437does not strip paths before searching for a command, so "./command" will
438never match an internal command.</li>
439
440<li><p>void <b>toybox_main</b>(void) - the main function for the multiplexer
441command (I.E. "toybox"). Given a command name as its first argument, calls
442toy_exec() on its arguments. With no arguments, it lists available commands.
443If the first argument starts with "-" it lists each command with its default
444install path prepended.</p></li>
Rob Landley4e68de12007-12-13 07:00:27 -0600445
446</ul>
447
448<h3>Config.in</h3>
449
450<p>Top level configuration file in a stylized variant of
Rob Landley6882ee82008-02-12 18:41:34 -0600451<a href=http://kernel.org/doc/Documentation/kbuild/kconfig-language.txt>kconfig</a> format. Includes generated/Config.in.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600452
453<p>These files are directly used by "make menuconfig" to select which commands
454to build into toybox (thus generating a .config file), and by
Rob Landley6882ee82008-02-12 18:41:34 -0600455scripts/config2help.py to create generated/help.h.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600456
Rob Landley7eaf4f52014-04-09 08:30:09 -0500457<a name="generated" />
458<h1><a href="#generated">Temporary files:</a></h1>
Rob Landley4e68de12007-12-13 07:00:27 -0600459
Rob Landley6882ee82008-02-12 18:41:34 -0600460<p>There is one temporary file in the top level source directory:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600461<ul>
462<li><p><b>.config</b> - Configuration file generated by kconfig, indicating
463which commands (and options to commands) are currently enabled. Used
Rob Landley7eaf4f52014-04-09 08:30:09 -0500464to make generated/config.h and determine which toys/*/*.c files to build.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600465
Rob Landley6882ee82008-02-12 18:41:34 -0600466<p>You can create a human readable "miniconfig" version of this file using
Rob Landley66a69d92012-01-16 01:44:17 -0600467<a href=http://landley.net/aboriginal/new_platform.html#miniconfig>these
Rob Landley6882ee82008-02-12 18:41:34 -0600468instructions</a>.</p>
469</li>
470</ul>
471
Rob Landley7eaf4f52014-04-09 08:30:09 -0500472<p><h2>Directory generated/</h2></p>
473
474<p>The remaining temporary files live in the "generated/" directory,
475which is for files generated at build time from other source files.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600476
477<ul>
Rob Landley7eaf4f52014-04-09 08:30:09 -0500478<li><p><b>generated/Config.in</b> - Included from the top level Config.in,
479contains one or more configuration entries for each command.</p>
480
481<p>Each command has a configuration entry with an upper case version of
482the command name. Options to commands start with the command
483name followed by an underscore and the option name. Global options are attached
484to the "toybox" command, and thus use the prefix "TOYBOX_". This organization
485is used by scripts/cfg2files to select which toys/*/*.c files to compile for a
486given .config.</p>
487
488<p>A command with multiple names (or multiple similar commands implemented in
489the same .c file) should have config symbols prefixed with the name of their
490C file. I.E. config symbol prefixes are NEWTOY() names. If OLDTOY() names
491have config symbols they must be options (symbols with an underscore and
492suffix) to the NEWTOY() name. (See generated/toylist.h)</p>
493</li>
494
Rob Landley6882ee82008-02-12 18:41:34 -0600495<li><p><b>generated/config.h</b> - list of CFG_SYMBOL and USE_SYMBOL() macros,
Rob Landley4e68de12007-12-13 07:00:27 -0600496generated from .config by a sed invocation in the top level Makefile.</p>
497
498<p>CFG_SYMBOL is a comple time constant set to 1 for enabled symbols and 0 for
Rob Landley7eaf4f52014-04-09 08:30:09 -0500499disabled symbols. This allows the use of normal if() statements to remove
Rob Landley6882ee82008-02-12 18:41:34 -0600500code at compile time via the optimizer's dead code elimination (which removes
Rob Landley7eaf4f52014-04-09 08:30:09 -0500501from the binary any code that cannot be reached). This saves space without
Rob Landley4e68de12007-12-13 07:00:27 -0600502cluttering the code with #ifdefs or leading to configuration dependent build
Rob Landley7eaf4f52014-04-09 08:30:09 -0500503breaks. (See the 1992 Usenix paper
Rob Landleyb6063de2012-01-29 13:54:13 -0600504<a href=http://doc.cat-v.org/henry_spencer/ifdef_considered_harmful.pdf>#ifdef
Rob Landley4e68de12007-12-13 07:00:27 -0600505Considered Harmful</a> for more information.)</p>
506
507<p>USE_SYMBOL(code) evaluates to the code in parentheses when the symbol
Rob Landley7eaf4f52014-04-09 08:30:09 -0500508is enabled, and nothing when the symbol is disabled. This can be used
Rob Landley4e68de12007-12-13 07:00:27 -0600509for things like varargs or variable declarations which can't always be
Rob Landley7eaf4f52014-04-09 08:30:09 -0500510eliminated by a simple test on CFG_SYMBOL. Note that
Rob Landley4e68de12007-12-13 07:00:27 -0600511(unlike CFG_SYMBOL) this is really just a variant of #ifdef, and can
Rob Landley7eaf4f52014-04-09 08:30:09 -0500512still result in configuration dependent build breaks. Use with caution.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600513</li>
Rob Landley4e68de12007-12-13 07:00:27 -0600514
Rob Landley7eaf4f52014-04-09 08:30:09 -0500515<li><p><b>generated/flags.h</b> - FLAG_? macros indicating which command
516line options were seen. The option parsing in lib/args.c sets bits in
517toys.optflags, which can be tested by anding with the appropriate FLAG_
518macro. (Bare longopts, which have no corresponding short option, will
519have the longopt name after FLAG_. All others use the single letter short
520option.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600521
Rob Landley7eaf4f52014-04-09 08:30:09 -0500522<p>To get the appropriate macros for your command, #define FOR_commandname
523before #including toys.h. To switch macro sets (because you have an OLDTOY()
524with different options in the same .c file), #define CLEANUP_oldcommand
525and also #define FOR_newcommand, then #include "generated/flags.h" to switch.
526</p>
527</li>
Rob Landley4e68de12007-12-13 07:00:27 -0600528
Rob Landley7eaf4f52014-04-09 08:30:09 -0500529<li><p><b>generated/globals.h</b> -
530Declares structures to hold the contents of each command's GLOBALS(),
531and combines them into "global_union this". (Yes, the name was
532chosen to piss off C++ developers who think that C
533is merely a subset of C++, not a language in its own right.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600534
Rob Landley7eaf4f52014-04-09 08:30:09 -0500535<p>The union reuses the same memory for each command's global struct:
536since only one command's globals are in use at any given time, collapsing
537them together saves space. The headers #define TT to the appropriate
538"this.commandname", so you can refer to the current command's global
539variables out of "this" as TT.variablename.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600540
Rob Landley7eaf4f52014-04-09 08:30:09 -0500541<p>The globals start zeroed, and the first few are filled out by the
542lib/args.c argument parsing code called from main.c.</p>
543</li>
Rob Landley4e68de12007-12-13 07:00:27 -0600544
Rob Landley7eaf4f52014-04-09 08:30:09 -0500545<li><p><b>toys/help.h</b> -
546#defines two help text strings for each command: a single line
Rob Landley4e68de12007-12-13 07:00:27 -0600547command_help and an additinal command_help_long. This is used by help_main()
548in toys/help.c to display help for commands.</p>
549
Rob Landley7eaf4f52014-04-09 08:30:09 -0500550<p>This file is created by scripts/make.sh, which compiles scripts/config2help.c
551into the binary generated/config2help, and then runs it against the top
552level .config and Config.in files to extract the help text from each config
553entry and collate together dependent options.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600554
Rob Landley7eaf4f52014-04-09 08:30:09 -0500555<p>This file contains help text for all commands, regardless of current
556configuration, but only the ones currently enabled in the .config file
557wind up in the help_data[] array, and only the enabled dependent options
558have their help text added to the command they depend on.</p>
559</li>
560
561<li><p><b>generated/newtoys.h</b> -
562All the NEWTOY() and OLDTOY() macros in alphabetical order,
563each of which should be inside the appropriate USE_ macro. (Ok, not _quite_
564alphabetical orer: the "toybox" multiplexer is always the first entry.)</p>
565
566<p>By #definining NEWTOY() to various things before #including this file,
567it may be used to create function prototypes (in toys.h), initialize the
568toy_list array (in main.c, the alphabetical order lets toy_find() do a
569binary search), initialize the help_data array (in lib/help.c), and so on.
570(It's even used to initialize the NEED_OPTIONS macro, which is has a 1 or 0
571for each command using command line option parsing, ORed together.
572This allows compile-time dead code elimination to remove the whole of
573lib/args.c if nothing currently enabled is using it.)<p>
574
575<p>Each NEWTOY and OLDTOY macro contains the command name, command line
576option string (telling lib/args.c how to parse command line options for
577this command), recommended install location, and miscelaneous data such
578as whether this command should retain root permissions if installed suid.</p>
579</li>
580
581<li><p><b>toys/oldtoys.h</b> - Macros with the command line option parsing
582string for each NEWTOY. This allows an OLDTOY that's just an alias for an
583existing command to refer to the existing option string instead of
584having to repeat it.</p>
585</li>
586</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600587
Rob Landley137bf342012-03-09 08:33:57 -0600588<a name="lib">
Rob Landley81b899d2007-12-18 02:02:47 -0600589<h2>Directory lib/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600590
Rob Landley137bf342012-03-09 08:33:57 -0600591<p>TODO: document lots more here.</p>
592
Rob Landleyc8d0da52012-07-15 17:47:08 -0500593<p>lib: getmountlist(), error_msg/error_exit, xmalloc(),
Rob Landley7c04f012008-01-20 19:00:16 -0600594strlcpy(), xexec(), xopen()/xread(), xgetcwd(), xabspath(), find_in_path(),
595itoa().</p>
596
Rob Landley137bf342012-03-09 08:33:57 -0600597<h3>lib/portability.h</h3>
598
599<p>This file is automatically included from the top of toys.h, and smooths
600over differences between platforms (hardware targets, compilers, C libraries,
601operating systems, etc).</p>
602
603<p>This file provides SWAP macros (SWAP_BE16(x) and SWAP_LE32(x) and so on).</p>
604
605<p>A macro like SWAP_LE32(x) means "The value in x is stored as a little
606endian 32 bit value, so perform the translation to/from whatever the native
60732-bit format is". You do the swap once on the way in, and once on the way
608out. If your target is already little endian, the macro is a NOP.</p>
609
610<p>The SWAP macros come in BE and LE each with 16, 32, and 64 bit versions.
611In each case, the name of the macro refers to the _external_ representation,
612and converts to/from whatever your native representation happens to be (which
613can vary depending on what you're currently compiling for).</p>
614
Rob Landleyc8d0da52012-07-15 17:47:08 -0500615<a name="lib_llist"><h3>lib/llist.c</h3>
616
617<p>Some generic single and doubly linked list functions, which take
618advantage of a couple properties of C:</p>
619
620<ul>
621<li><p>Structure elements are laid out in memory in the order listed, and
622the first element has no padding. This means you can always treat (typecast)
623a pointer to a structure as a pointer to the first element of the structure,
624even if you don't know anything about the data following it.</p></li>
625
626<li><p>An array of length zero at the end of a structure adds no space
627to the sizeof() the structure, but if you calculate how much extra space
628you want when you malloc() the structure it will be available at the end.
629Since C has no bounds checking, this means each struct can have one variable
630length array.</p></li>
631</ul>
632
633<p>Toybox's list structures always have their <b>next</b> pointer as
634the first entry of each struct, and singly linked lists end with a NULL pointer.
635This allows generic code to traverse such lists without knowing anything
636else about the specific structs composing them: if your pointer isn't NULL
637typecast it to void ** and dereference once to get the next entry.</p>
638
639<p><b>lib/lib.h</b> defines three structure types:</p>
640<ul>
641<li><p><b>struct string_list</b> - stores a single string (<b>char str[0]</b>),
642memory for which is allocated as part of the node. (I.E. llist_traverse(list,
643free); can clean up after this type of list.)</p></li>
644
645<li><p><b>struct arg_list</b> - stores a pointer to a single string
646(<b>char *arg</b>) which is stored in a separate chunk of memory.</p></li>
647
648<li><p><b>struct double_list</b> - has a second pointer (<b>struct double_list
649*prev</b> along with a <b>char *data</b> for payload.</p></li>
650</ul>
651
652<b>List Functions</b>
653
654<ul>
655<li><p>void *<b>llist_pop</b>(void **list) - advances through a list ala
656<b>node = llist_pop(&list);</b> This doesn't modify the list contents,
657but does advance the pointer you feed it (which is why you pass the _address_
658of that pointer, not the pointer itself).</p></li>
659
660<li><p>void <b>llist_traverse</b>(void *list, void (*using)(void *data)) -
661iterate through a list calling a function on each node.</p></li>
662
663<li><p>struct double_list *<b>dlist_add</b>(struct double_list **llist, char *data)
664- append an entry to a circular linked list.
665This function allocates a new struct double_list wrapper and returns the
666pointer to the new entry (which you can usually ignore since it's llist->prev,
667but if llist was NULL you need it). The argument is the ->data field for the
668new node.</p></li>
669<ul><li><p>void <b>dlist_add_nomalloc</b>(struct double_list **llist,
670struct double_list *new) - append existing struct double_list to
671list, does not allocate anything.</p></li></ul>
672</ul>
673
Rob Landley7eaf4f52014-04-09 08:30:09 -0500674<b>List code trivia questions:</b>
Rob Landleyc8d0da52012-07-15 17:47:08 -0500675
676<ul>
677<li><p><b>Why do arg_list and double_list contain a char * payload instead of
678a void *?</b> - Because you always have to typecast a void * to use it, and
Rob Landley7eaf4f52014-04-09 08:30:09 -0500679typecasting a char * does no harm. Since strings are the most common
680payload, and doing math on the pointer ala
681"(type *)(ptr+sizeof(thing)+sizeof(otherthing))" requires ptr to be char *
682anyway (at least according to the C standard), defaulting to char * saves
683a typecast.</p>
Rob Landleyc8d0da52012-07-15 17:47:08 -0500684</li>
685
686<li><p><b>Why do the names ->str, ->arg, and ->data differ?</b> - To force
687you to keep track of which one you're using, calling free(node->str) would
688be bad, and _failing_ to free(node->arg) leaks memory.</p></li>
689
690<li><p><b>Why does llist_pop() take a void * instead of void **?</b> -
691because the stupid compiler complains about "type punned pointers" when
Rob Landley7eaf4f52014-04-09 08:30:09 -0500692you typecast and dereference on the same line,
Rob Landleyc8d0da52012-07-15 17:47:08 -0500693due to insane FSF developers hardwiring limitations of their optimizer
694into gcc's warning system. Since C automatically typecasts any other
Rob Landley7eaf4f52014-04-09 08:30:09 -0500695pointer type to and from void *, the current code works fine. It's sad that it
Rob Landleyc8d0da52012-07-15 17:47:08 -0500696won't warn you if you forget the &, but the code crashes pretty quickly in
697that case.</p></li>
698
699<li><p><b>How do I assemble a singly-linked-list in order?</b> - use
700a double_list, dlist_add() your entries, and then break the circle with
701<b>list->prev->next = NULL;</b> when done.</li>
702</ul>
703
Rob Landley66a69d92012-01-16 01:44:17 -0600704<a name="lib_args"><h3>lib/args.c</h3>
Rob Landley7c04f012008-01-20 19:00:16 -0600705
Rob Landley66a69d92012-01-16 01:44:17 -0600706<p>Toybox's main.c automatically parses command line options before calling the
707command's main function. Option parsing starts in get_optflags(), which stores
708results in the global structures "toys" (optflags and optargs) and "this".</p>
709
710<p>The option parsing infrastructure stores a bitfield in toys.optflags to
711indicate which options the current command line contained. Arguments
712attached to those options are saved into the command's global structure
713("this"). Any remaining command line arguments are collected together into
714the null-terminated array toys.optargs, with the length in toys.optc. (Note
715that toys.optargs does not contain the current command name at position zero,
716use "toys.which->name" for that.) The raw command line arguments get_optflags()
717parsed are retained unmodified in toys.argv[].</p>
718
719<p>Toybox's option parsing logic is controlled by an "optflags" string, using
720a format reminiscent of getopt's optargs but has several important differences.
721Toybox does not use the getopt()
722function out of the C library, get_optflags() is an independent implementation
723which doesn't permute the original arguments (and thus doesn't change how the
724command is displayed in ps and top), and has many features not present in
725libc optargs() (such as the ability to describe long options in the same string
726as normal options).</p>
727
728<p>Each command's NEWTOY() macro has an optflags string as its middle argument,
729which sets toy_list.options for that command to tell get_optflags() what
730command line arguments to look for, and what to do with them.
731If a command has no option
732definition string (I.E. the argument is NULL), option parsing is skipped
733for that command, which must look at the raw data in toys.argv to parse its
734own arguments. (If no currently enabled command uses option parsing,
735get_optflags() is optimized out of the resulting binary by the compiler's
736--gc-sections option.)</p>
737
738<p>You don't have to free the option strings, which point into the environment
739space (I.E. the string data is not copied). A TOYFLAG_NOFORK command
740that uses the linked list type "*" should free the list objects but not
741the data they point to, via "llist_free(TT.mylist, NULL);". (If it's not
742NOFORK, exit() will free all the malloced data anyway unless you want
743to implement a CONFIG_TOYBOX_FREE cleanup for it.)</p>
744
745<h4>Optflags format string</h4>
746
747<p>Note: the optflags option description string format is much more
748concisely described by a large comment at the top of lib/args.c.</p>
749
750<p>The general theory is that letters set optflags, and punctuation describes
751other actions the option parsing logic should take.</p>
752
753<p>For example, suppose the command line <b>command -b fruit -d walrus -a 42</b>
754is parsed using the optflags string "<b>a#b:c:d</b>". (I.E.
755toys.which->options="a#b:c:d" and argv = ["command", "-b", "fruit", "-d",
756"walrus", "-a", "42"]). When get_optflags() returns, the following data is
757available to command_main():
758
759<ul>
760<li><p>In <b>struct toys</b>:
761<ul>
762<li>toys.optflags = 13; // -a = 8 | -b = 4 | -d = 1</li>
763<li>toys.optargs[0] = "walrus"; // leftover argument</li>
764<li>toys.optargs[1] = NULL; // end of list</li>
Rob Landleyb911d4d2013-09-21 14:27:26 -0500765<li>toys.optc = 1; // there was 1 leftover argument</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600766<li>toys.argv[] = {"-b", "fruit", "-d", "walrus", "-a", "42"}; // The original command line arguments
767</ul>
768<p></li>
769
770<li><p>In <b>union this</b> (treated as <b>long this[]</b>):
771<ul>
772<li>this[0] = NULL; // -c didn't get an argument this time, so get_optflags() didn't change it and toys_init() zeroed "this" during setup.)</li>
773<li>this[1] = (long)"fruit"; // argument to -b</li>
774<li>this[2] = 42; // argument to -a</li>
775</ul>
776</p></li>
777</ul>
778
779<p>If the command's globals are:</p>
780
781<blockquote><pre>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500782GLOBALS(
Rob Landley66a69d92012-01-16 01:44:17 -0600783 char *c;
784 char *b;
785 long a;
786)
Rob Landley66a69d92012-01-16 01:44:17 -0600787</pre></blockquote>
788<p>That would mean TT.c == NULL, TT.b == "fruit", and TT.a == 42. (Remember,
789each entry that receives an argument must be a long or pointer, to line up
790with the array position. Right to left in the optflags string corresponds to
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500791top to bottom in GLOBALS().</p>
Rob Landley66a69d92012-01-16 01:44:17 -0600792
Rob Landleyb911d4d2013-09-21 14:27:26 -0500793<p>Put globals not filled out by the option parsing logic at the end of the
794GLOBALS block. Common practice is to list the options one per line (to
795make the ordering explicit, first to last in globals corresponds to right
796to left in the option string), then leave a blank line before any non-option
797globals.</p>
798
Rob Landley66a69d92012-01-16 01:44:17 -0600799<p><b>long toys.optflags</b></p>
800
801<p>Each option in the optflags string corresponds to a bit position in
802toys.optflags, with the same value as a corresponding binary digit. The
803rightmost argument is (1<<0), the next to last is (1<<1) and so on. If
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600804the option isn't encountered while parsing argv[], its bit remains 0.</p>
805
806<p>For example,
Rob Landley66a69d92012-01-16 01:44:17 -0600807the optflags string "abcd" would parse the command line argument "-c" to set
808optflags to 2, "-a" would set optflags to 8, "-bd" would set optflags to
8096 (I.E. 4|2), and "-a -c" would set optflags to 10 (2|8).</p>
810
811<p>Only letters are relevant to optflags, punctuation is skipped: in the
812string "a*b:c#d", d=1, c=2, b=4, a=8. The punctuation after a letter
813usually indicate that the option takes an argument.</p>
814
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600815<p>Since toys.optflags is an unsigned int, it only stores 32 bits. (Which is
816the amount a long would have on 32-bit platforms anyway; 64 bit code on
81732 bit platforms is too expensive to require in common code used by almost
818all commands.) Bit positions beyond the 1<<31 aren't recorded, but
819parsing higher options can still set global variables.</p>
820
Rob Landley66a69d92012-01-16 01:44:17 -0600821<p><b>Automatically setting global variables from arguments (union this)</b></p>
822
823<p>The following punctuation characters may be appended to an optflags
824argument letter, indicating the option takes an additional argument:</p>
825
826<ul>
827<li><b>:</b> - plus a string argument, keep most recent if more than one.</li>
828<li><b>*</b> - plus a string argument, appended to a linked list.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600829<li><b>@</b> - plus an occurrence counter (stored in a long)</li>
Rob Landleyb6063de2012-01-29 13:54:13 -0600830<li><b>#</b> - plus a signed long argument.
Rob Landleyb911d4d2013-09-21 14:27:26 -0500831<li><b>-</b> - plus a signed long argument defaulting to negative (start argument with + to force a positive value).</li>
Rob Landleyb6063de2012-01-29 13:54:13 -0600832<li><b>.</b> - plus a floating point argument (if CFG_TOYBOX_FLOAT).</li>
833<ul>The following can be appended to a float or double:
834<li><b>&lt;123</b> - error if argument is less than this</li>
835<li><b>&gt;123</b> - error if argument is greater than this</li>
836<li><b>=123</b> - default value if argument not supplied</li>
837</ul>
Rob Landley66a69d92012-01-16 01:44:17 -0600838</ul>
839
Rob Landleyb911d4d2013-09-21 14:27:26 -0500840<p>A note about "." and CFG_TOYBOX_FLOAT: option parsing only understands <>=
841after . when CFG_TOYBOX_FLOAT
842is enabled. (Otherwise the code to determine where floating point constants
843end drops out; it requires floating point). When disabled, it can reserve a
844global data slot for the argument (so offsets won't change in your
845GLOBALS[] block), but will never fill it out. You can handle
846this by using the USE_BLAH() macros with C string concatenation, ala:
847"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</p>
848
849<p><b>GLOBALS</b></p>
Rob Landley66a69d92012-01-16 01:44:17 -0600850
851<p>Options which have an argument fill in the corresponding slot in the global
852union "this" (see generated/globals.h), treating it as an array of longs
Rob Landleyb911d4d2013-09-21 14:27:26 -0500853with the rightmost saved in this[0]. As described above, using "a*b:c#d",
854"-c 42" would set this[0] = 42; and "-b 42" would set this[1] = "42"; each
855slot is left NULL if the corresponding argument is not encountered.</p>
Rob Landley66a69d92012-01-16 01:44:17 -0600856
857<p>This behavior is useful because the LP64 standard ensures long and pointer
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600858are the same size. C99 guarantees structure members will occur in memory
859in the same order they're declared, and that padding won't be inserted between
Rob Landley66a69d92012-01-16 01:44:17 -0600860consecutive variables of register size. Thus the first few entries can
861be longs or pointers corresponding to the saved arguments.</p>
862
Rob Landleyb911d4d2013-09-21 14:27:26 -0500863<p>See toys/other/hello.c for a longer example of parsing options into the
864GLOBALS block.</p>
865
Rob Landley66a69d92012-01-16 01:44:17 -0600866<p><b>char *toys.optargs[]</b></p>
867
868<p>Command line arguments in argv[] which are not consumed by option parsing
869(I.E. not recognized either as -flags or arguments to -flags) will be copied
870to toys.optargs[], with the length of that array in toys.optc.
871(When toys.optc is 0, no unrecognized command line arguments remain.)
872The order of entries is preserved, and as with argv[] this new array is also
873terminated by a NULL entry.</p>
874
875<p>Option parsing can require a minimum or maximum number of optargs left
876over, by adding "<1" (read "at least one") or ">9" ("at most nine") to the
877start of the optflags string.</p>
878
879<p>The special argument "--" terminates option parsing, storing all remaining
880arguments in optargs. The "--" itself is consumed.</p>
881
882<p><b>Other optflags control characters</b></p>
883
884<p>The following characters may occur at the start of each command's
885optflags string, before any options that would set a bit in toys.optflags:</p>
886
887<ul>
888<li><b>^</b> - stop at first nonoption argument (for nice, xargs...)</li>
889<li><b>?</b> - allow unknown arguments (pass non-option arguments starting
890with - through to optargs instead of erroring out).</li>
891<li><b>&amp;</b> - the first argument has imaginary dash (ala tar/ps. If given twice, all arguments have imaginary dash.)</li>
892<li><b>&lt;</b> - must be followed by a decimal digit indicating at least this many leftover arguments are needed in optargs (default 0)</li>
893<li><b>&gt;</b> - must be followed by a decimal digit indicating at most this many leftover arguments allowed (default MAX_INT)</li>
894</ul>
895
896<p>The following characters may be appended to an option character, but do
897not by themselves indicate an extra argument should be saved in this[].
898(Technically any character not recognized as a control character sets an
899optflag, but letters are never control characters.)</p>
900
901<ul>
902<li><b>^</b> - stop parsing options after encountering this option, everything else goes into optargs.</li>
903<li><b>|</b> - this option is required. If more than one marked, only one is required.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600904</ul>
905
Rob Landleyb6063de2012-01-29 13:54:13 -0600906<p>The following may be appended to a float or double:</p>
907
908<ul>
909<li><b>&lt;123</b> - error if argument is less than this</li>
910<li><b>&gt;123</b> - error if argument is greater than this</li>
911<li><b>=123</b> - default value if argument not supplied</li>
912</ul>
913
914<p>Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT
915is enabled. (Otherwise the code to determine where floating point constants
916end drops out. When disabled, it can reserve a global data slot for the
917argument so offsets won't change, but will never fill it out.). You can handle
918this by using the USE_BLAH() macros with C string concatenation, ala:</p>
919
920<blockquote>"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</blockquote>
921
Rob Landley66a69d92012-01-16 01:44:17 -0600922<p><b>--longopts</b></p>
923
924<p>The optflags string can contain long options, which are enclosed in
925parentheses. They may be appended to an existing option character, in
926which case the --longopt is a synonym for that option, ala "a:(--fred)"
927which understands "-a blah" or "--fred blah" as synonyms.</p>
928
929<p>Longopts may also appear before any other options in the optflags string,
930in which case they have no corresponding short argument, but instead set
931their own bit based on position. So for "(walrus)#(blah)xy:z" "command
932--walrus 42" would set toys.optflags = 16 (-z = 1, -y = 2, -x = 4, --blah = 8)
933and would assign this[1] = 42;</p>
934
935<p>A short option may have multiple longopt synonyms, "a(one)(two)", but
936each "bare longopt" (ala "(one)(two)abc" before any option characters)
937always sets its own bit (although you can group them with +X).</p>
Rob Landley7c04f012008-01-20 19:00:16 -0600938
Rob Landleyb911d4d2013-09-21 14:27:26 -0500939<p><b>[groups]</b></p>
940
941<p>At the end of the option string, square bracket groups can define
942relationships between existing options. (This only applies to short
943options, bare --longopts can't participate.)</p>
944
945<p>The first character of the group defines the type, the remaining
946characters are options it applies to:</p>
947
948<ul>
949<li><b>-</b> - Exclusive, switch off all others in this group.</li>
950<li><b>+</b> - Inclusive, switch on all others in this group.</li>
951<li><b>!</b> - Error, fail if more than one defined.</li>
952</ul>
953
954<p>So "abc[-abc]" means -ab = -b, -ba = -a, -abc = -c. "abc[+abc]"
955means -ab=-abc, -c=-abc, and "abc[!abc] means -ab calls error_exit("no -b
956with -a"). Note that [-] groups clear the GLOBALS option slot of
957options they're switching back off, but [+] won't set options it didn't see
958(just the optflags).</p>
959
960<p><b>whitespace</b></p>
961
962<p>Arguments may occur with or without a space (I.E. "-a 42" or "-a42").
963The command line argument "-abc" may be interepreted many different ways:
964the optflags string "cba" sets toys.optflags = 7, "c:ba" sets toys.optflags=4
965and saves "ba" as the argument to -c, and "cb:a" sets optflags to 6 and saves
966"c" as the argument to -b.</p>
967
968<p>Note that &amp; changes whitespace handling, so that the command line
969"tar cvfCj outfile.tar.bz2 topdir filename" is parsed the same as
970"tar filename -c -v -j -f outfile.tar.bz2 -C topdir". Note that "tar -cvfCj
971one two three" would equal "tar -c -v -f Cj one two three". (This matches
972historical usage.)</p>
973
974<p>Appending a space to the option in the option string ("a: b") makes it
975require a space, I.E. "-ab" is interpreted as "-a" "-b". That way "kill -stop"
976differs from "kill -s top".</p>
977
978<p>Appending ; to a longopt in the option string makes its argument optional,
979and only settable with =, so in ls "(color):;" can accept "ls --color" and
980"ls --color=auto" without complaining that the first has no argument.</p>
981
Rob Landleyc8d0da52012-07-15 17:47:08 -0500982<a name="lib_dirtree"><h3>lib/dirtree.c</h3>
983
984<p>The directory tree traversal code should be sufficiently generic
985that commands never need to use readdir(), scandir(), or the fts.h family
986of functions.</p>
987
988<p>These functions do not call chdir() or rely on PATH_MAX. Instead they
989use openat() and friends, using one filehandle per directory level to
990recurseinto subdirectories. (I.E. they can descend 1000 directories deep
991if setrlimit(RLIMIT_NOFILE) allows enough open filehandles, and the default
992in /proc/self/limits is generally 1024.)</p>
993
994<p>The basic dirtree functions are:</p>
995
996<ul>
997<li><p><b>dirtree_read(char *path, int (*callback)(struct dirtree node))</b> -
998recursively read directories, either applying callback() or returning
999a tree of struct dirtree if callback is NULL.</p></li>
1000
1001<li><p><b>dirtree_path(struct dirtree *node, int *plen)</b> - malloc() a
1002string containing the path from the root of this tree to this node. If
1003plen isn't NULL then *plen is how many extra bytes to malloc at the end
1004of string.</p></li>
1005
1006<li><p><b>dirtree_parentfd(struct dirtree *node)</b> - return fd of
1007containing directory, for use with openat() and such.</p></li>
1008</ul>
1009
1010<p>The <b>dirtree_read()</b> function takes two arguments, a starting path for
1011the root of the tree, and a callback function. The callback takes a
1012<b>struct dirtree *</b> (from lib/lib.h) as its argument. If the callback is
1013NULL, the traversal uses a default callback (dirtree_notdotdot()) which
1014recursively assembles a tree of struct dirtree nodes for all files under
1015this directory and subdirectories (filtering out "." and ".." entries),
1016after which dirtree_read() returns the pointer to the root node of this
1017snapshot tree.</p>
1018
1019<p>Otherwise the callback() is called on each entry in the directory,
1020with struct dirtree * as its argument. This includes the initial
1021node created by dirtree_read() at the top of the tree.</p>
1022
1023<p><b>struct dirtree</b></p>
1024
1025<p>Each struct dirtree node contains <b>char name[]</b> and <b>struct stat
1026st</b> entries describing a file, plus a <b>char *symlink</b>
1027which is NULL for non-symlinks.</p>
1028
1029<p>During a callback function, the <b>int data</b> field of directory nodes
1030contains a dirfd (for use with the openat() family of functions). This is
1031generally used by calling dirtree_parentfd() on the callback's node argument.
1032For symlinks, data contains the length of the symlink string. On the second
1033callback from DIRTREE_COMEAGAIN (depth-first traversal) data = -1 for
1034all nodes (that's how you can tell it's the second callback).</p>
1035
1036<p>Users of this code may put anything they like into the <b>long extra</b>
1037field. For example, "cp" and "mv" use this to store a dirfd for the destination
1038directory (and use DIRTREE_COMEAGAIN to get the second callback so they can
1039close(node->extra) to avoid running out of filehandles).
1040This field is not directly used by the dirtree code, and
1041thanks to LP64 it's large enough to store a typecast pointer to an
1042arbitrary struct.</p>
1043
1044<p>The return value of the callback combines flags (with boolean or) to tell
1045the traversal infrastructure how to behave:</p>
1046
1047<ul>
1048<li><p><b>DIRTREE_SAVE</b> - Save this node, assembling a tree. (Without
1049this the struct dirtree is freed after the callback returns. Filtering out
1050siblings is fine, but discarding a parent while keeping its child leaks
1051memory.)</p></li>
1052<li><p><b>DIRTREE_ABORT</b> - Do not examine any more entries in this
1053directory. (Does not propagate up tree: to abort entire traversal,
1054return DIRTREE_ABORT from parent callbacks too.)</p></li>
1055<li><p><b>DIRTREE_RECURSE</b> - Examine directory contents. Ignored for
1056non-directory entries. The remaining flags only take effect when
1057recursing into the children of a directory.</p></li>
1058<li><p><b>DIRTREE_COMEAGAIN</b> - Call the callback a second time after
1059examining all directory contents, allowing depth-first traversal.
1060On the second call, dirtree->data = -1.</p></li>
1061<li><p><b>DIRTREE_SYMFOLLOW</b> - follow symlinks when populating children's
1062<b>struct stat st</b> (by feeding a nonzero value to the symfollow argument of
1063dirtree_add_node()), which means DIRTREE_RECURSE treats symlinks to
1064directories as directories. (Avoiding infinite recursion is the callback's
1065problem: the non-NULL dirtree->symlink can still distinguish between
1066them.)</p></li>
1067</ul>
1068
1069<p>Each struct dirtree contains three pointers (next, parent, and child)
1070to other struct dirtree.</p>
1071
1072<p>The <b>parent</b> pointer indicates the directory
1073containing this entry; even when not assembling a persistent tree of
1074nodes the parent entries remain live up to the root of the tree while
1075child nodes are active. At the top of the tree the parent pointer is
1076NULL, meaning the node's name[] is either an absolute path or relative
1077to cwd. The function dirtree_parentfd() gets the directory file descriptor
1078for use with openat() and friends, returning AT_FDCWD at the top of tree.</p>
1079
1080<p>The <b>child</b> pointer points to the first node of the list of contents of
1081this directory. If the directory contains no files, or the entry isn't
1082a directory, child is NULL.</p>
1083
1084<p>The <b>next</b> pointer indicates sibling nodes in the same directory as this
1085node, and since it's the first entry in the struct the llist.c traversal
1086mechanisms work to iterate over sibling nodes. Each dirtree node is a
1087single malloc() (even char *symlink points to memory at the end of the node),
1088so llist_free() works but its callback must descend into child nodes (freeing
1089a tree, not just a linked list), plus whatever the user stored in extra.</p>
1090
1091<p>The <b>dirtree_read</b>() function is a simple wrapper, calling <b>dirtree_add_node</b>()
1092to create a root node relative to the current directory, then calling
1093<b>handle_callback</b>() on that node (which recurses as instructed by the callback
1094return flags). Some commands (such as chgrp) bypass this wrapper, for example
1095to control whether or not to follow symlinks to the root node; symlinks
1096listed on the command line are often treated differently than symlinks
1097encountered during recursive directory traversal).
1098
1099<p>The ls command not only bypasses the wrapper, but never returns
1100<b>DIRTREE_RECURSE</b> from the callback, instead calling <b>dirtree_recurse</b>() manually
1101from elsewhere in the program. This gives ls -lR manual control
1102of traversal order, which is neither depth first nor breadth first but
1103instead a sort of FIFO order requried by the ls standard.</p>
1104
Rob Landley7eaf4f52014-04-09 08:30:09 -05001105<a name="toys">
1106<h1><a href="#toys">Directory toys/</a></h1>
Rob Landleyc0e56ed2012-10-08 00:02:30 -05001107
1108<p>This directory contains command implementations. Each command is a single
1109self-contained file. Adding a new command involves adding a single
1110file, and removing a command involves removing that file. Commands use
1111shared infrastructure from the lib/ and generated/ directories.</p>
1112
1113<p>Currently there are three subdirectories under "toys/" containing commands
1114described in POSIX-2008, the Linux Standard Base 4.1, or "other". The only
1115difference this makes is which menu the command shows up in during "make
1116menuconfig", the directories are otherwise identical. Note that they commands
1117exist within a single namespace at runtime, so you can't have the same
1118command in multiple subdirectories.</p>
1119
1120<p>(There are actually four sub-menus in "make menuconfig", the fourth
1121contains global configuration options for toybox, and lives in Config.in at
1122the top level.)</p>
1123
1124<p>See <a href="#adding">adding a new command</a> for details on the
1125layout of a command file.</p>
1126
Rob Landley81b899d2007-12-18 02:02:47 -06001127<h2>Directory scripts/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -06001128
Rob Landley1f4f41a2012-10-08 21:31:07 -05001129<p>Build infrastructure. The makefile calls scripts/make.sh for "make"
1130and scripts/install.sh for "make install".</p>
1131
1132<p>There's also a test suite, "make test" calls make/test.sh, which runs all
1133the tests in make/test/*. You can run individual tests via
1134"scripts/test.sh command", or "TEST_HOST=1 scripts/test.sh command" to run
1135that test against the host implementation instead of the toybox one.</p>
1136
Rob Landley4e68de12007-12-13 07:00:27 -06001137<h3>scripts/cfg2files.sh</h3>
1138
1139<p>Run .config through this filter to get a list of enabled commands, which
1140is turned into a list of files in toys via a sed invocation in the top level
1141Makefile.
1142</p>
1143
Rob Landley81b899d2007-12-18 02:02:47 -06001144<h2>Directory kconfig/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -06001145
1146<p>Menuconfig infrastructure copied from the Linux kernel. See the
1147Linux kernel's Documentation/kbuild/kconfig-language.txt</p>
1148
Rob Landley66a69d92012-01-16 01:44:17 -06001149<a name="generated">
1150<h2>Directory generated/</h2>
1151
1152<p>All the files in this directory except the README are generated by the
Rob Landleyca733922014-05-19 18:24:35 -05001153build. (See scripts/make.sh)</p>
Rob Landley66a69d92012-01-16 01:44:17 -06001154
1155<ul>
1156<li><p><b>config.h</b> - CFG_COMMAND and USE_COMMAND() macros set by menuconfig via .config.</p></li>
1157
1158<li><p><b>Config.in</b> - Kconfig entries for each command. Included by top level Config.in. The help text in here is used to generated help.h</p></li>
1159
1160<li><p><b>help.h</b> - Help text strings for use by "help" command. Building
1161this file requires python on the host system, so the prebuilt file is shipped
1162in the build tarball to avoid requiring python to build toybox.</p></li>
1163
1164<li><p><b>newtoys.h</b> - List of NEWTOY() or OLDTOY() macros for all available
1165commands. Associates command_main() functions with command names, provides
1166option string for command line parsing (<a href="#lib_args">see lib/args.c</a>),
1167specifies where to install each command and whether toysh should fork before
1168calling it.</p></li>
1169</ul>
1170
1171<p>Everything in this directory is a derivative file produced from something
1172else. The entire directory is deleted by "make distclean".</p>
Rob Landleyca733922014-05-19 18:24:35 -05001173
Rob Landley4e68de12007-12-13 07:00:27 -06001174<!--#include file="footer.html" -->