code.html 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. <html><head><title>toybox source code walkthrough</title></head>
  2. <!--#include file="header.html" -->
  3. <p><h1><a name="style" /><a href="#style">Code style</a></h1></p>
  4. <p>The primary goal of toybox is _simple_ code. Keeping the code small is
  5. second, with speed and lots of features coming in somewhere after that.
  6. (For more on that, see the <a href=design.html>design</a> page.)</p>
  7. <p>A simple implementation usually takes up fewer lines of source code,
  8. meaning more code can fit on the screen at once, meaning the programmer can
  9. see more of it on the screen and thus keep more if in their head at once.
  10. This helps code auditing and thus reduces bugs. That said, sometimes being
  11. more explicit is preferable to being clever enough to outsmart yourself:
  12. don't be so terse your code is unreadable.</p>
  13. <p>Toybox has an actual coding style guide over on
  14. <a href=design.html#codestyle>the design page</a>, but in general we just
  15. want the code to be consistent.</p>
  16. <p><h1><a name="building" /><a href="#building">Building Toybox</a></h1></p>
  17. <p>Toybox is configured using the
  18. <a href=https://github.com/torvalds/linux/blob/v2.6.16/Documentation/kbuild/kconfig-language.txt>Kconfig language</a> pioneered by the Linux
  19. kernel, and adopted by many other projects (buildroot, OpenEmbedded, etc).
  20. This generates a ".config" file containing the selected options, which
  21. controls which features are included when compiling toybox.</p>
  22. <p>Each configuration option has a default value. The defaults indicate the
  23. "maximum sane configuration", I.E. if the feature defaults to "n" then it
  24. either isn't complete or is a special-purpose option (such as debugging
  25. code) that isn't intended for general purpose use.</p>
  26. <p>For a more compact human-editable version .config files, you can use the
  27. <a href=http://landley.net/aboriginal/FAQ.html#dev_miniconfig>miniconfig</a>
  28. format.</p>
  29. <p>The standard build invocation is:</p>
  30. <ul>
  31. <li>make defconfig #(or menuconfig)</li>
  32. <li>make</li>
  33. <li>make install</li>
  34. </ul>
  35. <p>Type "make help" to see all available build options.</p>
  36. <p>The file "configure" contains a number of environment variable definitions
  37. which influence the build, such as specifying which compiler to use or where
  38. to install the resulting binaries. This file is included by the build, but
  39. accepts existing definitions of the environment variables, so it may be sourced
  40. or modified by the developer before building and the definitions exported
  41. to the environment will take precedence.</p>
  42. <p>(To clarify: ".config" lists the features selected by defconfig/menuconfig,
  43. I.E. "what to build", and "configure" describes the build and installation
  44. environment, I.E. "how to build it".)</p>
  45. <p>By default "make install" puts files in /usr/toybox. Adding this to the
  46. $PATH is up to you. The environment variable $PREFIX can change the
  47. install location, ala "PREFIX=/usr/local/bin make install".</p>
  48. <p>If you need an unstripped (debug) version of any of these binaries,
  49. look in generated/unstripped.</p>
  50. <p><h1><a name="running"><a href="#running">Running a command</a></h1></p>
  51. <h2>main</h2>
  52. <p>The toybox main() function is at the end of main.c at the top level. It has
  53. two possible codepaths, only one of which is configured into any given build
  54. of toybox.</p>
  55. <p>If CONFIG_SINGLE is selected, toybox is configured to contain only a single
  56. command, so most of the normal setup can be skipped. In this case the
  57. multiplexer isn't used, instead main() calls toy_singleinit() (also in main.c)
  58. to set up global state and parse command line arguments, calls the command's
  59. main function out of toy_list (in the CONFIG_SINGLE case the array has a single entry, no need to search), and if the function returns instead of exiting
  60. it flushes stdout (detecting error) and returns toys.exitval.</p>
  61. <p>When CONFIG_SINGLE is not selected, main() uses basename() to find the
  62. name it was run as, shifts its argument list one to the right so it lines up
  63. with where the multiplexer function expects it, and calls toybox_main(). This
  64. leverages the multiplexer command's infrastructure to find and run the
  65. appropriate command. (A command name starting with "toybox" will
  66. recursively call toybox_main(); you can go "./toybox toybox toybox toybox ls"
  67. if you want to...)</p>
  68. <h2>toybox_main</h2>
  69. <p>The toybox_main() function is also in main,c. It handles a possible
  70. --help option ("toybox --help ls"), prints the list of available commands if no
  71. arguments were provided to the multiplexer (or with full path names if any
  72. other option is provided before a command name, ala "toybox --list").
  73. Otherwise it calls toy_exec() on its argument list.</p>
  74. <p>Note that the multiplexer is the first entry in toy_list (the rest of the
  75. list is sorted alphabetically to allow binary search), so toybox_main can
  76. cheat and just grab the first entry to quickly set up its context without
  77. searching. Since all command names go through the multiplexer at least once
  78. in the non-TOYBOX_SINGLE case, this avoids a redundant search of
  79. the list.</p>
  80. <p>The toy_exec() function is also in main.c. It performs toy_find() to
  81. perform a binary search on the toy_list array to look up the command's
  82. entry by name and saves it in the global variable which, calls toy_init()
  83. to parse command line arguments and set up global state (using which->options),
  84. and calls the appropriate command's main() function (which->toy_main). On
  85. return it flushes all pending ansi FILE * I/O, detects if stdout had an
  86. error, and then calls xexit() (which uses toys.exitval).</p>
  87. <p><h1><a name="infrastructure" /><a href="#infrastructure">Infrastructure</a></h1></p>
  88. <p>The toybox source code is in following directories:</p>
  89. <ul>
  90. <li>The <a href="#top">top level directory</a> contains the file main.c (were
  91. execution starts), the header file toys.h (included by every command), and
  92. other global infrastructure.</li>
  93. <li>The <a href="#lib">lib directory</a> contains common functions shared by
  94. multiple commands:</li>
  95. <ul>
  96. <li><a href="#lib_lib">lib/lib.c</a></li>
  97. <li><a href="#lib_xwrap">lib/xwrap.c</a></li>
  98. <li><a href="#lib_llist">lib/llist.c</a></li>
  99. <li><a href="#lib_args">lib/args.c</a></li>
  100. <li><a href="#lib_dirtree">lib/dirtree.c</a></li>
  101. </ul>
  102. <li>The <a href="#toys">toys directory</a> contains the C files implementating
  103. each command. Currently it contains five subdirectories categorizing the
  104. commands: posix, lsb, other, example, and pending.</li>
  105. <li>The <a href="#scripts">scripts directory</a> contains the build and
  106. test infrastructure.</li>
  107. <li>The <a href="#kconfig">kconfig directory</a> contains the configuration
  108. infrastructure implementing menuconfig (copied from the Linux kernel).</li>
  109. <li>The <a href="#generated">generated directory</a> contains intermediate
  110. files generated from other parts of the source code.</li>
  111. <li>The <a href="#tests">tests directory</a> contains the test suite.
  112. NOSPACE=1 to allow tests to pass with diff -b</li>
  113. </ul>
  114. <a name="adding" />
  115. <p><h1><a href="#adding">Adding a new command</a></h1></p>
  116. <p>To add a new command to toybox, add a C file implementing that command to
  117. one of the subdirectories under the toys directory. No other files need to
  118. be modified; the build extracts all the information it needs (such as command
  119. line arguments) from specially formatted comments and macros in the C file.
  120. (See the description of the <a href="#generated">"generated" directory</a>
  121. for details.)</p>
  122. <p>Currently there are five subdirectories under "toys", one for commands
  123. defined by the POSIX standard, one for commands defined by the Linux Standard
  124. Base, an "other" directory for commands not covered by an obvious standard,
  125. a directory of example commands (templates to use when starting new commands),
  126. and a "pending" directory of commands that need further review/cleanup
  127. before moving to one of the other directories (run these at your own risk,
  128. cleanup patches welcome).
  129. These directories are just for developer convenience sorting the commands,
  130. the directories are otherwise functionally identical. To add a new category,
  131. create the appropriate directory with a README file in it whose first line
  132. is the description menuconfig should use for the directory.)</p>
  133. <p>An easy way to start a new command is copy the file "toys/example/hello.c"
  134. to the name of the new command, and modify this copy to implement the new
  135. command (more or less by turning every instance of "hello" into the
  136. name of your command, updating the command line arguments, globals, and
  137. help data, and then filling out its "main" function with code that does
  138. something interesting).</p>
  139. <p>You could also start with "toys/example/skeleton.c", which provides a lot
  140. more example code (showing several variants of command line option
  141. parsing, how to implement multiple commands in the same file, and so on).
  142. But usually it's just more stuff to delete.</p>
  143. <p>Here's a checklist of steps to turn hello.c into another command:</p>
  144. <ul>
  145. <li><p>First "cp toys/example/hello.c toys/other/yourcommand.c" and open
  146. the new file in your preferred text editor.</p>
  147. <ul><li><p>Note that the
  148. name of the new file is significant: it's the name of the new command you're
  149. adding to toybox. The build includes all *.c files under toys/*/ whose
  150. names are a case insensitive match for an enabled config symbol. So
  151. toys/posix/cat.c only gets included if you have "CAT=y" in ".config".</p></li>
  152. </ul></p></li>
  153. <li><p>Change the one line comment at the top of the file (currently
  154. "hello.c - A hello world program") to describe your new file.</p></li>
  155. <li><p>Change the copyright notice to your name, email, and the current
  156. year.</p></li>
  157. <li><p>Give a URL to the relevant standards document, where applicable.
  158. (Sample links to SUSv4, LSB, IETF RFC, and man7.org are provided, feel free to
  159. link to other documentation or standards as appropriate.)</p></li>
  160. <li><p>Update the USE_YOURCOMMAND(NEWTOY(yourcommand,"blah",0)) line.
  161. The NEWTOY macro fills out this command's <a href="#toy_list">toy_list</a>
  162. structure. The arguments to the NEWTOY macro are:</p>
  163. <ol>
  164. <li><p>the name used to run your command</p></li>
  165. <li><p>the command line argument <a href="#lib_args">option parsing string</a> (0 if none)</p></li>
  166. <li><p>a bitfield of TOYFLAG values
  167. (defined in toys.h) providing additional information such as where your
  168. command should be installed on a running system, whether to blank umask
  169. before running, whether or not the command must run as root (and thus should
  170. retain root access if installed SUID), and so on.</p></li>
  171. </ol>
  172. </li>
  173. <li><p>Change the kconfig data (from "config YOURCOMMAND" to the end of the
  174. comment block) to supply your command's configuration and help
  175. information. The uppper case config symbols are used by menuconfig, and are
  176. also what the CFG_ and USE_() macros are generated from (see [TODO]). The
  177. help information here is used by menuconfig, and also by the "help" command to
  178. describe your new command. (See [TODO] for details.) By convention,
  179. unfinished commands default to "n" and finished commands default to "y",
  180. so "make defconfig" selects all finished commands. (Note, "finished" means
  181. "ready to be used", not that it'll never change again.)<p>
  182. <p>Each help block should start with a "usage: yourcommand" line explaining
  183. any command line arguments added by this config option. The "help" command
  184. outputs this text, and scripts/config2help.c in the build infrastructure
  185. collates these usage lines for commands with multiple configuration
  186. options when producing generated/help.h.</p>
  187. </li>
  188. <li><p>Change the "#define FOR_hello" line to "#define FOR_yourcommand" right
  189. before the "#include <toys.h>". (This selects the appropriate FLAG_ macros and
  190. does a "#define TT this.yourcommand" so you can access the global variables
  191. out of the space-saving union of structures. If you aren't using any command
  192. flag bits and aren't defining a GLOBAL block, you can delete this line.)</p></li>
  193. <li><p>Update the GLOBALS() macro to contain your command's global
  194. variables. If your command has no global variables, delete this macro.</p>
  195. <p>Variables in the GLOBALS() block are are stored in a space saving
  196. <a href="#toy_union">union of structures</a> format, which may be accessed
  197. using the TT macro as if TT were a global structure (so TT.membername).
  198. If you specified two-character command line arguments in
  199. NEWTOY(), the first few global variables will be initialized by the automatic
  200. argument parsing logic, and the type and order of these variables must
  201. correspond to the arguments specified in NEWTOY().
  202. (See <a href="#lib_args">lib/args.c</a> for details.)</p>
  203. <blockquote><p>NOTE: the GLOBALS() block creates a "this.filename" entry
  204. in generated/globals.h. If your toys/*/filename.c does not match the first
  205. command name, you'll need to "#define TT this.filename" yourself before
  206. #including toys.h if you want to use TT globals</p></blockquote>
  207. </li>
  208. <li><p>Rename hello_main() to yourcommand_main(). This is the main() function
  209. where execution of your command starts. Your command line options are
  210. already sorted into this.optflags, this.optargs, this.optc, and the GLOBALS()
  211. as appropriate by the time this function is called. (See
  212. <a href="#lib_args">get_optflags()</a> for details.)</p></li>
  213. <li><p>Switch on TOYBOX_DEBUG in menuconfig (toybox global settings menu)
  214. the first time you build and run your new command. If anything is wrong
  215. with your option string, that will give you error messages.</p>
  216. <p>Otherwise it'll just segfault without
  217. explanation when it falls off the end because it didn't find a matching
  218. end parantheses for a longopt, or you put a nonexistent option in a square
  219. bracket grouping... Since these kind of errors can only be caused by a
  220. developer, not by end users, we don't normally want runtime checks for
  221. them. Once you're happy with your option string, you can switch TOYBOX_DEBUG
  222. back off.</p></li>
  223. </ul>
  224. <a name="headers" /><h2><a href="#headers">Headers.</a></h2>
  225. <p>Commands are implemented as self-contained .c files, and generally don't
  226. have their own .h files. If it's common code put it in lib/, and if it's
  227. something like a local structure definition just put it in the command's .c
  228. file. If it would only ever be #included from one place, inline it.
  229. (The line between implementing multiple commands in a C file via OLDTOY()
  230. to share infrastructure and moving that shared infrastructure to lib/ is a
  231. judgement call. Try to figure out which is simplest.)</p>
  232. <p>The top level toys.h should #include all the standard (posix) headers
  233. that any command uses. (Partly this is friendly to ccache and partly this
  234. makes the command implementations shorter.) Individual commands should only
  235. need to include nonstandard headers that might prevent that command from
  236. building in some context we'd care about (and thus requiring that command to
  237. be disabled to avoid a build break).</p>
  238. <p>Target-specific stuff (differences between compiler versions, libc versions,
  239. or operating systems) should be confined to lib/portability.h and
  240. lib/portability.c. (There's even some minimal compile-time environment probing
  241. that writes data to generated/portability.h, see scripts/genconfig.sh.)</p>
  242. <p>Only include &lt;linux/*.h&gt; headers from individual commands (not from other
  243. headers), and only if you really need to. Data that varies per architecture
  244. is a good reason to include a header. If you just need a couple constants
  245. that haven't changed since the 1990's, it's ok to #define them yourself or
  246. just use the constant inline with a comment explaining what it is. (A
  247. #define that's only used once isn't really helping.)</p>
  248. <p><a name="top" /><h1><a href="#top">Top level directory.</a></h1></p>
  249. <p>This directory contains global infrastructure.</p>
  250. <h3>toys.h</h3>
  251. <p>Each command #includes "toys.h" as part of its standard prolog. It
  252. may "#define FOR_commandname" before doing so to get some extra entries
  253. specific to this command.</p>
  254. <p>This file sucks in most of the commonly used standard #includes, so
  255. individual files can just #include "toys.h" and not have to worry about
  256. stdargs.h and so on. Individual commands still need to #include
  257. special-purpose headers that may not be present on all systems (and thus would
  258. prevent toybox from building that command on such a system with that command
  259. enabled). Examples include regex support, any "linux/" or "asm/" headers, mtab
  260. support (mntent.h and sys/mount.h), and so on.</p>
  261. <p>The toys.h header also defines structures for most of the global variables
  262. provided to each command by toybox_main(). These are described in
  263. detail in the description for main.c, where they are initialized.</p>
  264. <p>The global variables are grouped into structures (and a union) for space
  265. savings, to more easily track the amount of memory consumed by them,
  266. so that they may be automatically cleared/initialized as needed, and so
  267. that access to global variables is more easily distinguished from access to
  268. local variables.</p>
  269. <h3>main.c</h3>
  270. <p>Contains the main() function where execution starts, plus
  271. common infrastructure to initialize global variables and select which command
  272. to run. The "toybox" multiplexer command also lives here. (This is the
  273. only command defined outside of the toys directory.)</p>
  274. <p>Execution starts in main() which trims any path off of the first command
  275. name and calls toybox_main(), which calls toy_exec(), which calls toy_find()
  276. and toy_init() before calling the appropriate command's function from
  277. toy_list[] (via toys.which->toy_main()).
  278. If the command is "toybox", execution recurses into toybox_main(), otherwise
  279. the call goes to the appropriate commandname_main() from a C file in the toys
  280. directory.</p>
  281. <p>The following global variables are defined in main.c:</p>
  282. <ul>
  283. <a name="toy_list" />
  284. <li><p><b>struct toy_list toy_list[]</b> - array describing all the
  285. commands currently configured into toybox. The first entry (toy_list[0]) is
  286. for the "toybox" multiplexer command, which runs all the other built-in commands
  287. without symlinks by using its first argument as the name of the command to
  288. run and the rest as that command's argument list (ala "./toybox echo hello").
  289. The remaining entries are the commands in alphabetical order (for efficient
  290. binary search).</p>
  291. <p>This is a read-only array initialized at compile time by
  292. defining macros and #including generated/newtoys.h.</p>
  293. <p>Members of struct toy_list (defined in "toys.h") include:</p>
  294. <ul>
  295. <li><p>char *<b>name</b> - the name of this command.</p></li>
  296. <li><p>void (*<b>toy_main</b>)(void) - function pointer to run this
  297. command.</p></li>
  298. <li><p>char *<b>options</b> - command line option string (used by
  299. get_optflags() in lib/args.c to intialize toys.optflags, toys.optargs, and
  300. entries in the toy's GLOBALS struct). When this is NULL, no option
  301. parsing is done before calling toy_main().</p></li>
  302. <li><p>int <b>flags</b> - Behavior flags for this command. The following flags are currently understood:</p>
  303. <ul>
  304. <li><b>TOYFLAG_USR</b> - Install this command under /usr</li>
  305. <li><b>TOYFLAG_BIN</b> - Install this command under /bin</li>
  306. <li><b>TOYFLAG_SBIN</b> - Install this command under /sbin</li>
  307. <li><b>TOYFLAG_NOFORK</b> - This command can be used as a shell builtin.</li>
  308. <li><b>TOYFLAG_UMASK</b> - Call umask(0) before running this command.</li>
  309. <li><b>TOYFLAG_STAYROOT</b> - Don't drop permissions for this command if toybox is installed SUID root.</li>
  310. <li><b>TOYFLAG_NEEDROOT</b> - This command cannot function unless run with root access.</li>
  311. </ul>
  312. <br>
  313. <p>These flags are combined with | (or). For example, to install a command
  314. in /usr/bin, or together TOYFLAG_USR|TOYFLAG_BIN.</p>
  315. </ul>
  316. </li>
  317. <li><p><b>struct toy_context toys</b> - global structure containing information
  318. common to all commands, initializd by toy_init() and defined in "toys.h".
  319. Members of this structure include:</p>
  320. <ul>
  321. <li><p>struct toy_list *<b>which</b> - a pointer to this command's toy_list
  322. structure. Mostly used to grab the name of the running command
  323. (toys->which.name).</p>
  324. </li>
  325. <li><p>int <b>exitval</b> - Exit value of this command. Defaults to zero. The
  326. error_exit() functions will return 1 if this is zero, otherwise they'll
  327. return this value.</p></li>
  328. <li><p>char **<b>argv</b> - "raw" command line options, I.E. the original
  329. unmodified string array passed in to main(). Note that modifying this changes
  330. "ps" output, and is not recommended. This array is null terminated; a NULL
  331. entry indicates the end of the array.</p>
  332. <p>Most commands don't use this field, instead the use optargs, optflags,
  333. and the fields in the GLOBALS struct initialized by get_optflags().</p>
  334. </li>
  335. <li><p>unsigned <b>optflags</b> - Command line option flags, set by
  336. <a href="#lib_args">get_optflags()</a>. Indicates which of the command line options listed in
  337. toys->which.options occurred this time.</p>
  338. <p>The rightmost command line argument listed in toys->which.options sets bit
  339. 1, the next one sets bit 2, and so on. This means the bits are set in the same
  340. order the binary digits would be listed if typed out as a string. For example,
  341. the option string "abcd" would parse the command line "-c" to set optflags to 2,
  342. "-a" would set optflags to 8, and "-bd" would set optflags to 6 (4|2).</p>
  343. <p>Only letters are relevant to optflags. In the string "a*b:c#d", d=1, c=2,
  344. b=4, a=8. Punctuation after a letter initializes global variables at the
  345. start of the GLOBALS() block (see <a href="#toy_union">union toy_union this</a>
  346. for details).</p>
  347. <p>The build infrastructure creates FLAG_ macros for each option letter,
  348. corresponding to the bit position, so you can check (toys.optflags & FLAG_x)
  349. to see if a flag was specified. (The correct set of FLAG_ macros is selected
  350. by defining FOR_mycommand before #including toys.h. The macros live in
  351. toys/globals.h which is generated by scripts/make.sh.)</p>
  352. <p>For more information on option parsing, see <a href="#lib_args">get_optflags()</a>.</p>
  353. </li>
  354. <li><p>char **<b>optargs</b> - Null terminated array of arguments left over
  355. after get_optflags() removed all the ones it understood. Note: optarg[0] is
  356. the first argument, not the command name. Use toys.which->name for the command
  357. name.</p></li>
  358. <li><p>int <b>optc</b> - Optarg count, equivalent to argc but for
  359. optargs[].<p></li>
  360. </ul>
  361. <a name="toy_union" />
  362. <li><p><b>union toy_union this</b> - Union of structures containing each
  363. command's global variables.</p>
  364. <p>Global variables are useful: they reduce the overhead of passing extra
  365. command line arguments between functions, they conveniently start prezeroed to
  366. save initialization costs, and the command line argument parsing infrastructure
  367. can also initialize global variables with its results.</p>
  368. <p>But since each toybox process can only run one command at a time, allocating
  369. space for global variables belonging to other commands you aren't currently
  370. running would be wasteful.</p>
  371. <p>Toybox handles this by encapsulating each command's global variables in
  372. a structure, and declaring a union of those structures with a single global
  373. instance (called "this"). The GLOBALS() macro contains the global
  374. variables that should go in the current command's global structure. Each
  375. variable can then be accessed as "this.commandname.varname".
  376. If you #defined FOR_commandname before including toys.h, the macro TT is
  377. #defined to this.commandname so the variable can then be accessed as
  378. "TT.variable". See toys/hello.c for an example.</p>
  379. <p>A command that needs global variables should declare a structure to
  380. contain them all, and add that structure to this union. A command should never
  381. declare global variables outside of this, because such global variables would
  382. allocate memory when running other commands that don't use those global
  383. variables.</p>
  384. <p>The first few fields of this structure can be intialized by <a href="#lib_args">get_optargs()</a>,
  385. as specified by the options field off this command's toy_list entry. See
  386. the get_optargs() description in lib/args.c for details.</p>
  387. </li>
  388. <li><b>char toybuf[4096]</b> - a common scratch space buffer guaranteed
  389. to start zeroed, so commands don't need to allocate/initialize their own.
  390. Any command is free to use this, and it should never be directly referenced
  391. by functions in lib/ (although commands are free to pass toybuf in to a
  392. library function as an argument).</li>
  393. <li><b>char libbuf[4096]</b> - like toybuf, but for use by common code in
  394. lib/*.c. Commands should never directly reference libbuf, and library
  395. could should nnever directly reference toybuf.</li>
  396. </ul>
  397. <p>The following functions are defined in main.c:</p>
  398. <ul>
  399. <li><p>struct toy_list *<b>toy_find</b>(char *name) - Return the toy_list
  400. structure for this command name, or NULL if not found.</p></li>
  401. <li><p>void <b>toy_init</b>(struct toy_list *which, char *argv[]) - fill out
  402. the global toys structure, calling get_optargs() if necessary.</p></li>
  403. <li><p>void <b>toy_exec</b>(char *argv[]) - Run a built-in command with
  404. arguments.</p>
  405. <p>Calls toy_find() on argv[0] (which must be just a command name
  406. without path). Returns if it can't find this command, otherwise calls
  407. toy_init(), toys->which.toy_main(), and exit() instead of returning.</p>
  408. <p>Use the library function xexec() to fall back to external executables
  409. in $PATH if toy_exec() can't find a built-in command. Note that toy_exec()
  410. does not strip paths before searching for a command, so "./command" will
  411. never match an internal command.</li>
  412. <li><p>void <b>toybox_main</b>(void) - the main function for the multiplexer
  413. command (I.E. "toybox"). Given a command name as its first argument, calls
  414. toy_exec() on its arguments. With no arguments, it lists available commands.
  415. If the first argument starts with "-" it lists each command with its default
  416. install path prepended.</p></li>
  417. </ul>
  418. <h3>Config.in</h3>
  419. <p>Top level configuration file in a stylized variant of
  420. <a href=http://kernel.org/doc/Documentation/kbuild/kconfig-language.txt>kconfig</a> format. Includes generated/Config.in.</p>
  421. <p>These files are directly used by "make menuconfig" to select which commands
  422. to build into toybox (thus generating a .config file), and by
  423. scripts/config2help.py to create generated/help.h.</p>
  424. <a name="generated" />
  425. <h1><a href="#generated">Temporary files:</a></h1>
  426. <p>There is one temporary file in the top level source directory:</p>
  427. <ul>
  428. <li><p><b>.config</b> - Configuration file generated by kconfig, indicating
  429. which commands (and options to commands) are currently enabled. Used
  430. to make generated/config.h and determine which toys/*/*.c files to build.</p>
  431. <p>You can create a human readable "miniconfig" version of this file using
  432. <a href=http://landley.net/aboriginal/new_platform.html#miniconfig>these
  433. instructions</a>.</p>
  434. </li>
  435. </ul>
  436. <p><h2>Directory generated/</h2></p>
  437. <p>The remaining temporary files live in the "generated/" directory,
  438. which is for files generated at build time from other source files.</p>
  439. <ul>
  440. <li><p><b>generated/Config.in</b> - Kconfig entries for each command, included
  441. from the top level Config.in. The help text here is used to generate
  442. help.h.</p>
  443. <p>Each command has a configuration entry with an upper case version of
  444. the command name. Options to commands start with the command
  445. name followed by an underscore and the option name. Global options are attached
  446. to the "toybox" command, and thus use the prefix "TOYBOX_". This organization
  447. is used by scripts/cfg2files to select which toys/*/*.c files to compile for a
  448. given .config.</p>
  449. </li>
  450. <li><p><b>generated/config.h</b> - list of CFG_SYMBOL and USE_SYMBOL() macros,
  451. generated from .config by a sed invocation in scripts/make.sh.</p>
  452. <p>CFG_SYMBOL is a comple time constant set to 1 for enabled symbols and 0 for
  453. disabled symbols. This allows the use of normal if() statements to remove
  454. code at compile time via the optimizer's dead code elimination (which removes
  455. from the binary any code that cannot be reached). This saves space without
  456. cluttering the code with #ifdefs or leading to configuration dependent build
  457. breaks. (See the 1992 Usenix paper
  458. <a href=http://doc.cat-v.org/henry_spencer/ifdef_considered_harmful.pdf>#ifdef
  459. Considered Harmful</a> for more information.)</p>
  460. <p>When you can't entirely avoid an #ifdef, the USE_SYMBOL(code) macro
  461. provides a less intrusive alternative, evaluating to the code in parentheses
  462. when the symbol is enabled, and nothing when the symbol is disabled. This
  463. is most commonly used around NEWTOY() declarations (so only the enabled
  464. commands show up in toy_list), and in option strings. This can also be used
  465. for things like varargs or structure members which can't always be
  466. eliminated by a simple test on CFG_SYMBOL. Remember, unlike CFG_SYMBOL
  467. this is really just a variant of #ifdef, and can still result in configuration
  468. dependent build breaks. Use with caution.</p>
  469. </li>
  470. <li><p><b>generated/flags.h</b> - FLAG_? macros indicating which command
  471. line options were seen. The option parsing in lib/args.c sets bits in
  472. toys.optflags, which can be tested by anding with the appropriate FLAG_
  473. macro. (Bare longopts, which have no corresponding short option, will
  474. have the longopt name after FLAG_. All others use the single letter short
  475. option.)</p>
  476. <p>To get the appropriate macros for your command, #define FOR_commandname
  477. before #including toys.h. To switch macro sets (because you have an OLDTOY()
  478. with different options in the same .c file), #define CLEANUP_oldcommand
  479. and also #define FOR_newcommand, then #include "generated/flags.h" to switch.
  480. </p>
  481. </li>
  482. <li><p><b>generated/globals.h</b> -
  483. Declares structures to hold the contents of each command's GLOBALS(),
  484. and combines them into "global_union this". (Yes, the name was
  485. chosen to piss off C++ developers who think that C
  486. is merely a subset of C++, not a language in its own right.)</p>
  487. <p>The union reuses the same memory for each command's global struct:
  488. since only one command's globals are in use at any given time, collapsing
  489. them together saves space. The headers #define TT to the appropriate
  490. "this.commandname", so you can refer to the current command's global
  491. variables out of "this" as TT.variablename.</p>
  492. <p>The globals start zeroed, and the first few are filled out by the
  493. lib/args.c argument parsing code called from main.c.</p>
  494. </li>
  495. <li><p><b>toys/help.h</b> - Help strings for use by the "help" command and
  496. --help options. This file #defines a help_symbolname string for each
  497. symbolname, but only the symbolnames matching command names get used
  498. by show_help() in lib/help.c to display help for commands.</p>
  499. <p>This file is created by scripts/make.sh, which compiles scripts/config2help.c
  500. into the binary generated/config2help, and then runs it against the top
  501. level .config and Config.in files to extract the help text from each config
  502. entry and collate together dependent options.</p>
  503. <p>This file contains help text for all commands, regardless of current
  504. configuration, but only the ones currently enabled in the .config file
  505. wind up in the help_data[] array, and only the enabled dependent options
  506. have their help text added to the command they depend on.</p>
  507. </li>
  508. <li><p><b>generated/newtoys.h</b> -
  509. All the NEWTOY() and OLDTOY() macros from toys/*/*.c. The "toybox" multiplexer
  510. is the first entry, the rest are in alphabetical order. Each line should be
  511. inside an appropriate USE_ macro, so code that #includes this file only sees
  512. the currently enabled commands.</p>
  513. <p>By #definining NEWTOY() to various things before #including this file,
  514. it may be used to create function prototypes (in toys.h), initialize the
  515. help_data array (in lib/help.c), initialize the toy_list array (in main.c,
  516. the alphabetical order lets toy_find() do a binary search, the exception to
  517. the alphabetical order lets it use the multiplexer without searching), and so
  518. on. (It's even used to initialize the NEED_OPTIONS macro, which produces a 1
  519. or 0 for each command using command line option parsing, which is ORed together
  520. to allow compile-time dead code elimination to remove the whole of
  521. lib/args.c if nothing currently enabled is using it.)<p>
  522. <p>Each NEWTOY and OLDTOY macro contains the command name, command line
  523. option string (telling lib/args.c how to parse command line options for
  524. this command), recommended install location, and miscelaneous data such
  525. as whether this command should retain root permissions if installed suid.</p>
  526. </li>
  527. <li><p><b>toys/oldtoys.h</b> - Macros with the command line option parsing
  528. string for each NEWTOY. This allows an OLDTOY that's just an alias for an
  529. existing command to refer to the existing option string instead of
  530. having to repeat it.</p>
  531. </li>
  532. </ul>
  533. <a name="lib">
  534. <h2>Directory lib/</h2>
  535. <p>TODO: document lots more here.</p>
  536. <p>lib: getmountlist(), error_msg/error_exit, xmalloc(),
  537. strlcpy(), xexec(), xopen()/xread(), xgetcwd(), xabspath(), find_in_path(),
  538. itoa().</p>
  539. <a name="lib_xwrap"><h3>lib/xwrap.c</h3>
  540. <p>Functions prefixed with the letter x call perror_exit() when they hit
  541. errors, to eliminate common error checking. This prints an error message
  542. and the strerror() string for the errno encountered.</p>
  543. <p>We replaced exit(), _exit(), and atexit() with xexit(), _xexit(), and
  544. sigatexit(). This gives _xexit() the option to siglongjmp(toys.rebound, 1)
  545. instead of exiting, lets xexit() report stdout flush failures to stderr
  546. and change the exit code to indicate error, lets our toys.exit function
  547. change happen for signal exit paths and lets us remove the functions
  548. after we've called them.</p>
  549. <p>You can intercept our exit by assigning a sigsetjmp/siglongjmp buffer to
  550. toys.rebound (set it back to zero to restore the default behavior).
  551. If you do this, cleaning up resource leaks is your problem.</p>
  552. <ul>
  553. <li><b>void xstrncpy(char *dest, char *src, size_t size)</b></li>
  554. <li><p><b><p>void _xexit(void)</b></p>
  555. <p>Calls siglongjmp(toys.rebound, 1), or else _exit(toys.exitval). This
  556. lets you ignore errors with the NO_EXIT() macro wrapper, or intercept
  557. them with WOULD_EXIT().</p>
  558. <li><b><p>void xexit(void)</b></p>
  559. <p>Calls toys.xexit functions (if any) and flushes stdout/stderr (reporting
  560. failure to write to stdout both to stderr and in the exit code), then
  561. calls _xexit().</p>
  562. </li>
  563. <li><b>void *xmalloc(size_t size)</b></li>
  564. <li><b>void *xzalloc(size_t size)</b></li>
  565. <li><b>void *xrealloc(void *ptr, size_t size)</b></li>
  566. <li><b>char *xstrndup(char *s, size_t n)</b></li>
  567. <li><b>char *xstrdup(char *s)</b></li>
  568. <li><b>char *xmprintf(char *format, ...)</b></li>
  569. <li><b>void xprintf(char *format, ...)</b></li>
  570. <li><b>void xputs(char *s)</b></li>
  571. <li><b>void xputc(char c)</b></li>
  572. <li><b>void xflush(void)</b></li>
  573. <li><b>pid_t xfork(void)</b></li>
  574. <li><b>void xexec_optargs(int skip)</b></li>
  575. <li><b>void xexec(char **argv)</b></li>
  576. <li><b>pid_t xpopen(char **argv, int *pipes)</b></li>
  577. <li><b>int xpclose(pid_t pid, int *pipes)</b></li>
  578. <li><b>void xaccess(char *path, int flags)</b></li>
  579. <li><b>void xunlink(char *path)</b></li>
  580. <li><p><b>int xcreate(char *path, int flags, int mode)<br />
  581. int xopen(char *path, int flags)</b></p>
  582. <p>The xopen() and xcreate() functions open an existing file (exiting if
  583. it's not there) and create a new file (exiting if it can't).</p>
  584. <p>They default to O_CLOEXEC so the filehandles aren't passed on to child
  585. processes. Feed in O_CLOEXEC to disable this.</p>
  586. </li>
  587. <li><p><b>void xclose(int fd)</b></p>
  588. <p>Because NFS is broken, and won't necessarily perform the requested
  589. operation (and report the error) until you close the file. Of course, this
  590. being NFS, it's not guaranteed to report the error there either, but it
  591. _can_.</p>
  592. <p>Nothing else ever reports an error on close, everywhere else it's just a
  593. VFS operation freeing some resources. NFS is _special_, in a way that
  594. other network filesystems like smbfs and v9fs aren't..</p>
  595. </li>
  596. <li><b>int xdup(int fd)</b></li>
  597. <li><p><b>size_t xread(int fd, void *buf, size_t len)</b></p>
  598. <p>Can return 0, but not -1.</p>
  599. </li>
  600. <li><p><b>void xreadall(int fd, void *buf, size_t len)</b></p>
  601. <p>Reads the entire len-sized buffer, retrying to complete short
  602. reads. Exits if it can't get enough data.</p></li>
  603. <li><p><b>void xwrite(int fd, void *buf, size_t len)</b></p>
  604. <p>Retries short writes, exits if can't write the entire buffer.</p></li>
  605. <li><b>off_t xlseek(int fd, off_t offset, int whence)</b></li>
  606. <li><b>char *xgetcwd(void)</b></li>
  607. <li><b>void xstat(char *path, struct stat *st)</b></li>
  608. <li><p><b>char *xabspath(char *path, int exact) </b></p>
  609. <p>After several years of
  610. <a href=http://landley.net/notes-2007.html#18-06-2007>wrestling</a>
  611. <a href=http://landley.net/notes-2008.html#19-01-2008>with</a> realpath(),
  612. I broke down and <a href=http://landley.net/notes-2012.html#20-11-2012>wrote
  613. my own</a> implementation that doesn't use the one in libc. As I explained:
  614. <blockquote><p>If the path ends with a broken link,
  615. readlink -f should show where the link points to, not where the broken link
  616. lives. (The point of readlink -f is "if I write here, where would it attempt
  617. to create a file".) The problem is, realpath() returns NULL for a path ending
  618. with a broken link, and I can't beat different behavior out of code locked
  619. away in libc.</p></blockquote>
  620. <p>
  621. </li>
  622. <li><b>void xchdir(char *path)</b></li>
  623. <li><b>void xchroot(char *path)</b></li>
  624. <li><p><b>struct passwd *xgetpwuid(uid_t uid)<br />
  625. struct group *xgetgrgid(gid_t gid)<br />
  626. struct passwd *xgetpwnam(char *name)</b></p>
  627. </li>
  628. <li><b>void xsetuser(struct passwd *pwd)</b></li>
  629. <li><b>char *xreadlink(char *name)</b></li>
  630. <li><b>char *xreadfile(char *name, char *buf, off_t len)</b></li>
  631. <li><b>int xioctl(int fd, int request, void *data)</b></li>
  632. <li><b>void xpidfile(char *name)</b></li>
  633. <li><b>void xsendfile(int in, int out)</b></li>
  634. <li><b>long xparsetime(char *arg, long units, long *fraction)</b></li>
  635. <li><b>void xregcomp(regex_t *preg, char *regex, int cflags)</b></li>
  636. </ul>
  637. <a name="lib_lib"><h3>lib/lib.c</h3>
  638. <p>Eight gazillion common functions, see lib/lib.h for the moment:</p>
  639. <h3>lib/portability.h</h3>
  640. <p>This file is automatically included from the top of toys.h, and smooths
  641. over differences between platforms (hardware targets, compilers, C libraries,
  642. operating systems, etc).</p>
  643. <p>This file provides SWAP macros (SWAP_BE16(x) and SWAP_LE32(x) and so on).</p>
  644. <p>A macro like SWAP_LE32(x) means "The value in x is stored as a little
  645. endian 32 bit value, so perform the translation to/from whatever the native
  646. 32-bit format is". You do the swap once on the way in, and once on the way
  647. out. If your target is already little endian, the macro is a NOP.</p>
  648. <p>The SWAP macros come in BE and LE each with 16, 32, and 64 bit versions.
  649. In each case, the name of the macro refers to the _external_ representation,
  650. and converts to/from whatever your native representation happens to be (which
  651. can vary depending on what you're currently compiling for).</p>
  652. <a name="lib_llist"><h3>lib/llist.c</h3>
  653. <p>Some generic single and doubly linked list functions, which take
  654. advantage of a couple properties of C:</p>
  655. <ul>
  656. <li><p>Structure elements are laid out in memory in the order listed, and
  657. the first element has no padding. This means you can always treat (typecast)
  658. a pointer to a structure as a pointer to the first element of the structure,
  659. even if you don't know anything about the data following it.</p></li>
  660. <li><p>An array of length zero at the end of a structure adds no space
  661. to the sizeof() the structure, but if you calculate how much extra space
  662. you want when you malloc() the structure it will be available at the end.
  663. Since C has no bounds checking, this means each struct can have one variable
  664. length array.</p></li>
  665. </ul>
  666. <p>Toybox's list structures always have their <b>next</b> pointer as
  667. the first entry of each struct, and singly linked lists end with a NULL pointer.
  668. This allows generic code to traverse such lists without knowing anything
  669. else about the specific structs composing them: if your pointer isn't NULL
  670. typecast it to void ** and dereference once to get the next entry.</p>
  671. <p><b>lib/lib.h</b> defines three structure types:</p>
  672. <ul>
  673. <li><p><b>struct string_list</b> - stores a single string (<b>char str[0]</b>),
  674. memory for which is allocated as part of the node. (I.E. llist_traverse(list,
  675. free); can clean up after this type of list.)</p></li>
  676. <li><p><b>struct arg_list</b> - stores a pointer to a single string
  677. (<b>char *arg</b>) which is stored in a separate chunk of memory.</p></li>
  678. <li><p><b>struct double_list</b> - has a second pointer (<b>struct double_list
  679. *prev</b> along with a <b>char *data</b> for payload.</p></li>
  680. </ul>
  681. <b>List Functions</b>
  682. <ul>
  683. <li><p>void *<b>llist_pop</b>(void **list) - advances through a list ala
  684. <b>node = llist_pop(&list);</b> This doesn't modify the list contents,
  685. but does advance the pointer you feed it (which is why you pass the _address_
  686. of that pointer, not the pointer itself).</p></li>
  687. <li><p>void <b>llist_traverse</b>(void *list, void (*using)(void *data)) -
  688. iterate through a list calling a function on each node.</p></li>
  689. <li><p>struct double_list *<b>dlist_add</b>(struct double_list **llist, char *data)
  690. - append an entry to a circular linked list.
  691. This function allocates a new struct double_list wrapper and returns the
  692. pointer to the new entry (which you can usually ignore since it's llist->prev,
  693. but if llist was NULL you need it). The argument is the ->data field for the
  694. new node.</p></li>
  695. <ul><li><p>void <b>dlist_add_nomalloc</b>(struct double_list **llist,
  696. struct double_list *new) - append existing struct double_list to
  697. list, does not allocate anything.</p></li></ul>
  698. </ul>
  699. <b>List code trivia questions:</b>
  700. <ul>
  701. <li><p><b>Why do arg_list and double_list contain a char * payload instead of
  702. a void *?</b> - Because you always have to typecast a void * to use it, and
  703. typecasting a char * does no harm. Since strings are the most common
  704. payload, and doing math on the pointer ala
  705. "(type *)(ptr+sizeof(thing)+sizeof(otherthing))" requires ptr to be char *
  706. anyway (at least according to the C standard), defaulting to char * saves
  707. a typecast.</p>
  708. </li>
  709. <li><p><b>Why do the names ->str, ->arg, and ->data differ?</b> - To force
  710. you to keep track of which one you're using, calling free(node->str) would
  711. be bad, and _failing_ to free(node->arg) leaks memory.</p></li>
  712. <li><p><b>Why does llist_pop() take a void * instead of void **?</b> -
  713. because the stupid compiler complains about "type punned pointers" when
  714. you typecast and dereference on the same line,
  715. due to insane FSF developers hardwiring limitations of their optimizer
  716. into gcc's warning system. Since C automatically typecasts any other
  717. pointer type to and from void *, the current code works fine. It's sad that it
  718. won't warn you if you forget the &, but the code crashes pretty quickly in
  719. that case.</p></li>
  720. <li><p><b>How do I assemble a singly-linked-list in order?</b> - use
  721. a double_list, dlist_add() your entries, and then call dlist_terminate(list)
  722. to break the circle when done (turning the last ->next and the first ->prev
  723. into NULLs).</p>
  724. </ul>
  725. <a name="lib_args"><h3>lib/args.c</h3>
  726. <p>Toybox's main.c automatically parses command line options before calling the
  727. command's main function. Option parsing starts in get_optflags(), which stores
  728. results in the global structures "toys" (optflags and optargs) and "this".</p>
  729. <p>The option parsing infrastructure stores a bitfield in toys.optflags to
  730. indicate which options the current command line contained, and defines FLAG
  731. macros code can use to check whether each argument's bit is set. Arguments
  732. attached to those options are saved into the command's global structure
  733. ("this"). Any remaining command line arguments are collected together into
  734. the null-terminated array toys.optargs, with the length in toys.optc. (Note
  735. that toys.optargs does not contain the current command name at position zero,
  736. use "toys.which->name" for that.) The raw command line arguments get_optflags()
  737. parsed are retained unmodified in toys.argv[].</p>
  738. <p>Toybox's option parsing logic is controlled by an "optflags" string, using
  739. a format reminiscent of getopt's optargs but with several important differences.
  740. Toybox does not use the getopt()
  741. function out of the C library, get_optflags() is an independent implementation
  742. which doesn't permute the original arguments (and thus doesn't change how the
  743. command is displayed in ps and top), and has many features not present in
  744. libc optargs() (such as the ability to describe long options in the same string
  745. as normal options).</p>
  746. <p>Each command's NEWTOY() macro has an optflags string as its middle argument,
  747. which sets toy_list.options for that command to tell get_optflags() what
  748. command line arguments to look for, and what to do with them.
  749. If a command has no option
  750. definition string (I.E. the argument is NULL), option parsing is skipped
  751. for that command, which must look at the raw data in toys.argv to parse its
  752. own arguments. (If no currently enabled command uses option parsing,
  753. get_optflags() is optimized out of the resulting binary by the compiler's
  754. --gc-sections option.)</p>
  755. <p>You don't have to free the option strings, which point into the environment
  756. space (I.E. the string data is not copied). A TOYFLAG_NOFORK command
  757. that uses the linked list type "*" should free the list objects but not
  758. the data they point to, via "llist_free(TT.mylist, NULL);". (If it's not
  759. NOFORK, exit() will free all the malloced data anyway unless you want
  760. to implement a CONFIG_TOYBOX_FREE cleanup for it.)</p>
  761. <h4>Optflags format string</h4>
  762. <p>Note: the optflags option description string format is much more
  763. concisely described by a large comment at the top of lib/args.c.</p>
  764. <p>The general theory is that letters set optflags, and punctuation describes
  765. other actions the option parsing logic should take.</p>
  766. <p>For example, suppose the command line <b>command -b fruit -d walrus -a 42</b>
  767. is parsed using the optflags string "<b>a#b:c:d</b>". (I.E.
  768. toys.which->options="a#b:c:d" and argv = ["command", "-b", "fruit", "-d",
  769. "walrus", "-a", "42"]). When get_optflags() returns, the following data is
  770. available to command_main():
  771. <ul>
  772. <li><p>In <b>struct toys</b>:
  773. <ul>
  774. <li>toys.optflags = 13; // FLAG_a = 8 | FLAG_b = 4 | FLAG_d = 1</li>
  775. <li>toys.optargs[0] = "walrus"; // leftover argument</li>
  776. <li>toys.optargs[1] = NULL; // end of list</li>
  777. <li>toys.optc = 1; // there was 1 leftover argument</li>
  778. <li>toys.argv[] = {"-b", "fruit", "-d", "walrus", "-a", "42"}; // The original command line arguments
  779. </ul>
  780. <p></li>
  781. <li><p>In <b>union this</b> (treated as <b>long this[]</b>):
  782. <ul>
  783. <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>
  784. <li>this[1] = (long)"fruit"; // argument to -b</li>
  785. <li>this[2] = 42; // argument to -a</li>
  786. </ul>
  787. </p></li>
  788. </ul>
  789. <p>If the command's globals are:</p>
  790. <blockquote><pre>
  791. GLOBALS(
  792. char *c;
  793. char *b;
  794. long a;
  795. )
  796. </pre></blockquote>
  797. <p>That would mean TT.c == NULL, TT.b == "fruit", and TT.a == 42. (Remember,
  798. each entry that receives an argument must be a long or pointer, to line up
  799. with the array position. Right to left in the optflags string corresponds to
  800. top to bottom in GLOBALS().</p>
  801. <p>Put globals not filled out by the option parsing logic at the end of the
  802. GLOBALS block. Common practice is to list the options one per line (to
  803. make the ordering explicit, first to last in globals corresponds to right
  804. to left in the option string), then leave a blank line before any non-option
  805. globals.</p>
  806. <p><b>long toys.optflags</b></p>
  807. <p>Each option in the optflags string corresponds to a bit position in
  808. toys.optflags, with the same value as a corresponding binary digit. The
  809. rightmost argument is (1<<0), the next to last is (1<<1) and so on. If
  810. the option isn't encountered while parsing argv[], its bit remains 0.</p>
  811. <p>Each option -x has a FLAG_x macro for the command letter. Bare --longopts
  812. with no corresponding short option have a FLAG_longopt macro for the long
  813. optionname. Commands enable these macros by #defining FOR_commandname before
  814. #including <toys.h>. When multiple commands are implemented in the same
  815. source file, you can switch flag contexts later in the file by
  816. #defining CLEANUP_oldcommand and #defining FOR_newcommand, then
  817. #including <generated/flags.h>.</p>
  818. <p>Options disabled in the current configuration (wrapped in
  819. a USE_BLAH() macro for a CONFIG_BLAH that's switched off) have their
  820. corresponding FLAG macro set to zero, so code checking them ala
  821. if (toys.optargs & FLAG_x) gets optimized out via dead code elimination.
  822. #defining FORCE_FLAGS when switching flag context disables this
  823. behavior: the flag is never zero even if the config is disabled. This
  824. allows code shared between multiple commands to use the same flag
  825. values, as long as the common flags match up right to left in both option
  826. strings.</p>
  827. <p>For example,
  828. the optflags string "abcd" would parse the command line argument "-c" to set
  829. optflags to 2, "-a" would set optflags to 8, "-bd" would set optflags to
  830. 6 (I.E. 4|2), and "-a -c" would set optflags to 10 (2|8). To check if -c
  831. was encountered, code could test: if (toys.optflags & FLAG_c) printf("yup");
  832. (See the toys/examples directory for more.)</p>
  833. <p>Only letters are relevant to optflags, punctuation is skipped: in the
  834. string "a*b:c#d", d=1, c=2, b=4, a=8. The punctuation after a letter
  835. usually indicate that the option takes an argument.</p>
  836. <p>Since toys.optflags is an unsigned int, it only stores 32 bits. (Which is
  837. the amount a long would have on 32-bit platforms anyway; 64 bit code on
  838. 32 bit platforms is too expensive to require in common code used by almost
  839. all commands.) Bit positions beyond the 1<<31 aren't recorded, but
  840. parsing higher options can still set global variables.</p>
  841. <p><b>Automatically setting global variables from arguments (union this)</b></p>
  842. <p>The following punctuation characters may be appended to an optflags
  843. argument letter, indicating the option takes an additional argument:</p>
  844. <ul>
  845. <li><b>:</b> - plus a string argument, keep most recent if more than one.</li>
  846. <li><b>*</b> - plus a string argument, appended to a linked list.</li>
  847. <li><b>@</b> - plus an occurrence counter (stored in a long)</li>
  848. <li><b>#</b> - plus a signed long argument.
  849. <li><b>-</b> - plus a signed long argument defaulting to negative (start argument with + to force a positive value).</li>
  850. <li><b>.</b> - plus a floating point argument (if CFG_TOYBOX_FLOAT).</li>
  851. <ul>The following can be appended to a float or double:
  852. <li><b>&lt;123</b> - error if argument is less than this</li>
  853. <li><b>&gt;123</b> - error if argument is greater than this</li>
  854. <li><b>=123</b> - default value if argument not supplied</li>
  855. </ul>
  856. </ul>
  857. <p><b>GLOBALS</b></p>
  858. <p>Options which have an argument fill in the corresponding slot in the global
  859. union "this" (see generated/globals.h), treating it as an array of longs
  860. with the rightmost saved in this[0]. As described above, using "a*b:c#d",
  861. "-c 42" would set this[0] = 42; and "-b 42" would set this[1] = "42"; each
  862. slot is left NULL if the corresponding argument is not encountered.</p>
  863. <p>This behavior is useful because the LP64 standard ensures long and pointer
  864. are the same size. C99 guarantees structure members will occur in memory
  865. in the same order they're declared, and that padding won't be inserted between
  866. consecutive variables of register size. Thus the first few entries can
  867. be longs or pointers corresponding to the saved arguments.</p>
  868. <p>The main downside is that numeric arguments ("#" and "-" format)
  869. are limited to +- 2 billion on 32 bit platforms (the "truncate -s 8G"
  870. problem), because long is only 64 bits on 64 bit hosts, so the capabilities
  871. of some tools differ when built in 32 bit vs 64 bit mode. Fixing this
  872. kind of ugly and even embedded designs are slowly moving to 64 bits,
  873. so our current plan is to document the problem and wait it out. (If
  874. "x32 mode" and similar becomes popular enough, we may revisit this
  875. decision.)</p>
  876. <p>See toys/example/*.c for longer examples of parsing options into the
  877. GLOBALS block.</p>
  878. <p><b>char *toys.optargs[]</b></p>
  879. <p>Command line arguments in argv[] which are not consumed by option parsing
  880. (I.E. not recognized either as -flags or arguments to -flags) will be copied
  881. to toys.optargs[], with the length of that array in toys.optc.
  882. (When toys.optc is 0, no unrecognized command line arguments remain.)
  883. The order of entries is preserved, and as with argv[] this new array is also
  884. terminated by a NULL entry.</p>
  885. <p>Option parsing can require a minimum or maximum number of optargs left
  886. over, by adding "<1" (read "at least one") or ">9" ("at most nine") to the
  887. start of the optflags string.</p>
  888. <p>The special argument "--" terminates option parsing, storing all remaining
  889. arguments in optargs. The "--" itself is consumed.</p>
  890. <p><b>Other optflags control characters</b></p>
  891. <p>The following characters may occur at the start of each command's
  892. optflags string, before any options that would set a bit in toys.optflags:</p>
  893. <ul>
  894. <li><b>^</b> - stop at first nonoption argument (for nice, xargs...)</li>
  895. <li><b>?</b> - allow unknown arguments (pass non-option arguments starting
  896. with - through to optargs instead of erroring out).</li>
  897. <li><b>&amp;</b> - the first argument has imaginary dash (ala tar/ps. If given twice, all arguments have imaginary dash.)</li>
  898. <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>
  899. <li><b>&gt;</b> - must be followed by a decimal digit indicating at most this many leftover arguments allowed (default MAX_INT)</li>
  900. </ul>
  901. <p>The following characters may be appended to an option character, but do
  902. not by themselves indicate an extra argument should be saved in this[].
  903. (Technically any character not recognized as a control character sets an
  904. optflag, but letters are never control characters.)</p>
  905. <ul>
  906. <li><b>^</b> - stop parsing options after encountering this option, everything else goes into optargs.</li>
  907. <li><b>|</b> - this option is required. If more than one marked, only one is required.</li>
  908. </ul>
  909. <p>The following may be appended to a float or double:</p>
  910. <ul>
  911. <li><b>&lt;123</b> - error if argument is less than this</li>
  912. <li><b>&gt;123</b> - error if argument is greater than this</li>
  913. <li><b>=123</b> - default value if argument not supplied</li>
  914. </ul>
  915. <p>Option parsing only understands <>= after . when CFG_TOYBOX_FLOAT
  916. is enabled. (Otherwise the code to determine where floating point constants
  917. end drops out. When disabled, it can reserve a global data slot for the
  918. argument so offsets won't change, but will never fill it out.) You can handle
  919. this by using the USE_BLAH() macros with C string concatenation, ala:</p>
  920. <blockquote>"abc." USE_TOYBOX_FLOAT("<1.23>4.56=7.89") "def"</blockquote>
  921. <p><b>--longopts</b></p>
  922. <p>The optflags string can contain long options, which are enclosed in
  923. parentheses. They may be appended to an existing option character, in
  924. which case the --longopt is a synonym for that option, ala "a:(--fred)"
  925. which understands "-a blah" or "--fred blah" as synonyms.</p>
  926. <p>Longopts may also appear before any other options in the optflags string,
  927. in which case they have no corresponding short argument, but instead set
  928. their own bit based on position. So for "(walrus)#(blah)xy:z", "command
  929. --walrus 42" would set toys.optflags = 16 (-z = 1, -y = 2, -x = 4, --blah = 8)
  930. and would assign this[1] = 42;</p>
  931. <p>A short option may have multiple longopt synonyms, "a(one)(two)", but
  932. each "bare longopt" (ala "(one)(two)abc" before any option characters)
  933. always sets its own bit (although you can group them with +X).</p>
  934. <p>Only bare longopts have a FLAG_ macro with the longopt name
  935. (ala --fred would #define FLAG_fred). Other longopts use the short
  936. option's FLAG macro to test the toys.optflags bit.</p>
  937. <p>Options with a semicolon ";" after their data type can only set their
  938. corresponding GLOBALS() entry via "--longopt=value". For example, option
  939. string "x(boing): y" would set TT.x if it saw "--boing=value", but would
  940. treat "--boing value" as setting FLAG_x in toys.optargs, leaving TT.x NULL,
  941. and keeping "value" in toys.optargs[]. (This lets "ls --color" and
  942. "ls --color=auto" both work.)</p>
  943. <p><b>[groups]</b></p>
  944. <p>At the end of the option string, square bracket groups can define
  945. relationships between existing options. (This only applies to short
  946. options, bare --longopts can't participate.)</p>
  947. <p>The first character of the group defines the type, the remaining
  948. characters are options it applies to:</p>
  949. <ul>
  950. <li><b>-</b> - Exclusive, switch off all others in this group.</li>
  951. <li><b>+</b> - Inclusive, switch on all others in this group.</li>
  952. <li><b>!</b> - Error, fail if more than one defined.</li>
  953. </ul>
  954. <p>So "abc[-abc]" means -ab = -b, -ba = -a, -abc = -c. "abc[+abc]"
  955. means -ab=-abc, -c=-abc, and "abc[!abc] means -ab calls error_exit("no -b
  956. with -a"). Note that [-] groups clear the GLOBALS option slot of
  957. options they're switching back off, but [+] won't set options it didn't see
  958. (just the optflags).</p>
  959. <p><b>whitespace</b></p>
  960. <p>Arguments may occur with or without a space (I.E. "-a 42" or "-a42").
  961. The command line argument "-abc" may be interepreted many different ways:
  962. the optflags string "cba" sets toys.optflags = 7, "c:ba" sets toys.optflags=4
  963. and saves "ba" as the argument to -c, and "cb:a" sets optflags to 6 and saves
  964. "c" as the argument to -b.</p>
  965. <p>Note that &amp; changes whitespace handling, so that the command line
  966. "tar cvfCj outfile.tar.bz2 topdir filename" is parsed the same as
  967. "tar filename -c -v -j -f outfile.tar.bz2 -C topdir". Note that "tar -cvfCj
  968. one two three" would equal "tar -c -v -f Cj one two three". (This matches
  969. historical usage.)</p>
  970. <p>Appending a space to the option in the option string ("a: b") makes it
  971. require a space, I.E. "-ab" is interpreted as "-a" "-b". That way "kill -stop"
  972. differs from "kill -s top".</p>
  973. <p>Appending ; to a longopt in the option string makes its argument optional,
  974. and only settable with =, so in ls "(color):;" can accept "ls --color" and
  975. "ls --color=auto" without complaining that the first has no argument.</p>
  976. <a name="lib_dirtree"><h3>lib/dirtree.c</h3>
  977. <p>The directory tree traversal code should be sufficiently generic
  978. that commands never need to use readdir(), scandir(), or the fts.h family
  979. of functions.</p>
  980. <p>These functions do not call chdir() or rely on PATH_MAX. Instead they
  981. use openat() and friends, using one filehandle per directory level to
  982. recurse into subdirectories. (I.E. they can descend 1000 directories deep
  983. if setrlimit(RLIMIT_NOFILE) allows enough open filehandles, and the default
  984. in /proc/self/limits is generally 1024.)</p>
  985. <p>There are two main ways to use dirtree: 1) assemble a tree of nodes
  986. representing a snapshot of directory state and traverse them using the
  987. ->next and ->child pointers, or 2) traverse the tree calling a callback
  988. function on each entry, and freeing its node afterwards. (You can also
  989. combine the two, using the callback as a filter to determine which nodes
  990. to keep.)</p>
  991. <p>The basic dirtree functions are:</p>
  992. <ul>
  993. <li><p><b>struct dirtree *dirtree_read(char *path, int (*callback)(struct
  994. dirtree node))</b> - recursively read files and directories, calling
  995. callback() on each, and returning a tree of saved nodes (if any).
  996. If path doesn't exist, returns DIRTREE_ABORTVAL. If callback is NULL,
  997. returns a single node at that path.</p>
  998. <li><p><b>dirtree_notdotdot(struct dirtree *new)</b> - standard callback
  999. which discards "." and ".." entries and returns DIRTREE_SAVE|DIRTREE_RECURSE
  1000. for everything else. Used directly, this assembles a snapshot tree of
  1001. the contents of this directory and its subdirectories
  1002. to be processed after dirtree_read() returns (by traversing the
  1003. struct dirtree's ->next and ->child pointers from the returned root node).</p>
  1004. <li><p><b>dirtree_path(struct dirtree *node, int *plen)</b> - malloc() a
  1005. string containing the path from the root of this tree to this node. If
  1006. plen isn't NULL then *plen is how many extra bytes to malloc at the end
  1007. of string.</p></li>
  1008. <li><p><b>dirtree_parentfd(struct dirtree *node)</b> - return fd of
  1009. directory containing this node, for use with openat() and such.</p></li>
  1010. </ul>
  1011. <p>The <b>dirtree_read()</b> function is the standard way to start
  1012. directory traversal. It takes two arguments: a starting path for
  1013. the root of the tree, and a callback function. The callback() is called
  1014. on each directory entry, its argument is a fully populated
  1015. <b>struct dirtree *</b> (from lib/lib.h) describing the node, and its
  1016. return value tells the dirtree infrastructure what to do next.</p>
  1017. <p>(There's also a three argument version,
  1018. <b>dirtree_flagread(char *path, int flags, int (*callback)(struct
  1019. dirtree node))</b>, which lets you apply flags like DIRTREE_SYMFOLLOW and
  1020. DIRTREE_SHUTUP to reading the top node, but this only affects the top node.
  1021. Child nodes use the flags returned by callback().</p>
  1022. <p><b>struct dirtree</b></p>
  1023. <p>Each struct dirtree node contains <b>char name[]</b> and <b>struct stat
  1024. st</b> entries describing a file, plus a <b>char *symlink</b>
  1025. which is NULL for non-symlinks.</p>
  1026. <p>During a callback function, the <b>int dirfd</b> field of directory nodes
  1027. contains a directory file descriptor (for use with the openat() family of
  1028. functions). This isn't usually used directly, intstead call dirtree_parentfd()
  1029. on the callback's node argument. The <b>char again</b> field is 0 for the
  1030. first callback on a node, and 1 on the second callback (triggered by returning
  1031. DIRTREE_COMEAGAIN on a directory, made after all children have been processed).
  1032. </p>
  1033. <p>Users of this code may put anything they like into the <b>long extra</b>
  1034. field. For example, "cp" and "mv" use this to store a dirfd for the destination
  1035. directory (and use DIRTREE_COMEAGAIN to get the second callback so they can
  1036. close(node->extra) to avoid running out of filehandles).
  1037. This field is not directly used by the dirtree code, and
  1038. thanks to LP64 it's large enough to store a typecast pointer to an
  1039. arbitrary struct.</p>
  1040. <p>The return value of the callback combines flags (with boolean or) to tell
  1041. the traversal infrastructure how to behave:</p>
  1042. <ul>
  1043. <li><p><b>DIRTREE_SAVE</b> - Save this node, assembling a tree. (Without
  1044. this the struct dirtree is freed after the callback returns. Filtering out
  1045. siblings is fine, but discarding a parent while keeping its child leaks
  1046. memory.)</p></li>
  1047. <li><p><b>DIRTREE_ABORT</b> - Do not examine any more entries in this
  1048. directory. (Does not propagate up tree: to abort entire traversal,
  1049. return DIRTREE_ABORT from parent callbacks too.)</p></li>
  1050. <li><p><b>DIRTREE_RECURSE</b> - Examine directory contents. Ignored for
  1051. non-directory entries. The remaining flags only take effect when
  1052. recursing into the children of a directory.</p></li>
  1053. <li><p><b>DIRTREE_COMEAGAIN</b> - Call the callback on this node a second time
  1054. after examining all directory contents, allowing depth-first traversal.
  1055. On the second call, dirtree->again is nonzero.</p></li>
  1056. <li><p><b>DIRTREE_SYMFOLLOW</b> - follow symlinks when populating children's
  1057. <b>struct stat st</b> (by feeding a nonzero value to the symfollow argument of
  1058. dirtree_add_node()), which means DIRTREE_RECURSE treats symlinks to
  1059. directories as directories. (Avoiding infinite recursion is the callback's
  1060. problem: the non-NULL dirtree->symlink can still distinguish between
  1061. them. The "find" command follows ->parent up the tree to the root node
  1062. each time, checking to make sure that stat's dev and inode pair don't
  1063. match any ancestors.)</p></li>
  1064. </ul>
  1065. <p>Each struct dirtree contains three pointers (next, parent, and child)
  1066. to other struct dirtree.</p>
  1067. <p>The <b>parent</b> pointer indicates the directory
  1068. containing this entry; even when not assembling a persistent tree of
  1069. nodes the parent entries remain live up to the root of the tree while
  1070. child nodes are active. At the top of the tree the parent pointer is
  1071. NULL, meaning the node's name[] is either an absolute path or relative
  1072. to cwd. The function dirtree_parentfd() gets the directory file descriptor
  1073. for use with openat() and friends, returning AT_FDCWD at the top of tree.</p>
  1074. <p>The <b>child</b> pointer points to the first node of the list of contents of
  1075. this directory. If the directory contains no files, or the entry isn't
  1076. a directory, child is NULL.</p>
  1077. <p>The <b>next</b> pointer indicates sibling nodes in the same directory as this
  1078. node, and since it's the first entry in the struct the llist.c traversal
  1079. mechanisms work to iterate over sibling nodes. Each dirtree node is a
  1080. single malloc() (even char *symlink points to memory at the end of the node),
  1081. so llist_free() works but its callback must descend into child nodes (freeing
  1082. a tree, not just a linked list), plus whatever the user stored in extra.</p>
  1083. <p>The <b>dirtree_flagread</b>() function is a simple wrapper, calling <b>dirtree_add_node</b>()
  1084. to create a root node relative to the current directory, then calling
  1085. <b>dirtree_handle_callback</b>() on that node (which recurses as instructed by the callback
  1086. return flags). The flags argument primarily lets you
  1087. control whether or not to follow symlinks to the root node; symlinks
  1088. listed on the command line are often treated differently than symlinks
  1089. encountered during recursive directory traversal.
  1090. <p>The ls command not only bypasses this wrapper, but never returns
  1091. <b>DIRTREE_RECURSE</b> from the callback, instead calling <b>dirtree_recurse</b>() manually
  1092. from elsewhere in the program. This gives ls -lR manual control
  1093. of traversal order, which is neither depth first nor breadth first but
  1094. instead a sort of FIFO order requried by the ls standard.</p>
  1095. <a name="toys">
  1096. <h1><a href="#toys">Directory toys/</a></h1>
  1097. <p>This directory contains command implementations. Each command is a single
  1098. self-contained file. Adding a new command involves adding a single
  1099. file, and removing a command involves removing that file. Commands use
  1100. shared infrastructure from the lib/ and generated/ directories.</p>
  1101. <p>Currently there are five subdirectories under "toys/" containing "posix"
  1102. commands described in POSIX-2008, "lsb" commands described in the Linux
  1103. Standard Base 4.1, "other" commands not described by either standard,
  1104. "pending" commands awaiting cleanup (which default to "n" in menuconfig
  1105. because they don't necessarily work right yet), and "example" code showing
  1106. how toybox infrastructure works and providing template/skeleton files to
  1107. start new commands.</p>
  1108. <p>The only difference directory location makes is which menu the command
  1109. shows up in during "make menuconfig", the directories are otherwise identical.
  1110. Note that the commands exist within a single namespace at runtime, so you can't
  1111. have the same command in multiple subdirectories. (The build tries to fail
  1112. informatively when you do that.)</p>
  1113. <p>There is one more sub-menus in "make menuconfig" containing global
  1114. configuration options for toybox. This menu is defined in the top level
  1115. Config.in.</p>
  1116. <p>See <a href="#adding">adding a new command</a> for details on the
  1117. layout of a command file.</p>
  1118. <a name="scripts">
  1119. <h2>Directory scripts/</h2>
  1120. <p>Build infrastructure. The makefile calls scripts/make.sh for "make"
  1121. and scripts/install.sh for "make install".</p>
  1122. <p>There's also a test suite, "make test" calls make/test.sh, which runs all
  1123. the tests in make/test/*. You can run individual tests via
  1124. "scripts/test.sh command", or "TEST_HOST=1 scripts/test.sh command" to run
  1125. that test against the host implementation instead of the toybox one.</p>
  1126. <h3>scripts/cfg2files.sh</h3>
  1127. <p>Run .config through this filter to get a list of enabled commands, which
  1128. is turned into a list of files in toys via a sed invocation in the top level
  1129. Makefile.
  1130. </p>
  1131. <h2>Directory kconfig/</h2>
  1132. <p>Menuconfig infrastructure copied from the Linux kernel a long time ago
  1133. (version 2.6.16). See the
  1134. Linux kernel's Documentation/kbuild/kconfig-language.txt</p>
  1135. <!-- todo
  1136. Better OLDTOY and multiple command explanation. From Config.in:
  1137. <p>A command with multiple names (or multiple similar commands implemented in
  1138. the same .c file) should have config symbols prefixed with the name of their
  1139. C file. I.E. config symbol prefixes are NEWTOY() names. If OLDTOY() names
  1140. have config symbols they must be options (symbols with an underscore and
  1141. suffix) to the NEWTOY() name. (See generated/toylist.h)</p>
  1142. -->
  1143. <!--#include file="footer.html" -->