blob: 3a77a3ce3fcab28c6f88f7aad5f67909e0ff0949 [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
77each command.</li>
78<li>The <a href="#scripts">scripts directory</a> contains the build and
79test infrastructure.</li>
80<li>The <a href="#kconfig">kconfig directory</a> contains the configuration
81infrastructure implementing menuconfig (copied from the Linux kernel).</li>
82<li>The <a href="#generated">generated directory</a> contains intermediate
83files generated from other parts of the source code.</li>
84</ul>
Rob Landley4e68de12007-12-13 07:00:27 -060085
Rob Landleybbe500e2012-02-26 21:53:15 -060086<a name="adding" />
Rob Landley7c04f012008-01-20 19:00:16 -060087<p><h1>Adding a new command</h1></p>
88<p>To add a new command to toybox, add a C file implementing that command to
89the toys directory. No other files need to be modified; the build extracts
Rob Landley6882ee82008-02-12 18:41:34 -060090all the information it needs (such as command line arguments) from specially
Rob Landley7c04f012008-01-20 19:00:16 -060091formatted comments and macros in the C file. (See the description of the
Rob Landleye7c9a6d2012-02-28 06:34:09 -060092<a href="#generated">"generated" directory</a> for details.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -060093
Rob Landley7c04f012008-01-20 19:00:16 -060094<p>An easy way to start a new command is copy the file "hello.c" to
95the name of the new command, and modify this copy to implement the new command.
Rob Landley6882ee82008-02-12 18:41:34 -060096This file is an example command meant to be used as a "skeleton" for
Rob Landley7c04f012008-01-20 19:00:16 -060097new commands (more or less by turning every instance of "hello" into the
98name of your command, updating the command line arguments, globals, and
99help data, and then filling out its "main" function with code that does
Rob Landley6882ee82008-02-12 18:41:34 -0600100something interesting). It provides examples of all the build infrastructure
101(including optional elements like command line argument parsing and global
102variables that a "hello world" program doesn't strictly need).</p>
Rob Landley7c04f012008-01-20 19:00:16 -0600103
104<p>Here's a checklist of steps to turn hello.c into another command:</p>
105
106<ul>
107<li><p>First "cd toys" and "cp hello.c yourcommand.c". Note that the name
108of this file is significant, it's the name of the new command you're adding
109to toybox. Open your new file in your favorite editor.</p></li>
110
111<li><p>Change the one line comment at the top of the file (currently
112"hello.c - A hello world program") to describe your new file.</p></li>
113
114<li><p>Change the copyright notice to your name, email, and the current
115year.</p></li>
116
Rob Landley66a69d92012-01-16 01:44:17 -0600117<li><p>Give a URL to the relevant standards document, or say "Not in SUSv4" if
Rob Landley7c04f012008-01-20 19:00:16 -0600118there is no relevant standard. (Currently both lines are there, delete
Rob Landley66a69d92012-01-16 01:44:17 -0600119whichever is inappropriate.) The existing link goes to the directory of SUSv4
Rob Landley7c04f012008-01-20 19:00:16 -0600120command line utility standards on the Open Group's website, where there's often
121a relevant commandname.html file. Feel free to link to other documentation or
122standards as appropriate.</p></li>
123
Rob Landley66a69d92012-01-16 01:44:17 -0600124<li><p>Update the USE_YOURCOMMAND(NEWTOY(yourcommand,"blah",0)) line.
125The NEWTOY macro fills out this command's <a href="#toy_list">toy_list</a>
126structure. The arguments to the NEWTOY macro are:</p>
127
128<ol>
129<li><p>the name used to run your command</p></li>
130<li><p>the command line argument <a href="#lib_args">option parsing string</a> (NULL if none)</p></li>
131<li><p>a bitfield of TOYFLAG values
132(defined in toys.h) providing additional information such as where your
133command should be installed on a running system, whether to blank umask
134before running, whether or not the command must run as root (and thus should
135retain root access if installed SUID), and so on.</p></li>
136</ol>
137</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600138
139<li><p>Change the kconfig data (from "config YOURCOMMAND" to the end of the
140comment block) to supply your command's configuration and help
141information. The uppper case config symbols are used by menuconfig, and are
142also what the CFG_ and USE_() macros are generated from (see [TODO]). The
143help information here is used by menuconfig, and also by the "help" command to
144describe your new command. (See [TODO] for details.) By convention,
Rob Landley66a69d92012-01-16 01:44:17 -0600145unfinished commands default to "n" and finished commands default to "y",
146so "make defconfig" selects all finished commands. (Note, "finished" means
147"ready to be used", not that it'll never change again.)<p>
148
149<p>Each help block should start with a "usage: yourcommand" line explaining
150any command line arguments added by this config option. The "help" command
151outputs this text, and scripts/config2help.c in the build infrastructure
152collates these usage lines for commands with multiple configuration
153options when producing generated/help.h.</p>
154</li>
Rob Landley7c04f012008-01-20 19:00:16 -0600155
156<li><p>Update the DEFINE_GLOBALS() macro to contain your command's global
157variables, and also change the name "hello" in the #define TT line afterwards
158to the name of your command. If your command has no global variables, delete
159this macro (and the #define TT line afterwards). Note that if you specified
160two-character command line arguments in NEWTOY(), the first few global
161variables will be initialized by the automatic argument parsing logic, and
162the type and order of these variables must correspond to the arguments
163specified in NEWTOY(). See [TODO] for details.</p></li>
164
Rob Landley6882ee82008-02-12 18:41:34 -0600165<li><p>If you didn't delete the DEFINE_GLOBALS macro, change the "#define TT
166this.hello" line to use your command name in place of the "hello". This is a
167shortcut to access your global variables as if they were members of the global
168struct "TT". (Access these members with a period ".", not a right arrow
169"->".)</p></li>
Rob Landley7c04f012008-01-20 19:00:16 -0600170
171<li><p>Rename hello_main() to yourcommand_main(). This is the main() function
Rob Landley6882ee82008-02-12 18:41:34 -0600172where execution of your command starts. See [TODO] to figure out what
Rob Landley7c04f012008-01-20 19:00:16 -0600173happened to your command line arguments and how to access them.</p></li>
174</ul>
175
176<p><a name="top" /><h2>Top level directory.</h2></p>
177
Rob Landley66a69d92012-01-16 01:44:17 -0600178<p>This directory contains global infrastructure.</p>
179
180<h3>toys.h</h3>
181<p>Each command #includes "toys.h" as part of its standard prolog.</p>
182
183<p>This file sucks in most of the commonly used standard #includes, so
184individual files can just #include "toys.h" and not have to worry about
185stdargs.h and so on. Individual commands still need to #include
186special-purpose headers that may not be present on all systems (and thus would
187prevent toybox from building that command on such a system with that command
188enabled). Examples include regex support, any "linux/" or "asm/" headers, mtab
189support (mntent.h and sys/mount.h), and so on.</p>
190
191<p>The toys.h header also defines structures for most of the global variables
192provided to each command by toybox_main(). These are described in
193detail in the description for main.c, where they are initialized.</p>
194
195<p>The global variables are grouped into structures (and a union) for space
196savings, to more easily track the amount of memory consumed by them,
197so that they may be automatically cleared/initialized as needed, and so
198that access to global variables is more easily distinguished from access to
199local variables.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600200
201<h3>main.c</h3>
202<p>Contains the main() function where execution starts, plus
203common infrastructure to initialize global variables and select which command
Rob Landley6882ee82008-02-12 18:41:34 -0600204to run. The "toybox" multiplexer command also lives here. (This is the
Rob Landley7c04f012008-01-20 19:00:16 -0600205only command defined outside of the toys directory.)</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600206
Rob Landley6882ee82008-02-12 18:41:34 -0600207<p>Execution starts in main() which trims any path off of the first command
208name and calls toybox_main(), which calls toy_exec(), which calls toy_find()
Rob Landley66a69d92012-01-16 01:44:17 -0600209and toy_init() before calling the appropriate command's function from
210toy_list[] (via toys.which->toy_main()).
Rob Landley6882ee82008-02-12 18:41:34 -0600211If the command is "toybox", execution recurses into toybox_main(), otherwise
212the call goes to the appropriate commandname_main() from a C file in the toys
213directory.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600214
Rob Landley6882ee82008-02-12 18:41:34 -0600215<p>The following global variables are defined in main.c:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600216<ul>
Rob Landley66a69d92012-01-16 01:44:17 -0600217<a name="toy_list" />
218<li><p><b>struct toy_list toy_list[]</b> - array describing all the
Rob Landley4e68de12007-12-13 07:00:27 -0600219commands currently configured into toybox. The first entry (toy_list[0]) is
220for the "toybox" multiplexer command, which runs all the other built-in commands
221without symlinks by using its first argument as the name of the command to
222run and the rest as that command's argument list (ala "./toybox echo hello").
223The remaining entries are the commands in alphabetical order (for efficient
224binary search).</p>
225
226<p>This is a read-only array initialized at compile time by
Rob Landley6882ee82008-02-12 18:41:34 -0600227defining macros and #including generated/newtoys.h.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600228
Rob Landley66a69d92012-01-16 01:44:17 -0600229<p>Members of struct toy_list (defined in "toys.h") include:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600230<ul>
231<li><p>char *<b>name</b> - the name of this command.</p></li>
232<li><p>void (*<b>toy_main</b>)(void) - function pointer to run this
233command.</p></li>
234<li><p>char *<b>options</b> - command line option string (used by
235get_optflags() in lib/args.c to intialize toys.optflags, toys.optargs, and
Rob Landley66a69d92012-01-16 01:44:17 -0600236entries in the toy's DEFINE_GLOBALS struct). When this is NULL, no option
237parsing is done before calling toy_main().</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600238<li><p>int <b>flags</b> - Behavior flags for this command. The following flags are currently understood:</p>
239
240<ul>
241<li><b>TOYFLAG_USR</b> - Install this command under /usr</li>
242<li><b>TOYFLAG_BIN</b> - Install this command under /bin</li>
243<li><b>TOYFLAG_SBIN</b> - Install this command under /sbin</li>
244<li><b>TOYFLAG_NOFORK</b> - This command can be used as a shell builtin.</li>
245<li><b>TOYFLAG_UMASK</b> - Call umask(0) before running this command.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600246<li><b>TOYFLAG_STAYROOT</b> - Don't drop permissions for this command if toybox is installed SUID root.</li>
247<li><b>TOYFLAG_NEEDROOT</b> - This command cannot function unless run with root access.</li>
Rob Landley6882ee82008-02-12 18:41:34 -0600248</ul>
249<br>
250
251<p>These flags are combined with | (or). For example, to install a command
252in /usr/bin, or together TOYFLAG_USR|TOYFLAG_BIN.</p>
253</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600254</li>
255
Rob Landley66a69d92012-01-16 01:44:17 -0600256<li><p><b>struct toy_context toys</b> - global structure containing information
257common to all commands, initializd by toy_init() and defined in "toys.h".
258Members of this structure include:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600259<ul>
260<li><p>struct toy_list *<b>which</b> - a pointer to this command's toy_list
261structure. Mostly used to grab the name of the running command
262(toys->which.name).</p>
263</li>
264<li><p>int <b>exitval</b> - Exit value of this command. Defaults to zero. The
265error_exit() functions will return 1 if this is zero, otherwise they'll
266return this value.</p></li>
267<li><p>char **<b>argv</b> - "raw" command line options, I.E. the original
268unmodified string array passed in to main(). Note that modifying this changes
Rob Landley66a69d92012-01-16 01:44:17 -0600269"ps" output, and is not recommended. This array is null terminated; a NULL
270entry indicates the end of the array.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600271<p>Most commands don't use this field, instead the use optargs, optflags,
Rob Landley66a69d92012-01-16 01:44:17 -0600272and the fields in the DEFINE_GLOBALS struct initialized by get_optflags().</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600273</li>
274<li><p>unsigned <b>optflags</b> - Command line option flags, set by
Rob Landley66a69d92012-01-16 01:44:17 -0600275<a href="#lib_args">get_optflags()</a>. Indicates which of the command line options listed in
Rob Landley6882ee82008-02-12 18:41:34 -0600276toys->which.options occurred this time.</p>
277
278<p>The rightmost command line argument listed in toys->which.options sets bit
2791, the next one sets bit 2, and so on. This means the bits are set in the same
280order the binary digits would be listed if typed out as a string. For example,
281the option string "abcd" would parse the command line "-c" to set optflags to 2,
282"-a" would set optflags to 8, and "-bd" would set optflags to 6 (4|2).</p>
283
284<p>Only letters are relevant to optflags. In the string "a*b:c#d", d=1, c=2,
285b=4, a=8. The punctuation after a letter initializes global variables
286(see [TODO] DECLARE_GLOBALS() for details).</p>
287
Rob Landley66a69d92012-01-16 01:44:17 -0600288<p>For more information on option parsing, see <a href="#lib_args">get_optflags()</a>.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600289
290</li>
Rob Landley4e68de12007-12-13 07:00:27 -0600291<li><p>char **<b>optargs</b> - Null terminated array of arguments left over
292after get_optflags() removed all the ones it understood. Note: optarg[0] is
293the first argument, not the command name. Use toys.which->name for the command
294name.</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600295<li><p>int <b>optc</b> - Optarg count, equivalent to argc but for
296optargs[].<p></li>
Rob Landley4e68de12007-12-13 07:00:27 -0600297<li><p>int <b>exithelp</b> - Whether error_exit() should print a usage message
298via help_main() before exiting. (True during option parsing, defaults to
299false afterwards.)</p></li>
Rob Landley66a69d92012-01-16 01:44:17 -0600300</ul>
Rob Landley4e68de12007-12-13 07:00:27 -0600301
Rob Landley66a69d92012-01-16 01:44:17 -0600302<li><p><b>union toy_union this</b> - Union of structures containing each
Rob Landley4e68de12007-12-13 07:00:27 -0600303command's global variables.</p>
304
Rob Landley6882ee82008-02-12 18:41:34 -0600305<p>Global variables are useful: they reduce the overhead of passing extra
306command line arguments between functions, they conveniently start prezeroed to
307save initialization costs, and the command line argument parsing infrastructure
308can also initialize global variables with its results.</p>
309
310<p>But since each toybox process can only run one command at a time, allocating
311space for global variables belonging to other commands you aren't currently
312running would be wasteful.</p>
313
314<p>Toybox handles this by encapsulating each command's global variables in
Rob Landley66a69d92012-01-16 01:44:17 -0600315a structure, and declaring a union of those structures with a single global
316instance (called "this"). The DEFINE_GLOBALS() macro contains the global
317variables that should go in the current command's global structure. Each
318variable can then be accessed as "this.commandname.varname".
Rob Landley6882ee82008-02-12 18:41:34 -0600319Generally, the macro TT is #defined to this.commandname so the variable
Rob Landley66a69d92012-01-16 01:44:17 -0600320can then be accessed as "TT.variable". See toys/hello.c for an example.</p>
Rob Landley6882ee82008-02-12 18:41:34 -0600321
Rob Landley66a69d92012-01-16 01:44:17 -0600322<p>A command that needs global variables should declare a structure to
Rob Landley4e68de12007-12-13 07:00:27 -0600323contain them all, and add that structure to this union. A command should never
324declare global variables outside of this, because such global variables would
325allocate memory when running other commands that don't use those global
326variables.</p>
327
Rob Landley66a69d92012-01-16 01:44:17 -0600328<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 -0600329as specified by the options field off this command's toy_list entry. See
330the get_optargs() description in lib/args.c for details.</p>
331</li>
332
Rob Landley81b899d2007-12-18 02:02:47 -0600333<li><b>char toybuf[4096]</b> - a common scratch space buffer so
Rob Landley4e68de12007-12-13 07:00:27 -0600334commands don't need to allocate their own. Any command is free to use this,
335and it should never be directly referenced by functions in lib/ (although
336commands are free to pass toybuf in to a library function as an argument).</li>
337</ul>
338
Rob Landley6882ee82008-02-12 18:41:34 -0600339<p>The following functions are defined in main.c:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600340<ul>
341<li><p>struct toy_list *<b>toy_find</b>(char *name) - Return the toy_list
342structure for this command name, or NULL if not found.</p></li>
Rob Landley81b899d2007-12-18 02:02:47 -0600343<li><p>void <b>toy_init</b>(struct toy_list *which, char *argv[]) - fill out
344the global toys structure, calling get_optargs() if necessary.</p></li>
Rob Landley6882ee82008-02-12 18:41:34 -0600345<li><p>void <b>toy_exec</b>(char *argv[]) - Run a built-in command with
346arguments.</p>
347<p>Calls toy_find() on argv[0] (which must be just a command name
Rob Landley4e68de12007-12-13 07:00:27 -0600348without path). Returns if it can't find this command, otherwise calls
Rob Landley6882ee82008-02-12 18:41:34 -0600349toy_init(), toys->which.toy_main(), and exit() instead of returning.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600350
Rob Landley6882ee82008-02-12 18:41:34 -0600351<p>Use the library function xexec() to fall back to external executables
352in $PATH if toy_exec() can't find a built-in command. Note that toy_exec()
353does not strip paths before searching for a command, so "./command" will
354never match an internal command.</li>
355
356<li><p>void <b>toybox_main</b>(void) - the main function for the multiplexer
357command (I.E. "toybox"). Given a command name as its first argument, calls
358toy_exec() on its arguments. With no arguments, it lists available commands.
359If the first argument starts with "-" it lists each command with its default
360install path prepended.</p></li>
Rob Landley4e68de12007-12-13 07:00:27 -0600361
362</ul>
363
364<h3>Config.in</h3>
365
366<p>Top level configuration file in a stylized variant of
Rob Landley6882ee82008-02-12 18:41:34 -0600367<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 -0600368
369<p>These files are directly used by "make menuconfig" to select which commands
370to build into toybox (thus generating a .config file), and by
Rob Landley6882ee82008-02-12 18:41:34 -0600371scripts/config2help.py to create generated/help.h.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600372
373<h3>Temporary files:</h3>
374
Rob Landley6882ee82008-02-12 18:41:34 -0600375<p>There is one temporary file in the top level source directory:</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600376<ul>
377<li><p><b>.config</b> - Configuration file generated by kconfig, indicating
378which commands (and options to commands) are currently enabled. Used
Rob Landley6882ee82008-02-12 18:41:34 -0600379to make generated/config.h and determine which toys/*.c files to build.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600380
Rob Landley6882ee82008-02-12 18:41:34 -0600381<p>You can create a human readable "miniconfig" version of this file using
Rob Landley66a69d92012-01-16 01:44:17 -0600382<a href=http://landley.net/aboriginal/new_platform.html#miniconfig>these
Rob Landley6882ee82008-02-12 18:41:34 -0600383instructions</a>.</p>
384</li>
385</ul>
386
Rob Landleye7c9a6d2012-02-28 06:34:09 -0600387<a name="generated" />
Rob Landley6882ee82008-02-12 18:41:34 -0600388<p>The "generated/" directory contains files generated from other source code
389in toybox. All of these files can be recreated by the build system, although
390some (such as generated/help.h) are shipped in release versions to reduce
391environmental dependencies (I.E. so you don't need python on your build
392system).</p>
393
394<ul>
395<li><p><b>generated/config.h</b> - list of CFG_SYMBOL and USE_SYMBOL() macros,
Rob Landley4e68de12007-12-13 07:00:27 -0600396generated from .config by a sed invocation in the top level Makefile.</p>
397
398<p>CFG_SYMBOL is a comple time constant set to 1 for enabled symbols and 0 for
Rob Landley6882ee82008-02-12 18:41:34 -0600399disabled symbols. This allows the use of normal if() statements to remove
400code at compile time via the optimizer's dead code elimination (which removes
401from the binary any code that cannot be reached). This saves space without
Rob Landley4e68de12007-12-13 07:00:27 -0600402cluttering the code with #ifdefs or leading to configuration dependent build
403breaks. (See the 1992 Usenix paper
Rob Landleyb6063de2012-01-29 13:54:13 -0600404<a href=http://doc.cat-v.org/henry_spencer/ifdef_considered_harmful.pdf>#ifdef
Rob Landley4e68de12007-12-13 07:00:27 -0600405Considered Harmful</a> for more information.)</p>
406
407<p>USE_SYMBOL(code) evaluates to the code in parentheses when the symbol
408is enabled, and nothing when the symbol is disabled. This can be used
409for things like varargs or variable declarations which can't always be
Rob Landley6882ee82008-02-12 18:41:34 -0600410eliminated by a simple test on CFG_SYMBOL. Note that
Rob Landley4e68de12007-12-13 07:00:27 -0600411(unlike CFG_SYMBOL) this is really just a variant of #ifdef, and can
412still result in configuration dependent build breaks. Use with caution.</p>
413</li>
414</ul>
415
Rob Landley81b899d2007-12-18 02:02:47 -0600416<p><h2>Directory toys/</h2></p>
Rob Landley4e68de12007-12-13 07:00:27 -0600417
418<h3>toys/Config.in</h3>
419
420<p>Included from the top level Config.in, contains one or more
421configuration entries for each command.</p>
422
Rob Landley81b899d2007-12-18 02:02:47 -0600423<p>Each command has a configuration entry matching the command name (although
424configuration symbols are uppercase and command names are lower case).
Rob Landley4e68de12007-12-13 07:00:27 -0600425Options to commands start with the command name followed by an underscore and
Rob Landley66a69d92012-01-16 01:44:17 -0600426the option name. Global options are attached to the "toybox" command,
Rob Landley4e68de12007-12-13 07:00:27 -0600427and thus use the prefix "TOYBOX_". This organization is used by
Rob Landley81b899d2007-12-18 02:02:47 -0600428scripts/cfg2files to select which toys/*.c files to compile for a given
429.config.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600430
Rob Landley66a69d92012-01-16 01:44:17 -0600431<p>A command with multiple names (or multiple similar commands implemented in
Rob Landley4e68de12007-12-13 07:00:27 -0600432the same .c file) should have config symbols prefixed with the name of their
433C file. I.E. config symbol prefixes are NEWTOY() names. If OLDTOY() names
434have config symbols they're options (symbols with an underscore and suffix)
435to the NEWTOY() name. (See toys/toylist.h)</p>
436
437<h3>toys/toylist.h</h3>
Rob Landley81b899d2007-12-18 02:02:47 -0600438<p>The first half of this file prototypes all the structures to hold
Rob Landleyda09b7f2007-12-20 06:29:59 -0600439global variables for each command, and puts them in toy_union. These
440prototypes are only included if the macro NEWTOY isn't defined (in which
441case NEWTOY is defined to a default value that produces function
442prototypes).</p>
Rob Landley81b899d2007-12-18 02:02:47 -0600443
Rob Landleyda09b7f2007-12-20 06:29:59 -0600444<p>The second half of this file lists all the commands in alphabetical
445order, along with their command line arguments and install location.
446Each command has an appropriate configuration guard so only the commands that
447are enabled wind up in the list.</p>
448
449<p>The first time this header is #included, it defines structures and
450produces function prototypes for the commands in the toys directory.</p>
451
452
453<p>The first time it's included, it defines structures and produces function
454prototypes.
455 This
Rob Landley81b899d2007-12-18 02:02:47 -0600456is used to initialize toy_list in main.c, and later in that file to initialize
457NEED_OPTIONS (to figure out whether the command like parsing logic is needed),
458and to put the help entries in the right order in toys/help.c.</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600459
460<h3>toys/help.h</h3>
461
462<p>#defines two help text strings for each command: a single line
463command_help and an additinal command_help_long. This is used by help_main()
464in toys/help.c to display help for commands.</p>
465
466<p>Although this file is generated from Config.in help entries by
467scripts/config2help.py, it's shipped in release tarballs so you don't need
468python on the build system. (If you check code out of source control, or
469modify Config.in, then you'll need python installed to rebuild it.)</p>
470
471<p>This file contains help for all commands, regardless of current
472configuration, but only the currently enabled ones are entered into help_data[]
473in toys/help.c.</p>
474
Rob Landley137bf342012-03-09 08:33:57 -0600475<a name="lib">
Rob Landley81b899d2007-12-18 02:02:47 -0600476<h2>Directory lib/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600477
Rob Landley137bf342012-03-09 08:33:57 -0600478<p>TODO: document lots more here.</p>
479
Rob Landleyc8d0da52012-07-15 17:47:08 -0500480<p>lib: getmountlist(), error_msg/error_exit, xmalloc(),
Rob Landley7c04f012008-01-20 19:00:16 -0600481strlcpy(), xexec(), xopen()/xread(), xgetcwd(), xabspath(), find_in_path(),
482itoa().</p>
483
Rob Landley137bf342012-03-09 08:33:57 -0600484<h3>lib/portability.h</h3>
485
486<p>This file is automatically included from the top of toys.h, and smooths
487over differences between platforms (hardware targets, compilers, C libraries,
488operating systems, etc).</p>
489
490<p>This file provides SWAP macros (SWAP_BE16(x) and SWAP_LE32(x) and so on).</p>
491
492<p>A macro like SWAP_LE32(x) means "The value in x is stored as a little
493endian 32 bit value, so perform the translation to/from whatever the native
49432-bit format is". You do the swap once on the way in, and once on the way
495out. If your target is already little endian, the macro is a NOP.</p>
496
497<p>The SWAP macros come in BE and LE each with 16, 32, and 64 bit versions.
498In each case, the name of the macro refers to the _external_ representation,
499and converts to/from whatever your native representation happens to be (which
500can vary depending on what you're currently compiling for).</p>
501
Rob Landleyc8d0da52012-07-15 17:47:08 -0500502<a name="lib_llist"><h3>lib/llist.c</h3>
503
504<p>Some generic single and doubly linked list functions, which take
505advantage of a couple properties of C:</p>
506
507<ul>
508<li><p>Structure elements are laid out in memory in the order listed, and
509the first element has no padding. This means you can always treat (typecast)
510a pointer to a structure as a pointer to the first element of the structure,
511even if you don't know anything about the data following it.</p></li>
512
513<li><p>An array of length zero at the end of a structure adds no space
514to the sizeof() the structure, but if you calculate how much extra space
515you want when you malloc() the structure it will be available at the end.
516Since C has no bounds checking, this means each struct can have one variable
517length array.</p></li>
518</ul>
519
520<p>Toybox's list structures always have their <b>next</b> pointer as
521the first entry of each struct, and singly linked lists end with a NULL pointer.
522This allows generic code to traverse such lists without knowing anything
523else about the specific structs composing them: if your pointer isn't NULL
524typecast it to void ** and dereference once to get the next entry.</p>
525
526<p><b>lib/lib.h</b> defines three structure types:</p>
527<ul>
528<li><p><b>struct string_list</b> - stores a single string (<b>char str[0]</b>),
529memory for which is allocated as part of the node. (I.E. llist_traverse(list,
530free); can clean up after this type of list.)</p></li>
531
532<li><p><b>struct arg_list</b> - stores a pointer to a single string
533(<b>char *arg</b>) which is stored in a separate chunk of memory.</p></li>
534
535<li><p><b>struct double_list</b> - has a second pointer (<b>struct double_list
536*prev</b> along with a <b>char *data</b> for payload.</p></li>
537</ul>
538
539<b>List Functions</b>
540
541<ul>
542<li><p>void *<b>llist_pop</b>(void **list) - advances through a list ala
543<b>node = llist_pop(&list);</b> This doesn't modify the list contents,
544but does advance the pointer you feed it (which is why you pass the _address_
545of that pointer, not the pointer itself).</p></li>
546
547<li><p>void <b>llist_traverse</b>(void *list, void (*using)(void *data)) -
548iterate through a list calling a function on each node.</p></li>
549
550<li><p>struct double_list *<b>dlist_add</b>(struct double_list **llist, char *data)
551- append an entry to a circular linked list.
552This function allocates a new struct double_list wrapper and returns the
553pointer to the new entry (which you can usually ignore since it's llist->prev,
554but if llist was NULL you need it). The argument is the ->data field for the
555new node.</p></li>
556<ul><li><p>void <b>dlist_add_nomalloc</b>(struct double_list **llist,
557struct double_list *new) - append existing struct double_list to
558list, does not allocate anything.</p></li></ul>
559</ul>
560
561<b>Trivia questions:</b>
562
563<ul>
564<li><p><b>Why do arg_list and double_list contain a char * payload instead of
565a void *?</b> - Because you always have to typecast a void * to use it, and
566typecasting a char * does no harm. Thus having it default to the most common
567pointer type saves a few typecasts (strings are the most common payload),
568and doesn't hurt anything otherwise.</p>
569</li>
570
571<li><p><b>Why do the names ->str, ->arg, and ->data differ?</b> - To force
572you to keep track of which one you're using, calling free(node->str) would
573be bad, and _failing_ to free(node->arg) leaks memory.</p></li>
574
575<li><p><b>Why does llist_pop() take a void * instead of void **?</b> -
576because the stupid compiler complains about "type punned pointers" when
577you typecast and dereference ont he same line,
578due to insane FSF developers hardwiring limitations of their optimizer
579into gcc's warning system. Since C automatically typecasts any other
580pointer _down_ to a void *, the current code works fine. It's sad that it
581won't warn you if you forget the &, but the code crashes pretty quickly in
582that case.</p></li>
583
584<li><p><b>How do I assemble a singly-linked-list in order?</b> - use
585a double_list, dlist_add() your entries, and then break the circle with
586<b>list->prev->next = NULL;</b> when done.</li>
587</ul>
588
Rob Landley66a69d92012-01-16 01:44:17 -0600589<a name="lib_args"><h3>lib/args.c</h3>
Rob Landley7c04f012008-01-20 19:00:16 -0600590
Rob Landley66a69d92012-01-16 01:44:17 -0600591<p>Toybox's main.c automatically parses command line options before calling the
592command's main function. Option parsing starts in get_optflags(), which stores
593results in the global structures "toys" (optflags and optargs) and "this".</p>
594
595<p>The option parsing infrastructure stores a bitfield in toys.optflags to
596indicate which options the current command line contained. Arguments
597attached to those options are saved into the command's global structure
598("this"). Any remaining command line arguments are collected together into
599the null-terminated array toys.optargs, with the length in toys.optc. (Note
600that toys.optargs does not contain the current command name at position zero,
601use "toys.which->name" for that.) The raw command line arguments get_optflags()
602parsed are retained unmodified in toys.argv[].</p>
603
604<p>Toybox's option parsing logic is controlled by an "optflags" string, using
605a format reminiscent of getopt's optargs but has several important differences.
606Toybox does not use the getopt()
607function out of the C library, get_optflags() is an independent implementation
608which doesn't permute the original arguments (and thus doesn't change how the
609command is displayed in ps and top), and has many features not present in
610libc optargs() (such as the ability to describe long options in the same string
611as normal options).</p>
612
613<p>Each command's NEWTOY() macro has an optflags string as its middle argument,
614which sets toy_list.options for that command to tell get_optflags() what
615command line arguments to look for, and what to do with them.
616If a command has no option
617definition string (I.E. the argument is NULL), option parsing is skipped
618for that command, which must look at the raw data in toys.argv to parse its
619own arguments. (If no currently enabled command uses option parsing,
620get_optflags() is optimized out of the resulting binary by the compiler's
621--gc-sections option.)</p>
622
623<p>You don't have to free the option strings, which point into the environment
624space (I.E. the string data is not copied). A TOYFLAG_NOFORK command
625that uses the linked list type "*" should free the list objects but not
626the data they point to, via "llist_free(TT.mylist, NULL);". (If it's not
627NOFORK, exit() will free all the malloced data anyway unless you want
628to implement a CONFIG_TOYBOX_FREE cleanup for it.)</p>
629
630<h4>Optflags format string</h4>
631
632<p>Note: the optflags option description string format is much more
633concisely described by a large comment at the top of lib/args.c.</p>
634
635<p>The general theory is that letters set optflags, and punctuation describes
636other actions the option parsing logic should take.</p>
637
638<p>For example, suppose the command line <b>command -b fruit -d walrus -a 42</b>
639is parsed using the optflags string "<b>a#b:c:d</b>". (I.E.
640toys.which->options="a#b:c:d" and argv = ["command", "-b", "fruit", "-d",
641"walrus", "-a", "42"]). When get_optflags() returns, the following data is
642available to command_main():
643
644<ul>
645<li><p>In <b>struct toys</b>:
646<ul>
647<li>toys.optflags = 13; // -a = 8 | -b = 4 | -d = 1</li>
648<li>toys.optargs[0] = "walrus"; // leftover argument</li>
649<li>toys.optargs[1] = NULL; // end of list</li>
650<li>toys.optc=1; // there was 1 leftover argument</li>
651<li>toys.argv[] = {"-b", "fruit", "-d", "walrus", "-a", "42"}; // The original command line arguments
652</ul>
653<p></li>
654
655<li><p>In <b>union this</b> (treated as <b>long this[]</b>):
656<ul>
657<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>
658<li>this[1] = (long)"fruit"; // argument to -b</li>
659<li>this[2] = 42; // argument to -a</li>
660</ul>
661</p></li>
662</ul>
663
664<p>If the command's globals are:</p>
665
666<blockquote><pre>
667DECLARE_GLOBALS(
668 char *c;
669 char *b;
670 long a;
671)
672#define TT this.command
673</pre></blockquote>
674<p>That would mean TT.c == NULL, TT.b == "fruit", and TT.a == 42. (Remember,
675each entry that receives an argument must be a long or pointer, to line up
676with the array position. Right to left in the optflags string corresponds to
677top to bottom in DECLARE_GLOBALS().</p>
678
679<p><b>long toys.optflags</b></p>
680
681<p>Each option in the optflags string corresponds to a bit position in
682toys.optflags, with the same value as a corresponding binary digit. The
683rightmost argument is (1<<0), the next to last is (1<<1) and so on. If
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600684the option isn't encountered while parsing argv[], its bit remains 0.</p>
685
686<p>For example,
Rob Landley66a69d92012-01-16 01:44:17 -0600687the optflags string "abcd" would parse the command line argument "-c" to set
688optflags to 2, "-a" would set optflags to 8, "-bd" would set optflags to
6896 (I.E. 4|2), and "-a -c" would set optflags to 10 (2|8).</p>
690
691<p>Only letters are relevant to optflags, punctuation is skipped: in the
692string "a*b:c#d", d=1, c=2, b=4, a=8. The punctuation after a letter
693usually indicate that the option takes an argument.</p>
694
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600695<p>Since toys.optflags is an unsigned int, it only stores 32 bits. (Which is
696the amount a long would have on 32-bit platforms anyway; 64 bit code on
69732 bit platforms is too expensive to require in common code used by almost
698all commands.) Bit positions beyond the 1<<31 aren't recorded, but
699parsing higher options can still set global variables.</p>
700
Rob Landley66a69d92012-01-16 01:44:17 -0600701<p><b>Automatically setting global variables from arguments (union this)</b></p>
702
703<p>The following punctuation characters may be appended to an optflags
704argument letter, indicating the option takes an additional argument:</p>
705
706<ul>
707<li><b>:</b> - plus a string argument, keep most recent if more than one.</li>
708<li><b>*</b> - plus a string argument, appended to a linked list.</li>
Rob Landley66a69d92012-01-16 01:44:17 -0600709<li><b>@</b> - plus an occurrence counter (stored in a long)</li>
Rob Landleyb6063de2012-01-29 13:54:13 -0600710<li><b>#</b> - plus a signed long argument.
711<li><b>.</b> - plus a floating point argument (if CFG_TOYBOX_FLOAT).</li>
712<ul>The following can be appended to a float or double:
713<li><b>&lt;123</b> - error if argument is less than this</li>
714<li><b>&gt;123</b> - error if argument is greater than this</li>
715<li><b>=123</b> - default value if argument not supplied</li>
716</ul>
717<ul><li>Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT
718is enabled. (Otherwise the code to determine where floating point constants
719end drops out. When disabled, it can reserve a global data slot for the
720argument so offsets won't change, but will never fill it out.). You can handle
721this by using the USE_BLAH() macros with C string concatenation, ala:
722"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</li></ul>
Rob Landley66a69d92012-01-16 01:44:17 -0600723</ul>
724
725<p>Arguments may occur with or without a space (I.E. "-a 42" or "-a42").
726The command line argument "-abc" may be interepreted many different ways:
727the optflags string "cba" sets toys.optflags = 7, "c:ba" sets toys.optflags=4
728and saves "ba" as the argument to -c, and "cb:a" sets optflags to 6 and saves
729"c" as the argument to -b.</p>
730
731<p>Options which have an argument fill in the corresponding slot in the global
732union "this" (see generated/globals.h), treating it as an array of longs
733with the rightmost saved in this[0]. Again using "a*b:c#d", "-c 42" would set
734this[0]=42; and "-b 42" would set this[1]="42"; each slot is left NULL if
735the corresponding argument is not encountered.</p>
736
737<p>This behavior is useful because the LP64 standard ensures long and pointer
Rob Landleyb4a0efa2012-02-06 21:15:19 -0600738are the same size. C99 guarantees structure members will occur in memory
739in the same order they're declared, and that padding won't be inserted between
Rob Landley66a69d92012-01-16 01:44:17 -0600740consecutive variables of register size. Thus the first few entries can
741be longs or pointers corresponding to the saved arguments.</p>
742
743<p><b>char *toys.optargs[]</b></p>
744
745<p>Command line arguments in argv[] which are not consumed by option parsing
746(I.E. not recognized either as -flags or arguments to -flags) will be copied
747to toys.optargs[], with the length of that array in toys.optc.
748(When toys.optc is 0, no unrecognized command line arguments remain.)
749The order of entries is preserved, and as with argv[] this new array is also
750terminated by a NULL entry.</p>
751
752<p>Option parsing can require a minimum or maximum number of optargs left
753over, by adding "<1" (read "at least one") or ">9" ("at most nine") to the
754start of the optflags string.</p>
755
756<p>The special argument "--" terminates option parsing, storing all remaining
757arguments in optargs. The "--" itself is consumed.</p>
758
759<p><b>Other optflags control characters</b></p>
760
761<p>The following characters may occur at the start of each command's
762optflags string, before any options that would set a bit in toys.optflags:</p>
763
764<ul>
765<li><b>^</b> - stop at first nonoption argument (for nice, xargs...)</li>
766<li><b>?</b> - allow unknown arguments (pass non-option arguments starting
767with - through to optargs instead of erroring out).</li>
768<li><b>&amp;</b> - the first argument has imaginary dash (ala tar/ps. If given twice, all arguments have imaginary dash.)</li>
769<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>
770<li><b>&gt;</b> - must be followed by a decimal digit indicating at most this many leftover arguments allowed (default MAX_INT)</li>
771</ul>
772
773<p>The following characters may be appended to an option character, but do
774not by themselves indicate an extra argument should be saved in this[].
775(Technically any character not recognized as a control character sets an
776optflag, but letters are never control characters.)</p>
777
778<ul>
779<li><b>^</b> - stop parsing options after encountering this option, everything else goes into optargs.</li>
780<li><b>|</b> - this option is required. If more than one marked, only one is required.</li>
781<li><b>+X</b> enabling this option also enables option X (switch bit on).</li>
782<li><b>~X</b> enabling this option disables option X (switch bit off).</li>
783<li><b>!X</b> this option cannot be used in combination with X (die with error).</li>
784<li><b>[yz]</b> this option requires at least one of y or z to also be enabled.</li>
785</ul>
786
Rob Landleyb6063de2012-01-29 13:54:13 -0600787<p>The following may be appended to a float or double:</p>
788
789<ul>
790<li><b>&lt;123</b> - error if argument is less than this</li>
791<li><b>&gt;123</b> - error if argument is greater than this</li>
792<li><b>=123</b> - default value if argument not supplied</li>
793</ul>
794
795<p>Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT
796is enabled. (Otherwise the code to determine where floating point constants
797end drops out. When disabled, it can reserve a global data slot for the
798argument so offsets won't change, but will never fill it out.). You can handle
799this by using the USE_BLAH() macros with C string concatenation, ala:</p>
800
801<blockquote>"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</blockquote>
802
Rob Landley66a69d92012-01-16 01:44:17 -0600803<p><b>--longopts</b></p>
804
805<p>The optflags string can contain long options, which are enclosed in
806parentheses. They may be appended to an existing option character, in
807which case the --longopt is a synonym for that option, ala "a:(--fred)"
808which understands "-a blah" or "--fred blah" as synonyms.</p>
809
810<p>Longopts may also appear before any other options in the optflags string,
811in which case they have no corresponding short argument, but instead set
812their own bit based on position. So for "(walrus)#(blah)xy:z" "command
813--walrus 42" would set toys.optflags = 16 (-z = 1, -y = 2, -x = 4, --blah = 8)
814and would assign this[1] = 42;</p>
815
816<p>A short option may have multiple longopt synonyms, "a(one)(two)", but
817each "bare longopt" (ala "(one)(two)abc" before any option characters)
818always sets its own bit (although you can group them with +X).</p>
Rob Landley7c04f012008-01-20 19:00:16 -0600819
Rob Landleyc8d0da52012-07-15 17:47:08 -0500820<a name="lib_dirtree"><h3>lib/dirtree.c</h3>
821
822<p>The directory tree traversal code should be sufficiently generic
823that commands never need to use readdir(), scandir(), or the fts.h family
824of functions.</p>
825
826<p>These functions do not call chdir() or rely on PATH_MAX. Instead they
827use openat() and friends, using one filehandle per directory level to
828recurseinto subdirectories. (I.E. they can descend 1000 directories deep
829if setrlimit(RLIMIT_NOFILE) allows enough open filehandles, and the default
830in /proc/self/limits is generally 1024.)</p>
831
832<p>The basic dirtree functions are:</p>
833
834<ul>
835<li><p><b>dirtree_read(char *path, int (*callback)(struct dirtree node))</b> -
836recursively read directories, either applying callback() or returning
837a tree of struct dirtree if callback is NULL.</p></li>
838
839<li><p><b>dirtree_path(struct dirtree *node, int *plen)</b> - malloc() a
840string containing the path from the root of this tree to this node. If
841plen isn't NULL then *plen is how many extra bytes to malloc at the end
842of string.</p></li>
843
844<li><p><b>dirtree_parentfd(struct dirtree *node)</b> - return fd of
845containing directory, for use with openat() and such.</p></li>
846</ul>
847
848<p>The <b>dirtree_read()</b> function takes two arguments, a starting path for
849the root of the tree, and a callback function. The callback takes a
850<b>struct dirtree *</b> (from lib/lib.h) as its argument. If the callback is
851NULL, the traversal uses a default callback (dirtree_notdotdot()) which
852recursively assembles a tree of struct dirtree nodes for all files under
853this directory and subdirectories (filtering out "." and ".." entries),
854after which dirtree_read() returns the pointer to the root node of this
855snapshot tree.</p>
856
857<p>Otherwise the callback() is called on each entry in the directory,
858with struct dirtree * as its argument. This includes the initial
859node created by dirtree_read() at the top of the tree.</p>
860
861<p><b>struct dirtree</b></p>
862
863<p>Each struct dirtree node contains <b>char name[]</b> and <b>struct stat
864st</b> entries describing a file, plus a <b>char *symlink</b>
865which is NULL for non-symlinks.</p>
866
867<p>During a callback function, the <b>int data</b> field of directory nodes
868contains a dirfd (for use with the openat() family of functions). This is
869generally used by calling dirtree_parentfd() on the callback's node argument.
870For symlinks, data contains the length of the symlink string. On the second
871callback from DIRTREE_COMEAGAIN (depth-first traversal) data = -1 for
872all nodes (that's how you can tell it's the second callback).</p>
873
874<p>Users of this code may put anything they like into the <b>long extra</b>
875field. For example, "cp" and "mv" use this to store a dirfd for the destination
876directory (and use DIRTREE_COMEAGAIN to get the second callback so they can
877close(node->extra) to avoid running out of filehandles).
878This field is not directly used by the dirtree code, and
879thanks to LP64 it's large enough to store a typecast pointer to an
880arbitrary struct.</p>
881
882<p>The return value of the callback combines flags (with boolean or) to tell
883the traversal infrastructure how to behave:</p>
884
885<ul>
886<li><p><b>DIRTREE_SAVE</b> - Save this node, assembling a tree. (Without
887this the struct dirtree is freed after the callback returns. Filtering out
888siblings is fine, but discarding a parent while keeping its child leaks
889memory.)</p></li>
890<li><p><b>DIRTREE_ABORT</b> - Do not examine any more entries in this
891directory. (Does not propagate up tree: to abort entire traversal,
892return DIRTREE_ABORT from parent callbacks too.)</p></li>
893<li><p><b>DIRTREE_RECURSE</b> - Examine directory contents. Ignored for
894non-directory entries. The remaining flags only take effect when
895recursing into the children of a directory.</p></li>
896<li><p><b>DIRTREE_COMEAGAIN</b> - Call the callback a second time after
897examining all directory contents, allowing depth-first traversal.
898On the second call, dirtree->data = -1.</p></li>
899<li><p><b>DIRTREE_SYMFOLLOW</b> - follow symlinks when populating children's
900<b>struct stat st</b> (by feeding a nonzero value to the symfollow argument of
901dirtree_add_node()), which means DIRTREE_RECURSE treats symlinks to
902directories as directories. (Avoiding infinite recursion is the callback's
903problem: the non-NULL dirtree->symlink can still distinguish between
904them.)</p></li>
905</ul>
906
907<p>Each struct dirtree contains three pointers (next, parent, and child)
908to other struct dirtree.</p>
909
910<p>The <b>parent</b> pointer indicates the directory
911containing this entry; even when not assembling a persistent tree of
912nodes the parent entries remain live up to the root of the tree while
913child nodes are active. At the top of the tree the parent pointer is
914NULL, meaning the node's name[] is either an absolute path or relative
915to cwd. The function dirtree_parentfd() gets the directory file descriptor
916for use with openat() and friends, returning AT_FDCWD at the top of tree.</p>
917
918<p>The <b>child</b> pointer points to the first node of the list of contents of
919this directory. If the directory contains no files, or the entry isn't
920a directory, child is NULL.</p>
921
922<p>The <b>next</b> pointer indicates sibling nodes in the same directory as this
923node, and since it's the first entry in the struct the llist.c traversal
924mechanisms work to iterate over sibling nodes. Each dirtree node is a
925single malloc() (even char *symlink points to memory at the end of the node),
926so llist_free() works but its callback must descend into child nodes (freeing
927a tree, not just a linked list), plus whatever the user stored in extra.</p>
928
929<p>The <b>dirtree_read</b>() function is a simple wrapper, calling <b>dirtree_add_node</b>()
930to create a root node relative to the current directory, then calling
931<b>handle_callback</b>() on that node (which recurses as instructed by the callback
932return flags). Some commands (such as chgrp) bypass this wrapper, for example
933to control whether or not to follow symlinks to the root node; symlinks
934listed on the command line are often treated differently than symlinks
935encountered during recursive directory traversal).
936
937<p>The ls command not only bypasses the wrapper, but never returns
938<b>DIRTREE_RECURSE</b> from the callback, instead calling <b>dirtree_recurse</b>() manually
939from elsewhere in the program. This gives ls -lR manual control
940of traversal order, which is neither depth first nor breadth first but
941instead a sort of FIFO order requried by the ls standard.</p>
942
Rob Landley81b899d2007-12-18 02:02:47 -0600943<h2>Directory scripts/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600944
945<h3>scripts/cfg2files.sh</h3>
946
947<p>Run .config through this filter to get a list of enabled commands, which
948is turned into a list of files in toys via a sed invocation in the top level
949Makefile.
950</p>
951
Rob Landley81b899d2007-12-18 02:02:47 -0600952<h2>Directory kconfig/</h2>
Rob Landley4e68de12007-12-13 07:00:27 -0600953
954<p>Menuconfig infrastructure copied from the Linux kernel. See the
955Linux kernel's Documentation/kbuild/kconfig-language.txt</p>
956
Rob Landley66a69d92012-01-16 01:44:17 -0600957<a name="generated">
958<h2>Directory generated/</h2>
959
960<p>All the files in this directory except the README are generated by the
961build. (See scripts/make.sh)</p>
962
963<ul>
964<li><p><b>config.h</b> - CFG_COMMAND and USE_COMMAND() macros set by menuconfig via .config.</p></li>
965
966<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>
967
968<li><p><b>help.h</b> - Help text strings for use by "help" command. Building
969this file requires python on the host system, so the prebuilt file is shipped
970in the build tarball to avoid requiring python to build toybox.</p></li>
971
972<li><p><b>newtoys.h</b> - List of NEWTOY() or OLDTOY() macros for all available
973commands. Associates command_main() functions with command names, provides
974option string for command line parsing (<a href="#lib_args">see lib/args.c</a>),
975specifies where to install each command and whether toysh should fork before
976calling it.</p></li>
977</ul>
978
979<p>Everything in this directory is a derivative file produced from something
980else. The entire directory is deleted by "make distclean".</p>
Rob Landley4e68de12007-12-13 07:00:27 -0600981<!--#include file="footer.html" -->