blob: 73348ca049eb0373b6c5b4a1d139cd3f334b177c [file] [log] [blame]
Rob Landley4e68de12007-12-13 07:00:27 -06001<!--#include file="header.html" -->
2
Rob Landleyed6ed622012-03-06 20:49:03 -06003<p><h1>Code style</h1></p>
Rob Landleye7c9a6d2012-02-28 06:34:09 -06004
5<p>The primary goal of toybox is _simple_ code. Keeping the code small is
Rob Landleyed6ed622012-03-06 20:49:03 -06006second, with speed and lots of features coming in somewhere after that.
7(For more on that, see the <a href=design.html>design</a> page.)</p>
Rob Landleye7c9a6d2012-02-28 06:34:09 -06008
9<p>A simple implementation usually takes up fewer lines of source code,
10meaning more code can fit on the screen at once, meaning the programmer can
11see more of it on the screen and thus keep more if in their head at once.
Rob Landleyed6ed622012-03-06 20:49:03 -060012This helps code auditing and thus reduces bugs. That said, sometimes being
13more explicit is preferable to being clever enough to outsmart yourself:
14don't be so terse your code is unreadable.</p>
Rob Landley5a0660f2007-12-27 21:36:44 -060015
16<p>Toybox source is formatted to be read with 4-space tab stops. Each file
17starts with a special comment telling vi to set the tab stop to 4. Note that
18one of the bugs in Ubuntu 7.10 broke vi's ability to parse these comments; you
19must either rebuild vim from source, or go ":ts=4" yourself each time you load
20the file.</p>
21
22<p>Gotos are allowed for error handling, and for breaking out of
23nested loops. In general, a goto should only jump forward (not back), and
24should either jump to the end of an outer loop, or to error handling code
25at the end of the function. Goto labels are never indented: they override the
26block structure of the file. Putting them at the left edge makes them easy
27to spot as overrides to the normal flow of control, which they are.</p>
28
Rob Landleye7c9a6d2012-02-28 06:34:09 -060029<p><h1>Building Toybox:</h1></p>
30
31<p>Toybox is configured using the Kconfig language pioneered by the Linux
32kernel, and adopted by many other projects (uClibc, OpenEmbedded, etc).
33This generates a ".config" file containing the selected options, which
34controls which features to enable when building toybox.</p>
35
36<p>Each configuration option has a default value. The defaults indicate the
37"maximum sane configuration", I.E. if the feature defaults to "n" then it
38either isn't complete or is a special-purpose option (such as debugging
39code) that isn't intended for general purpose use.</p>
40
41<p>The standard build invocation is:</p>
42
43<ul>
44<li>make defconfig #(or menuconfig)</li>
45<li>make</li>
46<li>make install</li>
47</ul>
48
49<p>Type "make help" to see all available build options.</p>
50
51<p>The file "configure" contains a number of environment variable definitions
52which influence the build, such as specifying which compiler to use or where
53to install the resulting binaries. This file is included by the build, but
54accepts existing definitions of the environment variables, so it may be sourced
55or modified by the developer before building and the definitions exported
56to the environment will take precedence.</p>
57
58<p>(To clarify: "configure" describes the build and installation environment,
59".config" lists the features selected by defconfig/menuconfig.)</p>
Rob Landley6882ee82008-02-12 18:41:34 -060060
Rob Landley4e68de12007-12-13 07:00:27 -060061<p><h1>Infrastructure:</h1></p>
62
Rob Landley7c04f012008-01-20 19:00:16 -060063<p>The toybox source code is in following directories:</p>
64<ul>
65<li>The <a href="#top">top level directory</a> contains the file main.c (were
66execution starts), the header file toys.h (included by every command), and
67other global infrastructure.</li>
68<li>The <a href="#lib">lib directory</a> contains common functions shared by
Rob Landleyc8d0da52012-07-15 17:47:08 -050069multiple commands:</li>
70<ul>
71<li><a href="#lib_lib">lib/lib.c</a></li>
72<li><a href="#lib_llist">lib/llist.c</a></li>
73<li><a href="#lib_args">lib/args.c</a></li>
74<li><a href="#lib_dirtree">lib/dirtree.c</a></li>
75</ul>
Rob Landley7c04f012008-01-20 19:00:16 -060076<li>The <a href="#toys">toys directory</a> contains the C files implementating
Rob Landleyc0e56ed2012-10-08 00:02:30 -050077each command. Currently it contains three subdirectories:
78posix, lsb, and other.</li>
Rob Landley7c04f012008-01-20 19:00:16 -060079<li>The <a href="#scripts">scripts directory</a> contains the build and
80test infrastructure.</li>
81<li>The <a href="#kconfig">kconfig directory</a> contains the configuration
82infrastructure implementing menuconfig (copied from the Linux kernel).</li>
83<li>The <a href="#generated">generated directory</a> contains intermediate
84files generated from other parts of the source code.</li>
85</ul>
Rob Landley4e68de12007-12-13 07:00:27 -060086
Rob Landleybbe500e2012-02-26 21:53:15 -060087<a name="adding" />
Rob Landley7c04f012008-01-20 19:00:16 -060088<p><h1>Adding a new command</h1></p>
Rob Landleyc0e56ed2012-10-08 00:02:30 -050089<p>To add a new command to toybox, add a C file implementing that command under
Rob Landley7c04f012008-01-20 19:00:16 -060090the toys directory. No other files need to be modified; the build extracts
Rob Landley6882ee82008-02-12 18:41:34 -060091all the information it needs (such as command line arguments) from specially
Rob Landley7c04f012008-01-20 19:00:16 -060092formatted comments and macros in the C file. (See the description of the
Rob Landleye7c9a6d2012-02-28 06:34:09 -060093<a href="#generated">"generated" directory</a> for details.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -060094
Rob Landleyc0e56ed2012-10-08 00:02:30 -050095<p>Currently there are three subdirectories under "toys", one for commands
96defined by the POSIX standard, one for commands defined by the Linux Standard
97Base, and one for all other commands. (This is just for developer convenience
98sorting them, the directories are otherwise functionally identical.)</p>
99
100<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 -0600101the name of the new command, and modify this copy to implement the new command.
Rob Landley6882ee82008-02-12 18:41:34 -0600102This file is an example command meant to be used as a "skeleton" for
Rob Landley7c04f012008-01-20 19:00:16 -0600103new commands (more or less by turning every instance of "hello" into the
104name of your command, updating the command line arguments, globals, and
105help data, and then filling out its "main" function with code that does
Rob Landley6882ee82008-02-12 18:41:34 -0600106something interesting). It provides examples of all the build infrastructure
107(including optional elements like command line argument parsing and global
108variables that a "hello world" program doesn't strictly need).</p>
Rob Landley7c04f012008-01-20 19:00:16 -0600109
110<p>Here's a checklist of steps to turn hello.c into another command:</p>
111
112<ul>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500113<li><p>First "cd toys/other" and "cp hello.c yourcommand.c". Note that the name
Rob Landley7c04f012008-01-20 19:00:16 -0600114of this file is significant, it's the name of the new command you're adding
115to toybox. Open your new file in your favorite editor.</p></li>
116
117<li><p>Change the one line comment at the top of the file (currently
118"hello.c - A hello world program") to describe your new file.</p></li>
119
120<li><p>Change the copyright notice to your name, email, and the current
121year.</p></li>
122
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500123<li><p>Give a URL to the relevant standards document, where applicable.
124(Sample links to SUSv4 and LSB are provided, feel free to link to other
125documentation or standards as appropriate.)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600126
Rob Landley66a69d92012-01-16 01:44:17 -0600127<li><p>Update the USE_YOURCOMMAND(NEWTOY(yourcommand,"blah",0)) line.
128The NEWTOY macro fills out this command's <a href="#toy_list">toy_list</a>
129structure. The arguments to the NEWTOY macro are:</p>
130
131<ol>
132<li><p>the name used to run your command</p></li>
133<li><p>the command line argument <a href="#lib_args">option parsing string</a> (NULL if none)</p></li>
134<li><p>a bitfield of TOYFLAG values
135(defined in toys.h) providing additional information such as where your
136command should be installed on a running system, whether to blank umask
137before running, whether or not the command must run as root (and thus should
138retain root access if installed SUID), and so on.</p></li>
139</ol>
140</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600141
142<li><p>Change the kconfig data (from "config YOURCOMMAND" to the end of the
143comment block) to supply your command's configuration and help
144information. The uppper case config symbols are used by menuconfig, and are
145also what the CFG_ and USE_() macros are generated from (see [TODO]). The
146help information here is used by menuconfig, and also by the "help" command to
147describe your new command. (See [TODO] for details.) By convention,
Rob Landley66a69d92012-01-16 01:44:17 -0600148unfinished commands default to "n" and finished commands default to "y",
149so "make defconfig" selects all finished commands. (Note, "finished" means
150"ready to be used", not that it'll never change again.)<p>
151
152<p>Each help block should start with a "usage: yourcommand" line explaining
153any command line arguments added by this config option. The "help" command
154outputs this text, and scripts/config2help.c in the build infrastructure
155collates these usage lines for commands with multiple configuration
156options when producing generated/help.h.</p>
157</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600158
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500159<li><p>Change the "#define FOR_hello" line to "#define FOR_yourcommand" right
160before the "#include <toys.h>". (This selects the appropriate FLAG_ macros and
161does a "#define TT this.yourcommand" so you can access the global variables
162out of the space-saving union of structures. If you aren't using any command
163flag bits and aren't defining a GLOBAL block, you can delete this line.)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600164
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500165<li><p>Update the GLOBALS() macro to contain your command's global
166variables. If your command has no global variables, delete this macro.</p>
167
168<p>Variables in the GLOBALS() block are are stored in a space saving
169<a href="#toy_union">union of structures</a> format, which may be accessed
170using the TT macro as if TT were a global structure (so TT.membername).
171If you specified two-character command line arguments in
172NEWTOY(), the first few global variables will be initialized by the automatic
173argument parsing logic, and the type and order of these variables must
174correspond to the arguments specified in NEWTOY().
175(See <a href="#lib_args">lib/args.c</a> for details.)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600176
177<li><p>Rename hello_main() to yourcommand_main(). This is the main() function
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500178where execution of your command starts. Your command line options are
179already sorted into this.optflags, this.optargs, this.optc, and the GLOBALS()
180as appropriate by the time this function is called. (See
181<a href="#lib_args">get_optflags()</a> for details.</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600182</ul>
183
184<p><a name="top" /><h2>Top level directory.</h2></p>
185
Rob Landley66a69d92012-01-16 01:44:17 -0600186<p>This directory contains global infrastructure.</p>
187
188<h3>toys.h</h3>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500189<p>Each command #includes "toys.h" as part of its standard prolog. It
190may "#define FOR_commandname" before doing so to get some extra entries
191specific to this command.</p>
Rob Landley66a69d92012-01-16 01:44:17 -0600192
193<p>This file sucks in most of the commonly used standard #includes, so
194individual files can just #include "toys.h" and not have to worry about
195stdargs.h and so on. Individual commands still need to #include
196special-purpose headers that may not be present on all systems (and thus would
197prevent toybox from building that command on such a system with that command
198enabled). Examples include regex support, any "linux/" or "asm/" headers, mtab
199support (mntent.h and sys/mount.h), and so on.</p>
200
201<p>The toys.h header also defines structures for most of the global variables
202provided to each command by toybox_main(). These are described in
203detail in the description for main.c, where they are initialized.</p>
204
205<p>The global variables are grouped into structures (and a union) for space
206savings, to more easily track the amount of memory consumed by them,
207so that they may be automatically cleared/initialized as needed, and so
208that access to global variables is more easily distinguished from access to
209local variables.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600210
211<h3>main.c</h3>
212<p>Contains the main() function where execution starts, plus
213common infrastructure to initialize global variables and select which command
Rob Landley6882ee82008-02-12 18:41:34 -0600214to run. The "toybox" multiplexer command also lives here. (This is the
Rob Landley7c04f012008-01-20 19:00:16 -0600215only command defined outside of the toys directory.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600216
Rob Landley6882ee82008-02-12 18:41:34 -0600217<p>Execution starts in main() which trims any path off of the first command
218name and calls toybox_main(), which calls toy_exec(), which calls toy_find()
Rob Landley66a69d92012-01-16 01:44:17 -0600219and toy_init() before calling the appropriate command's function from
220toy_list[] (via toys.which->toy_main()).
Rob Landley6882ee82008-02-12 18:41:34 -0600221If the command is "toybox", execution recurses into toybox_main(), otherwise
222the call goes to the appropriate commandname_main() from a C file in the toys
223directory.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600224
Rob Landley6882ee82008-02-12 18:41:34 -0600225<p>The following global variables are defined in main.c:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600226<ul>
Rob Landley66a69d92012-01-16 01:44:17 -0600227<a name="toy_list" />
228<li><p><b>struct toy_list toy_list[]</b> - array describing all the
Rob Landley4e68de12007-12-13 07:00:27 -0600229commands currently configured into toybox. The first entry (toy_list[0]) is
230for the "toybox" multiplexer command, which runs all the other built-in commands
231without symlinks by using its first argument as the name of the command to
232run and the rest as that command's argument list (ala "./toybox echo hello").
233The remaining entries are the commands in alphabetical order (for efficient
234binary search).</p>
235
236<p>This is a read-only array initialized at compile time by
Rob Landley6882ee82008-02-12 18:41:34 -0600237defining macros and #including generated/newtoys.h.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600238
Rob Landley66a69d92012-01-16 01:44:17 -0600239<p>Members of struct toy_list (defined in "toys.h") include:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600240<ul>
241<li><p>char *<b>name</b> - the name of this command.</p></li>
242<li><p>void (*<b>toy_main</b>)(void) - function pointer to run this
243command.</p></li>
244<li><p>char *<b>options</b> - command line option string (used by
245get_optflags() in lib/args.c to intialize toys.optflags, toys.optargs, and
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500246entries in the toy's GLOBALS struct). When this is NULL, no option
Rob Landley66a69d92012-01-16 01:44:17 -0600247parsing is done before calling toy_main().</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600248<li><p>int <b>flags</b> - Behavior flags for this command. The following flags are currently understood:</p>
249
250<ul>
251<li><b>TOYFLAG_USR</b> - Install this command under /usr</li>
252<li><b>TOYFLAG_BIN</b> - Install this command under /bin</li>
253<li><b>TOYFLAG_SBIN</b> - Install this command under /sbin</li>
254<li><b>TOYFLAG_NOFORK</b> - This command can be used as a shell builtin.</li>
255<li><b>TOYFLAG_UMASK</b> - Call umask(0) before running this command.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600256<li><b>TOYFLAG_STAYROOT</b> - Don't drop permissions for this command if toybox is installed SUID root.</li>
257<li><b>TOYFLAG_NEEDROOT</b> - This command cannot function unless run with root access.</li>
Rob Landley6882ee82008-02-12 18:41:34 -0600258</ul>
259<br>
260
261<p>These flags are combined with | (or). For example, to install a command
262in /usr/bin, or together TOYFLAG_USR|TOYFLAG_BIN.</p>
263</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600264</li>
265
Rob Landley66a69d92012-01-16 01:44:17 -0600266<li><p><b>struct toy_context toys</b> - global structure containing information
267common to all commands, initializd by toy_init() and defined in "toys.h".
268Members of this structure include:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600269<ul>
270<li><p>struct toy_list *<b>which</b> - a pointer to this command's toy_list
271structure. Mostly used to grab the name of the running command
272(toys->which.name).</p>
273</li>
274<li><p>int <b>exitval</b> - Exit value of this command. Defaults to zero. The
275error_exit() functions will return 1 if this is zero, otherwise they'll
276return this value.</p></li>
277<li><p>char **<b>argv</b> - "raw" command line options, I.E. the original
278unmodified string array passed in to main(). Note that modifying this changes
Rob Landley66a69d92012-01-16 01:44:17 -0600279"ps" output, and is not recommended. This array is null terminated; a NULL
280entry indicates the end of the array.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600281<p>Most commands don't use this field, instead the use optargs, optflags,
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500282and the fields in the GLOBALS struct initialized by get_optflags().</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600283</li>
284<li><p>unsigned <b>optflags</b> - Command line option flags, set by
Rob Landley66a69d92012-01-16 01:44:17 -0600285<a href="#lib_args">get_optflags()</a>. Indicates which of the command line options listed in
Rob Landley6882ee82008-02-12 18:41:34 -0600286toys->which.options occurred this time.</p>
287
288<p>The rightmost command line argument listed in toys->which.options sets bit
2891, the next one sets bit 2, and so on. This means the bits are set in the same
290order the binary digits would be listed if typed out as a string. For example,
291the option string "abcd" would parse the command line "-c" to set optflags to 2,
292"-a" would set optflags to 8, and "-bd" would set optflags to 6 (4|2).</p>
293
294<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 -0500295b=4, a=8. Punctuation after a letter initializes global variables at the
296start of the GLOBALS() block (see <a href="#toy_union">union toy_union this</a>
297for details).</p>
298
299<p>The build infrastructure creates FLAG_ macros for each option letter,
300corresponding to the bit position, so you can check (toys.optflags & FLAG_x)
301to see if a flag was specified. (The correct set of FLAG_ macros is selected
302by defining FOR_mycommand before #including toys.h. The macros live in
303toys/globals.h which is generated by scripts/make.sh.)</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600304
Rob Landley66a69d92012-01-16 01:44:17 -0600305<p>For more information on option parsing, see <a href="#lib_args">get_optflags()</a>.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600306
307</li>
Rob Landley4e68de12007-12-13 07:00:27 -0600308<li><p>char **<b>optargs</b> - Null terminated array of arguments left over
309after get_optflags() removed all the ones it understood. Note: optarg[0] is
310the first argument, not the command name. Use toys.which->name for the command
311name.</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600312<li><p>int <b>optc</b> - Optarg count, equivalent to argc but for
313optargs[].<p></li>
Rob Landley4e68de12007-12-13 07:00:27 -0600314<li><p>int <b>exithelp</b> - Whether error_exit() should print a usage message
315via help_main() before exiting. (True during option parsing, defaults to
316false afterwards.)</p></li>
Rob Landley66a69d92012-01-16 01:44:17 -0600317</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600318
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500319<a name="toy_union" />
Rob Landley66a69d92012-01-16 01:44:17 -0600320<li><p><b>union toy_union this</b> - Union of structures containing each
Rob Landley4e68de12007-12-13 07:00:27 -0600321command's global variables.</p>
322
Rob Landley6882ee82008-02-12 18:41:34 -0600323<p>Global variables are useful: they reduce the overhead of passing extra
324command line arguments between functions, they conveniently start prezeroed to
325save initialization costs, and the command line argument parsing infrastructure
326can also initialize global variables with its results.</p>
327
328<p>But since each toybox process can only run one command at a time, allocating
329space for global variables belonging to other commands you aren't currently
330running would be wasteful.</p>
331
332<p>Toybox handles this by encapsulating each command's global variables in
Rob Landley66a69d92012-01-16 01:44:17 -0600333a structure, and declaring a union of those structures with a single global
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500334instance (called "this"). The GLOBALS() macro contains the global
Rob Landley66a69d92012-01-16 01:44:17 -0600335variables that should go in the current command's global structure. Each
336variable can then be accessed as "this.commandname.varname".
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500337If you #defined FOR_commandname before including toys.h, the macro TT is
338#defined to this.commandname so the variable can then be accessed as
339"TT.variable". See toys/hello.c for an example.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600340
Rob Landley66a69d92012-01-16 01:44:17 -0600341<p>A command that needs global variables should declare a structure to
Rob Landley4e68de12007-12-13 07:00:27 -0600342contain them all, and add that structure to this union. A command should never
343declare global variables outside of this, because such global variables would
344allocate memory when running other commands that don't use those global
345variables.</p>
346
Rob Landley66a69d92012-01-16 01:44:17 -0600347<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 -0600348as specified by the options field off this command's toy_list entry. See
349the get_optargs() description in lib/args.c for details.</p>
350</li>
351
Rob Landley81b899d2007-12-18 02:02:47 -0600352<li><b>char toybuf[4096]</b> - a common scratch space buffer so
Rob Landley4e68de12007-12-13 07:00:27 -0600353commands don't need to allocate their own. Any command is free to use this,
354and it should never be directly referenced by functions in lib/ (although
355commands are free to pass toybuf in to a library function as an argument).</li>
356</ul>
357
Rob Landley6882ee82008-02-12 18:41:34 -0600358<p>The following functions are defined in main.c:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600359<ul>
360<li><p>struct toy_list *<b>toy_find</b>(char *name) - Return the toy_list
361structure for this command name, or NULL if not found.</p></li>
Rob Landley81b899d2007-12-18 02:02:47 -0600362<li><p>void <b>toy_init</b>(struct toy_list *which, char *argv[]) - fill out
363the global toys structure, calling get_optargs() if necessary.</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600364<li><p>void <b>toy_exec</b>(char *argv[]) - Run a built-in command with
365arguments.</p>
366<p>Calls toy_find() on argv[0] (which must be just a command name
Rob Landley4e68de12007-12-13 07:00:27 -0600367without path). Returns if it can't find this command, otherwise calls
Rob Landley6882ee82008-02-12 18:41:34 -0600368toy_init(), toys->which.toy_main(), and exit() instead of returning.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600369
Rob Landley6882ee82008-02-12 18:41:34 -0600370<p>Use the library function xexec() to fall back to external executables
371in $PATH if toy_exec() can't find a built-in command. Note that toy_exec()
372does not strip paths before searching for a command, so "./command" will
373never match an internal command.</li>
374
375<li><p>void <b>toybox_main</b>(void) - the main function for the multiplexer
376command (I.E. "toybox"). Given a command name as its first argument, calls
377toy_exec() on its arguments. With no arguments, it lists available commands.
378If the first argument starts with "-" it lists each command with its default
379install path prepended.</p></li>
Rob Landley4e68de12007-12-13 07:00:27 -0600380
381</ul>
382
383<h3>Config.in</h3>
384
385<p>Top level configuration file in a stylized variant of
Rob Landley6882ee82008-02-12 18:41:34 -0600386<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 -0600387
388<p>These files are directly used by "make menuconfig" to select which commands
389to build into toybox (thus generating a .config file), and by
Rob Landley6882ee82008-02-12 18:41:34 -0600390scripts/config2help.py to create generated/help.h.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600391
392<h3>Temporary files:</h3>
393
Rob Landley6882ee82008-02-12 18:41:34 -0600394<p>There is one temporary file in the top level source directory:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600395<ul>
396<li><p><b>.config</b> - Configuration file generated by kconfig, indicating
397which commands (and options to commands) are currently enabled. Used
Rob Landley6882ee82008-02-12 18:41:34 -0600398to make generated/config.h and determine which toys/*.c files to build.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600399
Rob Landley6882ee82008-02-12 18:41:34 -0600400<p>You can create a human readable "miniconfig" version of this file using
Rob Landley66a69d92012-01-16 01:44:17 -0600401<a href=http://landley.net/aboriginal/new_platform.html#miniconfig>these
Rob Landley6882ee82008-02-12 18:41:34 -0600402instructions</a>.</p>
403</li>
404</ul>
405
Rob Landleye7c9a6d2012-02-28 06:34:09 -0600406<a name="generated" />
Rob Landley6882ee82008-02-12 18:41:34 -0600407<p>The "generated/" directory contains files generated from other source code
408in toybox. All of these files can be recreated by the build system, although
409some (such as generated/help.h) are shipped in release versions to reduce
410environmental dependencies (I.E. so you don't need python on your build
411system).</p>
412
413<ul>
414<li><p><b>generated/config.h</b> - list of CFG_SYMBOL and USE_SYMBOL() macros,
Rob Landley4e68de12007-12-13 07:00:27 -0600415generated from .config by a sed invocation in the top level Makefile.</p>
416
417<p>CFG_SYMBOL is a comple time constant set to 1 for enabled symbols and 0 for
Rob Landley6882ee82008-02-12 18:41:34 -0600418disabled symbols. This allows the use of normal if() statements to remove
419code at compile time via the optimizer's dead code elimination (which removes
420from the binary any code that cannot be reached). This saves space without
Rob Landley4e68de12007-12-13 07:00:27 -0600421cluttering the code with #ifdefs or leading to configuration dependent build
422breaks. (See the 1992 Usenix paper
Rob Landleyb6063de2012-01-29 13:54:13 -0600423<a href=http://doc.cat-v.org/henry_spencer/ifdef_considered_harmful.pdf>#ifdef
Rob Landley4e68de12007-12-13 07:00:27 -0600424Considered Harmful</a> for more information.)</p>
425
426<p>USE_SYMBOL(code) evaluates to the code in parentheses when the symbol
427is enabled, and nothing when the symbol is disabled. This can be used
428for things like varargs or variable declarations which can't always be
Rob Landley6882ee82008-02-12 18:41:34 -0600429eliminated by a simple test on CFG_SYMBOL. Note that
Rob Landley4e68de12007-12-13 07:00:27 -0600430(unlike CFG_SYMBOL) this is really just a variant of #ifdef, and can
431still result in configuration dependent build breaks. Use with caution.</p>
432</li>
433</ul>
434
Rob Landley81b899d2007-12-18 02:02:47 -0600435<p><h2>Directory toys/</h2></p>
Rob Landley4e68de12007-12-13 07:00:27 -0600436
437<h3>toys/Config.in</h3>
438
439<p>Included from the top level Config.in, contains one or more
440configuration entries for each command.</p>
441
Rob Landley81b899d2007-12-18 02:02:47 -0600442<p>Each command has a configuration entry matching the command name (although
443configuration symbols are uppercase and command names are lower case).
Rob Landley4e68de12007-12-13 07:00:27 -0600444Options to commands start with the command name followed by an underscore and
Rob Landley66a69d92012-01-16 01:44:17 -0600445the option name. Global options are attached to the "toybox" command,
Rob Landley4e68de12007-12-13 07:00:27 -0600446and thus use the prefix "TOYBOX_". This organization is used by
Rob Landley81b899d2007-12-18 02:02:47 -0600447scripts/cfg2files to select which toys/*.c files to compile for a given
448.config.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600449
Rob Landley66a69d92012-01-16 01:44:17 -0600450<p>A command with multiple names (or multiple similar commands implemented in
Rob Landley4e68de12007-12-13 07:00:27 -0600451the same .c file) should have config symbols prefixed with the name of their
452C file. I.E. config symbol prefixes are NEWTOY() names. If OLDTOY() names
453have config symbols they're options (symbols with an underscore and suffix)
454to the NEWTOY() name. (See toys/toylist.h)</p>
455
456<h3>toys/toylist.h</h3>
Rob Landley81b899d2007-12-18 02:02:47 -0600457<p>The first half of this file prototypes all the structures to hold
Rob Landleyda09b7f2007-12-20 06:29:59 -0600458global variables for each command, and puts them in toy_union. These
459prototypes are only included if the macro NEWTOY isn't defined (in which
460case NEWTOY is defined to a default value that produces function
461prototypes).</p>
Rob Landley81b899d2007-12-18 02:02:47 -0600462
Rob Landleyda09b7f2007-12-20 06:29:59 -0600463<p>The second half of this file lists all the commands in alphabetical
464order, along with their command line arguments and install location.
465Each command has an appropriate configuration guard so only the commands that
466are enabled wind up in the list.</p>
467
468<p>The first time this header is #included, it defines structures and
469produces function prototypes for the commands in the toys directory.</p>
470
471
472<p>The first time it's included, it defines structures and produces function
473prototypes.
474 This
Rob Landley81b899d2007-12-18 02:02:47 -0600475is used to initialize toy_list in main.c, and later in that file to initialize
476NEED_OPTIONS (to figure out whether the command like parsing logic is needed),
477and to put the help entries in the right order in toys/help.c.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600478
479<h3>toys/help.h</h3>
480
481<p>#defines two help text strings for each command: a single line
482command_help and an additinal command_help_long. This is used by help_main()
483in toys/help.c to display help for commands.</p>
484
485<p>Although this file is generated from Config.in help entries by
486scripts/config2help.py, it's shipped in release tarballs so you don't need
487python on the build system. (If you check code out of source control, or
488modify Config.in, then you'll need python installed to rebuild it.)</p>
489
490<p>This file contains help for all commands, regardless of current
491configuration, but only the currently enabled ones are entered into help_data[]
492in toys/help.c.</p>
493
Rob Landley137bf342012-03-09 08:33:57 -0600494<a name="lib">
Rob Landley81b899d2007-12-18 02:02:47 -0600495<h2>Directory lib/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600496
Rob Landley137bf342012-03-09 08:33:57 -0600497<p>TODO: document lots more here.</p>
498
Rob Landleyc8d0da52012-07-15 17:47:08 -0500499<p>lib: getmountlist(), error_msg/error_exit, xmalloc(),
Rob Landley7c04f012008-01-20 19:00:16 -0600500strlcpy(), xexec(), xopen()/xread(), xgetcwd(), xabspath(), find_in_path(),
501itoa().</p>
502
Rob Landley137bf342012-03-09 08:33:57 -0600503<h3>lib/portability.h</h3>
504
505<p>This file is automatically included from the top of toys.h, and smooths
506over differences between platforms (hardware targets, compilers, C libraries,
507operating systems, etc).</p>
508
509<p>This file provides SWAP macros (SWAP_BE16(x) and SWAP_LE32(x) and so on).</p>
510
511<p>A macro like SWAP_LE32(x) means "The value in x is stored as a little
512endian 32 bit value, so perform the translation to/from whatever the native
51332-bit format is". You do the swap once on the way in, and once on the way
514out. If your target is already little endian, the macro is a NOP.</p>
515
516<p>The SWAP macros come in BE and LE each with 16, 32, and 64 bit versions.
517In each case, the name of the macro refers to the _external_ representation,
518and converts to/from whatever your native representation happens to be (which
519can vary depending on what you're currently compiling for).</p>
520
Rob Landleyc8d0da52012-07-15 17:47:08 -0500521<a name="lib_llist"><h3>lib/llist.c</h3>
522
523<p>Some generic single and doubly linked list functions, which take
524advantage of a couple properties of C:</p>
525
526<ul>
527<li><p>Structure elements are laid out in memory in the order listed, and
528the first element has no padding. This means you can always treat (typecast)
529a pointer to a structure as a pointer to the first element of the structure,
530even if you don't know anything about the data following it.</p></li>
531
532<li><p>An array of length zero at the end of a structure adds no space
533to the sizeof() the structure, but if you calculate how much extra space
534you want when you malloc() the structure it will be available at the end.
535Since C has no bounds checking, this means each struct can have one variable
536length array.</p></li>
537</ul>
538
539<p>Toybox's list structures always have their <b>next</b> pointer as
540the first entry of each struct, and singly linked lists end with a NULL pointer.
541This allows generic code to traverse such lists without knowing anything
542else about the specific structs composing them: if your pointer isn't NULL
543typecast it to void ** and dereference once to get the next entry.</p>
544
545<p><b>lib/lib.h</b> defines three structure types:</p>
546<ul>
547<li><p><b>struct string_list</b> - stores a single string (<b>char str[0]</b>),
548memory for which is allocated as part of the node. (I.E. llist_traverse(list,
549free); can clean up after this type of list.)</p></li>
550
551<li><p><b>struct arg_list</b> - stores a pointer to a single string
552(<b>char *arg</b>) which is stored in a separate chunk of memory.</p></li>
553
554<li><p><b>struct double_list</b> - has a second pointer (<b>struct double_list
555*prev</b> along with a <b>char *data</b> for payload.</p></li>
556</ul>
557
558<b>List Functions</b>
559
560<ul>
561<li><p>void *<b>llist_pop</b>(void **list) - advances through a list ala
562<b>node = llist_pop(&list);</b> This doesn't modify the list contents,
563but does advance the pointer you feed it (which is why you pass the _address_
564of that pointer, not the pointer itself).</p></li>
565
566<li><p>void <b>llist_traverse</b>(void *list, void (*using)(void *data)) -
567iterate through a list calling a function on each node.</p></li>
568
569<li><p>struct double_list *<b>dlist_add</b>(struct double_list **llist, char *data)
570- append an entry to a circular linked list.
571This function allocates a new struct double_list wrapper and returns the
572pointer to the new entry (which you can usually ignore since it's llist->prev,
573but if llist was NULL you need it). The argument is the ->data field for the
574new node.</p></li>
575<ul><li><p>void <b>dlist_add_nomalloc</b>(struct double_list **llist,
576struct double_list *new) - append existing struct double_list to
577list, does not allocate anything.</p></li></ul>
578</ul>
579
580<b>Trivia questions:</b>
581
582<ul>
583<li><p><b>Why do arg_list and double_list contain a char * payload instead of
584a void *?</b> - Because you always have to typecast a void * to use it, and
585typecasting a char * does no harm. Thus having it default to the most common
586pointer type saves a few typecasts (strings are the most common payload),
587and doesn't hurt anything otherwise.</p>
588</li>
589
590<li><p><b>Why do the names ->str, ->arg, and ->data differ?</b> - To force
591you to keep track of which one you're using, calling free(node->str) would
592be bad, and _failing_ to free(node->arg) leaks memory.</p></li>
593
594<li><p><b>Why does llist_pop() take a void * instead of void **?</b> -
595because the stupid compiler complains about "type punned pointers" when
596you typecast and dereference ont he same line,
597due to insane FSF developers hardwiring limitations of their optimizer
598into gcc's warning system. Since C automatically typecasts any other
599pointer _down_ to a void *, the current code works fine. It's sad that it
600won't warn you if you forget the &, but the code crashes pretty quickly in
601that case.</p></li>
602
603<li><p><b>How do I assemble a singly-linked-list in order?</b> - use
604a double_list, dlist_add() your entries, and then break the circle with
605<b>list->prev->next = NULL;</b> when done.</li>
606</ul>
607
Rob Landley66a69d92012-01-16 01:44:17 -0600608<a name="lib_args"><h3>lib/args.c</h3>
Rob Landley7c04f012008-01-20 19:00:16 -0600609
Rob Landley66a69d92012-01-16 01:44:17 -0600610<p>Toybox's main.c automatically parses command line options before calling the
611command's main function. Option parsing starts in get_optflags(), which stores
612results in the global structures "toys" (optflags and optargs) and "this".</p>
613
614<p>The option parsing infrastructure stores a bitfield in toys.optflags to
615indicate which options the current command line contained. Arguments
616attached to those options are saved into the command's global structure
617("this"). Any remaining command line arguments are collected together into
618the null-terminated array toys.optargs, with the length in toys.optc. (Note
619that toys.optargs does not contain the current command name at position zero,
620use "toys.which->name" for that.) The raw command line arguments get_optflags()
621parsed are retained unmodified in toys.argv[].</p>
622
623<p>Toybox's option parsing logic is controlled by an "optflags" string, using
624a format reminiscent of getopt's optargs but has several important differences.
625Toybox does not use the getopt()
626function out of the C library, get_optflags() is an independent implementation
627which doesn't permute the original arguments (and thus doesn't change how the
628command is displayed in ps and top), and has many features not present in
629libc optargs() (such as the ability to describe long options in the same string
630as normal options).</p>
631
632<p>Each command's NEWTOY() macro has an optflags string as its middle argument,
633which sets toy_list.options for that command to tell get_optflags() what
634command line arguments to look for, and what to do with them.
635If a command has no option
636definition string (I.E. the argument is NULL), option parsing is skipped
637for that command, which must look at the raw data in toys.argv to parse its
638own arguments. (If no currently enabled command uses option parsing,
639get_optflags() is optimized out of the resulting binary by the compiler's
640--gc-sections option.)</p>
641
642<p>You don't have to free the option strings, which point into the environment
643space (I.E. the string data is not copied). A TOYFLAG_NOFORK command
644that uses the linked list type "*" should free the list objects but not
645the data they point to, via "llist_free(TT.mylist, NULL);". (If it's not
646NOFORK, exit() will free all the malloced data anyway unless you want
647to implement a CONFIG_TOYBOX_FREE cleanup for it.)</p>
648
649<h4>Optflags format string</h4>
650
651<p>Note: the optflags option description string format is much more
652concisely described by a large comment at the top of lib/args.c.</p>
653
654<p>The general theory is that letters set optflags, and punctuation describes
655other actions the option parsing logic should take.</p>
656
657<p>For example, suppose the command line <b>command -b fruit -d walrus -a 42</b>
658is parsed using the optflags string "<b>a#b:c:d</b>". (I.E.
659toys.which->options="a#b:c:d" and argv = ["command", "-b", "fruit", "-d",
660"walrus", "-a", "42"]). When get_optflags() returns, the following data is
661available to command_main():
662
663<ul>
664<li><p>In <b>struct toys</b>:
665<ul>
666<li>toys.optflags = 13; // -a = 8 | -b = 4 | -d = 1</li>
667<li>toys.optargs[0] = "walrus"; // leftover argument</li>
668<li>toys.optargs[1] = NULL; // end of list</li>
669<li>toys.optc=1; // there was 1 leftover argument</li>
670<li>toys.argv[] = {"-b", "fruit", "-d", "walrus", "-a", "42"}; // The original command line arguments
671</ul>
672<p></li>
673
674<li><p>In <b>union this</b> (treated as <b>long this[]</b>):
675<ul>
676<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>
677<li>this[1] = (long)"fruit"; // argument to -b</li>
678<li>this[2] = 42; // argument to -a</li>
679</ul>
680</p></li>
681</ul>
682
683<p>If the command's globals are:</p>
684
685<blockquote><pre>
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500686GLOBALS(
Rob Landley66a69d92012-01-16 01:44:17 -0600687 char *c;
688 char *b;
689 long a;
690)
Rob Landley66a69d92012-01-16 01:44:17 -0600691</pre></blockquote>
692<p>That would mean TT.c == NULL, TT.b == "fruit", and TT.a == 42. (Remember,
693each entry that receives an argument must be a long or pointer, to line up
694with the array position. Right to left in the optflags string corresponds to
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500695top to bottom in GLOBALS().</p>
Rob Landley66a69d92012-01-16 01:44:17 -0600696
697<p><b>long toys.optflags</b></p>
698
699<p>Each option in the optflags string corresponds to a bit position in
700toys.optflags, with the same value as a corresponding binary digit. The
701rightmost argument is (1<<0), the next to last is (1<<1) and so on. If
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600702the option isn't encountered while parsing argv[], its bit remains 0.</p>
703
704<p>For example,
Rob Landley66a69d92012-01-16 01:44:17 -0600705the optflags string "abcd" would parse the command line argument "-c" to set
706optflags to 2, "-a" would set optflags to 8, "-bd" would set optflags to
7076 (I.E. 4|2), and "-a -c" would set optflags to 10 (2|8).</p>
708
709<p>Only letters are relevant to optflags, punctuation is skipped: in the
710string "a*b:c#d", d=1, c=2, b=4, a=8. The punctuation after a letter
711usually indicate that the option takes an argument.</p>
712
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600713<p>Since toys.optflags is an unsigned int, it only stores 32 bits. (Which is
714the amount a long would have on 32-bit platforms anyway; 64 bit code on
71532 bit platforms is too expensive to require in common code used by almost
716all commands.) Bit positions beyond the 1<<31 aren't recorded, but
717parsing higher options can still set global variables.</p>
718
Rob Landley66a69d92012-01-16 01:44:17 -0600719<p><b>Automatically setting global variables from arguments (union this)</b></p>
720
721<p>The following punctuation characters may be appended to an optflags
722argument letter, indicating the option takes an additional argument:</p>
723
724<ul>
725<li><b>:</b> - plus a string argument, keep most recent if more than one.</li>
726<li><b>*</b> - plus a string argument, appended to a linked list.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600727<li><b>@</b> - plus an occurrence counter (stored in a long)</li>
Rob Landleyb6063de2012-01-29 13:54:13 -0600728<li><b>#</b> - plus a signed long argument.
729<li><b>.</b> - plus a floating point argument (if CFG_TOYBOX_FLOAT).</li>
730<ul>The following can be appended to a float or double:
731<li><b>&lt;123</b> - error if argument is less than this</li>
732<li><b>&gt;123</b> - error if argument is greater than this</li>
733<li><b>=123</b> - default value if argument not supplied</li>
734</ul>
735<ul><li>Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT
736is enabled. (Otherwise the code to determine where floating point constants
737end drops out. When disabled, it can reserve a global data slot for the
738argument so offsets won't change, but will never fill it out.). You can handle
739this by using the USE_BLAH() macros with C string concatenation, ala:
740"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</li></ul>
Rob Landley66a69d92012-01-16 01:44:17 -0600741</ul>
742
743<p>Arguments may occur with or without a space (I.E. "-a 42" or "-a42").
744The command line argument "-abc" may be interepreted many different ways:
745the optflags string "cba" sets toys.optflags = 7, "c:ba" sets toys.optflags=4
746and saves "ba" as the argument to -c, and "cb:a" sets optflags to 6 and saves
747"c" as the argument to -b.</p>
748
749<p>Options which have an argument fill in the corresponding slot in the global
750union "this" (see generated/globals.h), treating it as an array of longs
751with the rightmost saved in this[0]. Again using "a*b:c#d", "-c 42" would set
752this[0]=42; and "-b 42" would set this[1]="42"; each slot is left NULL if
753the corresponding argument is not encountered.</p>
754
755<p>This behavior is useful because the LP64 standard ensures long and pointer
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600756are the same size. C99 guarantees structure members will occur in memory
757in the same order they're declared, and that padding won't be inserted between
Rob Landley66a69d92012-01-16 01:44:17 -0600758consecutive variables of register size. Thus the first few entries can
759be longs or pointers corresponding to the saved arguments.</p>
760
761<p><b>char *toys.optargs[]</b></p>
762
763<p>Command line arguments in argv[] which are not consumed by option parsing
764(I.E. not recognized either as -flags or arguments to -flags) will be copied
765to toys.optargs[], with the length of that array in toys.optc.
766(When toys.optc is 0, no unrecognized command line arguments remain.)
767The order of entries is preserved, and as with argv[] this new array is also
768terminated by a NULL entry.</p>
769
770<p>Option parsing can require a minimum or maximum number of optargs left
771over, by adding "<1" (read "at least one") or ">9" ("at most nine") to the
772start of the optflags string.</p>
773
774<p>The special argument "--" terminates option parsing, storing all remaining
775arguments in optargs. The "--" itself is consumed.</p>
776
777<p><b>Other optflags control characters</b></p>
778
779<p>The following characters may occur at the start of each command's
780optflags string, before any options that would set a bit in toys.optflags:</p>
781
782<ul>
783<li><b>^</b> - stop at first nonoption argument (for nice, xargs...)</li>
784<li><b>?</b> - allow unknown arguments (pass non-option arguments starting
785with - through to optargs instead of erroring out).</li>
786<li><b>&amp;</b> - the first argument has imaginary dash (ala tar/ps. If given twice, all arguments have imaginary dash.)</li>
787<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>
788<li><b>&gt;</b> - must be followed by a decimal digit indicating at most this many leftover arguments allowed (default MAX_INT)</li>
789</ul>
790
791<p>The following characters may be appended to an option character, but do
792not by themselves indicate an extra argument should be saved in this[].
793(Technically any character not recognized as a control character sets an
794optflag, but letters are never control characters.)</p>
795
796<ul>
797<li><b>^</b> - stop parsing options after encountering this option, everything else goes into optargs.</li>
798<li><b>|</b> - this option is required. If more than one marked, only one is required.</li>
799<li><b>+X</b> enabling this option also enables option X (switch bit on).</li>
800<li><b>~X</b> enabling this option disables option X (switch bit off).</li>
801<li><b>!X</b> this option cannot be used in combination with X (die with error).</li>
802<li><b>[yz]</b> this option requires at least one of y or z to also be enabled.</li>
803</ul>
804
Rob Landleyb6063de2012-01-29 13:54:13 -0600805<p>The following may be appended to a float or double:</p>
806
807<ul>
808<li><b>&lt;123</b> - error if argument is less than this</li>
809<li><b>&gt;123</b> - error if argument is greater than this</li>
810<li><b>=123</b> - default value if argument not supplied</li>
811</ul>
812
813<p>Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT
814is enabled. (Otherwise the code to determine where floating point constants
815end drops out. When disabled, it can reserve a global data slot for the
816argument so offsets won't change, but will never fill it out.). You can handle
817this by using the USE_BLAH() macros with C string concatenation, ala:</p>
818
819<blockquote>"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</blockquote>
820
Rob Landley66a69d92012-01-16 01:44:17 -0600821<p><b>--longopts</b></p>
822
823<p>The optflags string can contain long options, which are enclosed in
824parentheses. They may be appended to an existing option character, in
825which case the --longopt is a synonym for that option, ala "a:(--fred)"
826which understands "-a blah" or "--fred blah" as synonyms.</p>
827
828<p>Longopts may also appear before any other options in the optflags string,
829in which case they have no corresponding short argument, but instead set
830their own bit based on position. So for "(walrus)#(blah)xy:z" "command
831--walrus 42" would set toys.optflags = 16 (-z = 1, -y = 2, -x = 4, --blah = 8)
832and would assign this[1] = 42;</p>
833
834<p>A short option may have multiple longopt synonyms, "a(one)(two)", but
835each "bare longopt" (ala "(one)(two)abc" before any option characters)
836always sets its own bit (although you can group them with +X).</p>
Rob Landley7c04f012008-01-20 19:00:16 -0600837
Rob Landleyc8d0da52012-07-15 17:47:08 -0500838<a name="lib_dirtree"><h3>lib/dirtree.c</h3>
839
840<p>The directory tree traversal code should be sufficiently generic
841that commands never need to use readdir(), scandir(), or the fts.h family
842of functions.</p>
843
844<p>These functions do not call chdir() or rely on PATH_MAX. Instead they
845use openat() and friends, using one filehandle per directory level to
846recurseinto subdirectories. (I.E. they can descend 1000 directories deep
847if setrlimit(RLIMIT_NOFILE) allows enough open filehandles, and the default
848in /proc/self/limits is generally 1024.)</p>
849
850<p>The basic dirtree functions are:</p>
851
852<ul>
853<li><p><b>dirtree_read(char *path, int (*callback)(struct dirtree node))</b> -
854recursively read directories, either applying callback() or returning
855a tree of struct dirtree if callback is NULL.</p></li>
856
857<li><p><b>dirtree_path(struct dirtree *node, int *plen)</b> - malloc() a
858string containing the path from the root of this tree to this node. If
859plen isn't NULL then *plen is how many extra bytes to malloc at the end
860of string.</p></li>
861
862<li><p><b>dirtree_parentfd(struct dirtree *node)</b> - return fd of
863containing directory, for use with openat() and such.</p></li>
864</ul>
865
866<p>The <b>dirtree_read()</b> function takes two arguments, a starting path for
867the root of the tree, and a callback function. The callback takes a
868<b>struct dirtree *</b> (from lib/lib.h) as its argument. If the callback is
869NULL, the traversal uses a default callback (dirtree_notdotdot()) which
870recursively assembles a tree of struct dirtree nodes for all files under
871this directory and subdirectories (filtering out "." and ".." entries),
872after which dirtree_read() returns the pointer to the root node of this
873snapshot tree.</p>
874
875<p>Otherwise the callback() is called on each entry in the directory,
876with struct dirtree * as its argument. This includes the initial
877node created by dirtree_read() at the top of the tree.</p>
878
879<p><b>struct dirtree</b></p>
880
881<p>Each struct dirtree node contains <b>char name[]</b> and <b>struct stat
882st</b> entries describing a file, plus a <b>char *symlink</b>
883which is NULL for non-symlinks.</p>
884
885<p>During a callback function, the <b>int data</b> field of directory nodes
886contains a dirfd (for use with the openat() family of functions). This is
887generally used by calling dirtree_parentfd() on the callback's node argument.
888For symlinks, data contains the length of the symlink string. On the second
889callback from DIRTREE_COMEAGAIN (depth-first traversal) data = -1 for
890all nodes (that's how you can tell it's the second callback).</p>
891
892<p>Users of this code may put anything they like into the <b>long extra</b>
893field. For example, "cp" and "mv" use this to store a dirfd for the destination
894directory (and use DIRTREE_COMEAGAIN to get the second callback so they can
895close(node->extra) to avoid running out of filehandles).
896This field is not directly used by the dirtree code, and
897thanks to LP64 it's large enough to store a typecast pointer to an
898arbitrary struct.</p>
899
900<p>The return value of the callback combines flags (with boolean or) to tell
901the traversal infrastructure how to behave:</p>
902
903<ul>
904<li><p><b>DIRTREE_SAVE</b> - Save this node, assembling a tree. (Without
905this the struct dirtree is freed after the callback returns. Filtering out
906siblings is fine, but discarding a parent while keeping its child leaks
907memory.)</p></li>
908<li><p><b>DIRTREE_ABORT</b> - Do not examine any more entries in this
909directory. (Does not propagate up tree: to abort entire traversal,
910return DIRTREE_ABORT from parent callbacks too.)</p></li>
911<li><p><b>DIRTREE_RECURSE</b> - Examine directory contents. Ignored for
912non-directory entries. The remaining flags only take effect when
913recursing into the children of a directory.</p></li>
914<li><p><b>DIRTREE_COMEAGAIN</b> - Call the callback a second time after
915examining all directory contents, allowing depth-first traversal.
916On the second call, dirtree->data = -1.</p></li>
917<li><p><b>DIRTREE_SYMFOLLOW</b> - follow symlinks when populating children's
918<b>struct stat st</b> (by feeding a nonzero value to the symfollow argument of
919dirtree_add_node()), which means DIRTREE_RECURSE treats symlinks to
920directories as directories. (Avoiding infinite recursion is the callback's
921problem: the non-NULL dirtree->symlink can still distinguish between
922them.)</p></li>
923</ul>
924
925<p>Each struct dirtree contains three pointers (next, parent, and child)
926to other struct dirtree.</p>
927
928<p>The <b>parent</b> pointer indicates the directory
929containing this entry; even when not assembling a persistent tree of
930nodes the parent entries remain live up to the root of the tree while
931child nodes are active. At the top of the tree the parent pointer is
932NULL, meaning the node's name[] is either an absolute path or relative
933to cwd. The function dirtree_parentfd() gets the directory file descriptor
934for use with openat() and friends, returning AT_FDCWD at the top of tree.</p>
935
936<p>The <b>child</b> pointer points to the first node of the list of contents of
937this directory. If the directory contains no files, or the entry isn't
938a directory, child is NULL.</p>
939
940<p>The <b>next</b> pointer indicates sibling nodes in the same directory as this
941node, and since it's the first entry in the struct the llist.c traversal
942mechanisms work to iterate over sibling nodes. Each dirtree node is a
943single malloc() (even char *symlink points to memory at the end of the node),
944so llist_free() works but its callback must descend into child nodes (freeing
945a tree, not just a linked list), plus whatever the user stored in extra.</p>
946
947<p>The <b>dirtree_read</b>() function is a simple wrapper, calling <b>dirtree_add_node</b>()
948to create a root node relative to the current directory, then calling
949<b>handle_callback</b>() on that node (which recurses as instructed by the callback
950return flags). Some commands (such as chgrp) bypass this wrapper, for example
951to control whether or not to follow symlinks to the root node; symlinks
952listed on the command line are often treated differently than symlinks
953encountered during recursive directory traversal).
954
955<p>The ls command not only bypasses the wrapper, but never returns
956<b>DIRTREE_RECURSE</b> from the callback, instead calling <b>dirtree_recurse</b>() manually
957from elsewhere in the program. This gives ls -lR manual control
958of traversal order, which is neither depth first nor breadth first but
959instead a sort of FIFO order requried by the ls standard.</p>
960
Rob Landleyc0e56ed2012-10-08 00:02:30 -0500961<a name="#toys">
962<h2>Directory toys/</h2>
963
964<p>This directory contains command implementations. Each command is a single
965self-contained file. Adding a new command involves adding a single
966file, and removing a command involves removing that file. Commands use
967shared infrastructure from the lib/ and generated/ directories.</p>
968
969<p>Currently there are three subdirectories under "toys/" containing commands
970described in POSIX-2008, the Linux Standard Base 4.1, or "other". The only
971difference this makes is which menu the command shows up in during "make
972menuconfig", the directories are otherwise identical. Note that they commands
973exist within a single namespace at runtime, so you can't have the same
974command in multiple subdirectories.</p>
975
976<p>(There are actually four sub-menus in "make menuconfig", the fourth
977contains global configuration options for toybox, and lives in Config.in at
978the top level.)</p>
979
980<p>See <a href="#adding">adding a new command</a> for details on the
981layout of a command file.</p>
982
Rob Landley81b899d2007-12-18 02:02:47 -0600983<h2>Directory scripts/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600984
985<h3>scripts/cfg2files.sh</h3>
986
987<p>Run .config through this filter to get a list of enabled commands, which
988is turned into a list of files in toys via a sed invocation in the top level
989Makefile.
990</p>
991
Rob Landley81b899d2007-12-18 02:02:47 -0600992<h2>Directory kconfig/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600993
994<p>Menuconfig infrastructure copied from the Linux kernel. See the
995Linux kernel's Documentation/kbuild/kconfig-language.txt</p>
996
Rob Landley66a69d92012-01-16 01:44:17 -0600997<a name="generated">
998<h2>Directory generated/</h2>
999
1000<p>All the files in this directory except the README are generated by the
1001build. (See scripts/make.sh)</p>
1002
1003<ul>
1004<li><p><b>config.h</b> - CFG_COMMAND and USE_COMMAND() macros set by menuconfig via .config.</p></li>
1005
1006<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>
1007
1008<li><p><b>help.h</b> - Help text strings for use by "help" command. Building
1009this file requires python on the host system, so the prebuilt file is shipped
1010in the build tarball to avoid requiring python to build toybox.</p></li>
1011
1012<li><p><b>newtoys.h</b> - List of NEWTOY() or OLDTOY() macros for all available
1013commands. Associates command_main() functions with command names, provides
1014option string for command line parsing (<a href="#lib_args">see lib/args.c</a>),
1015specifies where to install each command and whether toysh should fork before
1016calling it.</p></li>
1017</ul>
1018
1019<p>Everything in this directory is a derivative file produced from something
1020else. The entire directory is deleted by "make distclean".</p>
Rob Landley4e68de12007-12-13 07:00:27 -06001021<!--#include file="footer.html" -->